/**
 * FLOWhatsapp — Message Scheduler Content Script
 * Handles scheduling, local storage persistence, UI overlay, and execution.
 */
(() => {
  'use strict';

  // Content scripts run at document_start. On a cold WhatsApp load Chrome can
  // execute us just before <html>/<head> is attached, so never append directly.
  function appendWhenDocumentReady(node) {
    const target = document.head || document.documentElement;
    if (target) {
      target.appendChild(node);
      return;
    }
    document.addEventListener('DOMContentLoaded', () => {
      const readyTarget = document.head || document.documentElement;
      if (readyTarget && !node.isConnected) readyTarget.appendChild(node);
    }, { once: true });
  }

  // CSS for the scheduler UI
  const STYLE_ID = 'flowhatsapp-scheduler-styles';
  if (!document.getElementById(STYLE_ID)) {
    const style = document.createElement('style');
    style.id = STYLE_ID;
    style.textContent = `
      #wf-schedule-btn {
        background: transparent;
        border: none;
        color: #cbd5e1;
        cursor: pointer;
        padding: 8px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        margin-right: 8px;
        transition: all 0.2s ease;
      }
      #wf-schedule-btn:hover {
        background: rgba(255, 255, 255, 0.08);
        color: #a78bfa;
      }
      
      /* Modal Styles */
      .wf-sched-modal-overlay {
        position: fixed; inset: 0; z-index: 999999;
        background: rgba(0, 0, 0, 0.85); backdrop-filter: blur(8px);
        display: flex; align-items: center; justify-content: center;
        font-family: 'Montserrat', -apple-system, sans-serif;
        color: #f1f5f9;
        animation: wfFadeIn 0.2s ease;
        padding: max(12px, env(safe-area-inset-top)) max(12px, env(safe-area-inset-right)) max(12px, env(safe-area-inset-bottom)) max(12px, env(safe-area-inset-left));
        overflow: auto; overscroll-behavior: contain; box-sizing: border-box;
      }
      .wf-sched-modal {
        background: #111b21; border: 1.5px solid #222e35; border-radius: 20px;
        width: 500px; max-width: 100%; max-height: 100%; overflow: auto; padding: 28px;
        box-shadow: 0 20px 45px rgba(0, 0, 0, 0.5), 0 0 30px rgba(167, 139, 250, 0.1);
        display: flex; flex-direction: column; gap: 20px;
        animation: wfScaleIn 0.3s cubic-bezier(0.16, 1, 0.3, 1);
      }
      @keyframes wfFadeIn { from { opacity: 0; } to { opacity: 1; } }
      @keyframes wfScaleIn { from { opacity: 0; transform: scale(0.95) translateY(10px); } to { opacity: 1; transform: none; } }
      
      .wf-sched-input, .wf-sched-textarea {
        width: 100%; background: #202c33; border: 1px solid #2a3942;
        border-radius: 10px; padding: 10px 14px; color: #e9edef;
        font-family: inherit; font-size: 14px; outline: none; box-sizing: border-box;
      }
      .wf-sched-input:focus, .wf-sched-textarea:focus {
        border-color: #a78bfa;
      }
      .wf-sched-btn-primary {
        background: #a78bfa; color: #111b21; border: none; border-radius: 10px;
        padding: 11px 20px; font-weight: 700; cursor: pointer; font-family: inherit;
        font-size: 14px; display: inline-flex; align-items: center; gap: 6px;
      }
      .wf-sched-btn-primary:hover { opacity: 0.95; }
      
      .wf-sched-tab-btn {
        background: transparent; border: none; color: #cbd5e1;
        padding: 8px 16px; cursor: pointer; font-family: inherit;
        font-size: 13px; font-weight: 600; border-bottom: 2px solid transparent;
      }
      .wf-sched-tab-btn.active {
        color: #a78bfa; border-bottom-color: #a78bfa;
      }
      
      .wf-sched-list {
        max-height: 200px; overflow-y: auto; display: flex; flex-direction: column; gap: 10px;
      }
      .wf-sched-item {
        background: #202c33; border: 1px solid #2a3942; border-radius: 10px;
        padding: 12px; display: flex; justify-content: space-between; align-items: center;
        font-size: 13px;
      }
      .wf-sched-del-btn {
        background: transparent; border: none; color: #ea580c; cursor: pointer; font-size: 16px;
      }
      @media (max-width: 480px) {
        .wf-sched-modal { padding: 20px; border-radius: 16px; gap: 16px; }
        .wf-sched-tab-btn { padding: 8px 10px; font-size: 12px; }
      }
    `;
    appendWhenDocumentReady(style);
  }

  // Active chat state variables
  let currentChatJid = '';
  let currentChatName = '';

  // Get current active chat from WhatsApp Web DOM
  function updateActiveChatInfo() {
    try {
      const header = document.querySelector('header[data-testid="conversation-header"]');
      if (!header) return;

      // Extract contact/group name
      const nameEl = header.querySelector('[title]');
      if (nameEl) {
        currentChatName = nameEl.getAttribute('title') || nameEl.textContent || '';
      }

      // Extract active chatId or search for matching JID
      // WPPConnect defines WPP.chat.getActiveChat() in page context.
      // We can also retrieve the target chatId by looking at the layout elements.
      const conversationSection = document.querySelector('[data-testid="conversation-panel-wrapper"]');
      if (conversationSection) {
        // Fallback or hook into active conversation class / ID.
      }
    } catch (_) {}
  }

  // Injects the schedule button in conversation header
  function injectScheduleButton() {
    if (document.getElementById('wf-schedule-btn')) return;

    const header = document.querySelector('header[data-testid="conversation-header"]');
    if (!header) return;

    // Find the actions area (e.g. search, menu)
    const rightActionsArea = header.querySelector('div[role="button"]')?.parentElement?.parentElement;
    if (!rightActionsArea) return;

    const btn = document.createElement('button');
    btn.id = 'wf-schedule-btn';
    btn.type = 'button';
    btn.title = 'Agendar Lembrete / Mensagem';
    btn.innerHTML = `
      <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
        <path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm4.2 14.2L11 13V7h1.5v5.2l4.7 2.8-.8 1.2z"/>
      </svg>
    `;

    btn.addEventListener('click', () => {
      updateActiveChatInfo();
      
      // Determine active chatId from WPP or state
      // We inject an event to retrieve it from window context if possible, or fallback
      window.dispatchEvent(new CustomEvent('wfGetActiveChatJidRequest'));
      
      setTimeout(() => {
        openSchedulerModal();
      }, 50);
    });

    rightActionsArea.prepend(btn);
  }

  // Listen to Active Chat JID response from the page context
  window.addEventListener('wfGetActiveChatJidResponse', (e) => {
    if (e.detail?.jid) {
      currentChatJid = e.detail.jid;
    }
  });

  // Render modal
  function openSchedulerModal() {
    // If we didn't receive the JID from page context, try to resolve it from UI elements
    if (!currentChatJid) {
      // Fallback JID generation if needed or query WPP again
    }

    const overlay = document.createElement('div');
    overlay.className = 'wf-sched-modal-overlay';
    
    overlay.innerHTML = `
      <div class="wf-sched-modal">
        <div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid #222e35; padding-bottom:12px;">
          <h3 style="margin:0; font-size:16px; font-weight:800; color:#fff;"><i class="ti ti-alarm" style="vertical-align:middle; margin-right:4px;"></i> Agendador de Mensagens</h3>
          <button type="button" id="wf-close-sched" style="background:transparent; border:none; color:#e2e8f0; font-size:22px; cursor:pointer;" aria-label="Fechar agendador">&times;</button>
        </div>
        
        <div style="display:flex; border-bottom:1px solid #222e35; margin-bottom:10px;">
          <button type="button" id="tab-new" class="wf-sched-tab-btn active">Novo Agendamento</button>
          <button type="button" id="tab-list" class="wf-sched-tab-btn">Agendados</button>
        </div>
        
        <!-- Tab: New Schedule -->
        <div id="sched-tab-new-content" style="display:flex; flex-direction:column; gap:14px;">
          <div style="font-size:13px; color:#cbd5e1;">
            Agendando para: <strong style="color:#a78bfa;">${escapeHtml(currentChatName || 'Conversa Ativa')}</strong>
          </div>
          
          <div style="display:flex; flex-direction:column; gap:6px;">
            <label style="font-size:11px; font-weight:700; color:#cbd5e1; text-transform:uppercase;">Mensagem</label>
            <textarea id="sched-msg" class="wf-sched-textarea" rows="4" placeholder="Escreva a mensagem aqui..."></textarea>
          </div>
          
          <div style="display:grid; grid-template-columns: 1fr 1fr; gap:12px;">
            <div style="display:flex; flex-direction:column; gap:6px;">
              <label style="font-size:11px; font-weight:700; color:#cbd5e1; text-transform:uppercase;">Data</label>
              <input type="date" id="sched-date" class="wf-sched-input" />
            </div>
            <div style="display:flex; flex-direction:column; gap:6px;">
              <label style="font-size:11px; font-weight:700; color:#cbd5e1; text-transform:uppercase;">Hora</label>
              <input type="time" id="sched-time" class="wf-sched-input" />
            </div>
          </div>
          
          <div style="margin-top:10px; display:flex; justify-content:flex-end;">
            <button type="button" id="wf-save-schedule" class="wf-sched-btn-primary">
              <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"/></svg>
              Salvar Agendamento
            </button>
          </div>
        </div>
        
        <!-- Tab: List -->
        <div id="sched-tab-list-content" style="display:none; flex-direction:column; gap:14px;">
          <div id="wf-sched-container" class="wf-sched-list">
            <!-- Items loaded here -->
          </div>
        </div>
      </div>
    `;

    document.body.appendChild(overlay);

    // Set default date as today
    const today = new Date().toISOString().split('T')[0];
    document.getElementById('sched-date').value = today;

    // Tabs switching
    const tabNew = document.getElementById('tab-new');
    const tabList = document.getElementById('tab-list');
    const contentNew = document.getElementById('sched-tab-new-content');
    const contentList = document.getElementById('sched-tab-list-content');

    tabNew.addEventListener('click', () => {
      tabNew.classList.add('active');
      tabList.classList.remove('active');
      contentNew.style.display = 'flex';
      contentList.style.display = 'none';
    });

    tabList.addEventListener('click', () => {
      tabList.classList.add('active');
      tabNew.classList.remove('active');
      contentList.style.display = 'flex';
      contentNew.style.display = 'none';
      loadScheduledList();
    });

    // Close handler
    const closeModal = () => overlay.remove();
    document.getElementById('wf-close-sched').addEventListener('click', closeModal);
    overlay.addEventListener('click', (e) => { if (e.target === overlay) closeModal(); });

    // Save handler
    document.getElementById('wf-save-schedule').addEventListener('click', () => {
      const message = document.getElementById('sched-msg').value.trim();
      const date = document.getElementById('sched-date').value;
      const time = document.getElementById('sched-time').value;

      if (!message || !date || !time) {
        alert('Por favor, preencha todos os campos.');
        return;
      }

      // Convert date/time inputs to Timestamp
      const runAt = new Date(`${date}T${time}:00`).getTime();
      if (runAt <= Date.now()) {
        alert('A data e hora do agendamento precisam ser no futuro.');
        return;
      }

      // JID fallback if WPP helper didn't respond (assume contact number from name/UI if digits)
      let resolvedJid = currentChatJid;
      if (!resolvedJid) {
        // Fallback: request from background or resolve
        const chatTitle = currentChatName.replace(/\D/g, '');
        if (chatTitle.length >= 8) {
          resolvedJid = `${chatTitle}@c.us`;
        } else {
          alert('Não foi possível identificar o contato desta conversa. Aguarde o WhatsApp carregar completamente e tente novamente.');
          return;
        }
      }

      const newSchedule = {
        id: 'SCHED_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
        chatId: resolvedJid,
        targetName: currentChatName,
        message: message,
        runAt: runAt,
        status: 'pending'
      };

      chrome.storage.local.get(['flowhatsapp_scheduled_messages'], (res) => {
        const list = res.flowhatsapp_scheduled_messages || [];
        list.push(newSchedule);
        chrome.storage.local.set({ flowhatsapp_scheduled_messages: list }, () => {
          alert('✅ Mensagem agendada com sucesso!');
          closeModal();
        });
      });
    });
  }

  // Load scheduled messages list
  function loadScheduledList() {
    const container = document.getElementById('wf-sched-container');
    container.innerHTML = '<div style="text-align:center;color:#cbd5e1;font-size:13px;padding:20px;">Carregando...</div>';

    chrome.storage.local.get(['flowhatsapp_scheduled_messages'], (res) => {
      const list = res.flowhatsapp_scheduled_messages || [];
      const pendingList = list.filter(item => item.status === 'pending');

      if (pendingList.length === 0) {
        container.innerHTML = '<div style="text-align:center;color:#cbd5e1;font-size:13px;padding:30px 0;">Nenhuma mensagem pendente.</div>';
        return;
      }

      // Sort pendingList by runAt ascending
      pendingList.sort((a, b) => a.runAt - b.runAt);

      container.innerHTML = '';
      pendingList.forEach(item => {
        const itemDate = new Date(item.runAt).toLocaleString();
        
        const card = document.createElement('div');
        card.className = 'wf-sched-item';
        card.innerHTML = `
          <div style="text-align:left; max-width:80%;">
            <strong style="color:#a78bfa; display:block; font-size:12px;">Para: ${escapeHtml(item.targetName)}</strong>
            <span style="color:#e9edef; display:block; font-size:13px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; margin: 3px 0;">${escapeHtml(item.message)}</span>
            <small style="color:#cbd5e1; display:block; font-size:11px;">⏰ ${itemDate}</small>
          </div>
          <button type="button" class="wf-sched-del-btn" title="Excluir" data-id="${item.id}">&times;</button>
        `;

        card.querySelector('.wf-sched-del-btn').addEventListener('click', function() {
          const idToDelete = this.getAttribute('data-id');
          if (confirm('Deseja realmente cancelar este agendamento?')) {
            deleteSchedule(idToDelete);
          }
        });

        container.appendChild(card);
      });
    });
  }

  // Delete schedule helper
  function deleteSchedule(id) {
    chrome.storage.local.get(['flowhatsapp_scheduled_messages'], (res) => {
      const list = res.flowhatsapp_scheduled_messages || [];
      const updated = list.filter(item => item.id !== id);
      chrome.storage.local.set({ flowhatsapp_scheduled_messages: updated }, () => {
        loadScheduledList();
      });
    });
  }

  // Escape HTML helper
  function escapeHtml(str) {
    return String(str || '').replace(/[&<>'"]/g, char => ({
      '&': '&amp;', '<': '&lt;', '>': '&gt;', "'": '&#39;', '"': '&quot;'
    })[char]);
  }

  // ─── EXECUTION / DISPATCHER LOOP ─────────────────────────────────────────
  function startDispatcherLoop() {
    setInterval(() => {
      chrome.storage.local.get(['flowhatsapp_scheduled_messages'], (res) => {
        const list = res.flowhatsapp_scheduled_messages || [];
        const now = Date.now();
        let changed = false;

        list.forEach(item => {
          if (item.status === 'pending' && item.runAt <= now) {
            // Trigger message send via WPP bridge
            window.postMessage({
              type: "SEND_SCHEDULED_MESSAGE",
              payload: {
                chatId: item.chatId,
                message: item.message,
                targetType: item.chatId.includes('@g.us') ? 'group' : 'contact',
                targetName: item.targetName,
                templateType: 'message'
              }
            }, "*");

            item.status = 'sent';
            item.sentAt = now;
            changed = true;

            // Simple notification or logs
            console.log('[Scheduler] Mensagem disparada com sucesso para:', item.targetName);
          }
        });

        if (changed) {
          chrome.storage.local.set({ flowhatsapp_scheduled_messages: list });
        }
      });
    }, 10000); // Poll every 10 seconds
  }

  // Start bootstrap checks
  function init() {
    // Start dispatcher loop immediately
    startDispatcherLoop();

    // Check for conversation header periodically to inject the button
    setInterval(injectScheduleButton, 2000);
  }

  // Page load event
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();
