import { sendMessageToGemini } from './services/geminiService.ts';

declare global {
  interface Window {
    lucide?: {
      createIcons: () => void;
    };
  }
}

document.addEventListener('DOMContentLoaded', () => {
  // --- Icons Initialization ---
  if (window.lucide) {
    window.lucide.createIcons();
  }

  // --- Dark Mode Logic ---
  const themeToggle = document.getElementById('theme-toggle');
  const themeToggleMobile = document.getElementById('theme-toggle-mobile');
  const html = document.documentElement;
  const themeIcon = document.getElementById('theme-icon');
  const themeIconMobile = document.getElementById('theme-icon-mobile');

  function updateIcons(isDark: boolean) {
    const iconName = isDark ? 'sun' : 'moon';
    if (themeIcon) themeIcon.setAttribute('data-lucide', iconName);
    if (themeIconMobile) themeIconMobile.setAttribute('data-lucide', iconName);
    if (window.lucide) window.lucide.createIcons();
  }

  function setDark(isDark: boolean) {
    if (isDark) {
      html.classList.add('dark');
      localStorage.setItem('theme', 'dark');
    } else {
      html.classList.remove('dark');
      localStorage.setItem('theme', 'light');
    }
    updateIcons(isDark);
  }

  // Init Theme
  const savedTheme = localStorage.getItem('theme');
  const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
  if (savedTheme === 'dark' || (!savedTheme && prefersDark)) {
    setDark(true);
  } else {
    setDark(false);
  }

  [themeToggle, themeToggleMobile].forEach(btn => {
    if (btn) {
      btn.addEventListener('click', () => {
        setDark(!html.classList.contains('dark'));
      });
    }
  });

  // --- Mobile Menu ---
  const menuBtn = document.getElementById('menu-btn');
  const mobileMenu = document.getElementById('mobile-menu');
  const mobileLinks = document.querySelectorAll('.mobile-link');

  if (menuBtn && mobileMenu) {
    menuBtn.addEventListener('click', () => {
      mobileMenu.classList.toggle('hidden');
    });

    mobileLinks.forEach(link => {
      link.addEventListener('click', () => {
        mobileMenu.classList.add('hidden');
      });
    });
  }

  // --- Chat Widget Logic ---
  const toggleChatBtn = document.getElementById('toggle-chat-btn');
  const closeChatBtn = document.getElementById('close-chat-btn');
  const chatWindow = document.getElementById('chat-window');
  const chatForm = document.getElementById('chat-form');
  const chatInput = document.getElementById('chat-input') as HTMLInputElement;
  const chatMessages = document.getElementById('chat-messages');

  let chatHistory = [
    { role: 'model', parts: [{ text: 'Olá! Sou seu assistente virtual de saúde. Tem alguma dúvida sobre carência, reembolso ou qual operadora escolher?' }] }
  ];

  function toggleChat() {
    if (chatWindow && toggleChatBtn) {
        chatWindow.classList.toggle('hidden');
        toggleChatBtn.classList.toggle('hidden');
        if (!chatWindow.classList.contains('hidden') && chatMessages) {
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
    }
  }

  if (toggleChatBtn) toggleChatBtn.addEventListener('click', toggleChat);
  if (closeChatBtn) closeChatBtn.addEventListener('click', toggleChat);

  function addMessage(text: string, isUser: boolean, isError = false) {
    if (!chatMessages) return;
    const div = document.createElement('div');
    div.className = `flex ${isUser ? 'justify-end' : 'justify-start'}`;
    
    const bubble = document.createElement('div');
    bubble.className = `max-w-[80%] p-3 rounded-lg text-sm shadow-sm ${
      isUser 
        ? 'bg-primary-600 text-white rounded-tr-none' 
        : isError 
          ? 'bg-red-100 text-red-800 border border-red-200 rounded-tl-none'
          : 'bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-200 border border-gray-200 dark:border-gray-600 rounded-tl-none'
    }`;
    bubble.textContent = text;
    
    div.appendChild(bubble);
    chatMessages.appendChild(div);
    chatMessages.scrollTop = chatMessages.scrollHeight;
  }

  if (chatForm) {
    chatForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      // Ensure chatInput exists (though casting above handles strict types, runtime check is safer)
      if (!chatInput) return;

      const text = chatInput.value.trim();
      if (!text) return;

      // Add User Message
      addMessage(text, true);
      chatInput.value = '';
      chatInput.disabled = true;

      // Add to history
      chatHistory.push({ role: 'user', parts: [{ text: text }] });

      // Show typing indicator (simple)
      const typingId = 'typing-' + Date.now();
      const typingDiv = document.createElement('div');
      typingDiv.id = typingId;
      typingDiv.className = 'flex justify-start';
      typingDiv.innerHTML = '<div class="bg-white dark:bg-gray-700 p-3 rounded-lg rounded-tl-none text-xs text-gray-500">Digitando...</div>';
      if (chatMessages) {
          chatMessages.appendChild(typingDiv);
          chatMessages.scrollTop = chatMessages.scrollHeight;
      }

      try {
        const responseText = await sendMessageToGemini(text, chatHistory);
        
        // Remove typing
        const typingEl = document.getElementById(typingId);
        if (typingEl) typingEl.remove();

        addMessage(responseText, false);
        chatHistory.push({ role: 'model', parts: [{ text: responseText }] });
      } catch (error) {
         const typingEl = document.getElementById(typingId);
         if (typingEl) typingEl.remove();
         addMessage("Desculpe, ocorreu um erro na comunicação. Tente novamente.", false, true);
      } finally {
        chatInput.disabled = false;
        chatInput.focus();
      }
    });
  }
});