/** FLOWhatsapp — guided, contextual onboarding for licensed users. */
(() => {
  'use strict';

  const STORAGE_KEY = 'flowhatsapp_onboarding_completed_v245';
  const STYLE_ID = 'flowhatsapp-onboarding-styles';

  function appendWhenDocumentReady(node) {
    const target = document.head || document.documentElement;
    if (target) return target.appendChild(node);
    document.addEventListener('DOMContentLoaded', () => {
      const readyTarget = document.head || document.documentElement;
      if (readyTarget && !node.isConnected) readyTarget.appendChild(node);
    }, { once: true });
  }

  function outlineIcon(name) {
    const paths = {
      welcome: '<path d="M5 12h14M12 5l7 7-7 7"/>',
      kanban: '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M9 4v16M15 4v16"/>',
      chatbot: '<path d="M12 3v3M8 6h8a4 4 0 0 1 4 4v6a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4v-6a4 4 0 0 1 4-4Z"/><path d="M8 13h.01M16 13h.01M9 17h6"/>',
      broadcast: '<path d="m3 11 18-5-5 18-4-9-9-4Z"/><path d="m12 15 9-9"/>',
      schedule: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',
      settings: '<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1-2.9 2.9-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21h-4v-.1a1.7 1.7 0 0 0-1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1-2.9-2.9.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3v-4h.1a1.7 1.7 0 0 0 1.5-1 1.7 1.7 0 0 0-.3-1.8l-.1-.1 2.9-2.9.1.1a1.7 1.7 0 0 0 1.8.3 1.7 1.7 0 0 0 1-1.5V3h4v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1 2.9 2.9-.1.1a1.7 1.7 0 0 0-.3 1.8 1.7 1.7 0 0 0 1.5 1h.1v4h-.1a1.7 1.7 0 0 0-1.5 1Z"/>',
      license: '<rect x="5" y="10" width="14" height="11" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/>',
      done: '<circle cx="12" cy="12" r="9"/><path d="m8 12 3 3 5-6"/>'
    };
    return `<svg class="wf-tour-title-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${paths[name] || paths.welcome}</svg>`;
  }

  if (!document.getElementById(STYLE_ID)) {
    const style = document.createElement('style');
    style.id = STYLE_ID;
    style.textContent = `
      .wf-tour-overlay{position:fixed;z-index:99998;pointer-events:none;border:2px solid #a78bfa;border-radius:12px;box-shadow:0 0 0 9999px rgba(5,9,18,.68),0 0 0 6px rgba(167,139,250,.18);transition:inset .25s ease,width .25s ease,height .25s ease,opacity .2s ease}
      .wf-tour-overlay.is-centered{inset:0!important;width:auto!important;height:auto!important;border:0;border-radius:0;background:rgba(5,9,18,.68);box-shadow:none}
      .wf-tour-tooltip{position:fixed;z-index:100000;background:#111b21;border:1.5px solid #a78bfa;border-radius:16px;padding:20px;width:392px;max-width:calc(100vw - 24px);max-height:calc(100dvh - 24px);overflow:hidden;box-sizing:border-box;color:#f8fafc;font-family:'Montserrat',-apple-system,sans-serif;box-shadow:0 16px 44px rgba(0,0,0,.58),0 0 20px rgba(167,139,250,.18);display:flex;flex-direction:column;gap:13px;animation:wfTooltipIn .25s cubic-bezier(.16,1,.3,1);pointer-events:auto}
      @keyframes wfTooltipIn{from{opacity:0;transform:scale(.96) translateY(8px)}to{opacity:1;transform:none}}
      .wf-tour-title{font-size:16px;font-weight:800;color:#fff;display:flex;align-items:center;gap:10px;line-height:1.25}
      .wf-tour-title-icon{width:22px;height:22px;flex:0 0 22px;color:#c4b5fd}
      .wf-tour-description{font-size:13px;color:#e2e8f0;line-height:1.55}
      .wf-tour-location{display:flex;align-items:flex-start;gap:8px;padding:9px 10px;border:1px solid #334155;border-radius:10px;background:#0b141a;color:#f1f5f9;font-size:12px;line-height:1.4}
      .wf-tour-location svg{width:17px;height:17px;flex:0 0 17px;color:#a78bfa}
      .wf-tour-footer{display:flex;justify-content:space-between;align-items:center;gap:10px;margin-top:2px;border-top:1px solid #334155;padding-top:12px;white-space:nowrap}
      .wf-tour-progress{font-size:11px;color:#cbd5e1;white-space:nowrap;flex:0 0 auto}
      .wf-tour-actions{display:flex;gap:7px;flex:0 0 auto}
      .wf-tour-btn{background:transparent;border:1px solid #64748b;border-radius:8px;padding:7px 11px;color:#f1f5f9;font-family:inherit;font-size:12px;font-weight:700;cursor:pointer;transition:background .18s,color .18s,border-color .18s}
      .wf-tour-btn:hover{background:#26343d;color:#fff;border-color:#94a3b8}
      .wf-tour-btn-primary{background:#a78bfa;color:#111827;border-color:#a78bfa}
      .wf-tour-btn-primary:hover{background:#c4b5fd;color:#0f172a;border-color:#c4b5fd}
      .wf-tour-btn:focus-visible{outline:3px solid #f8fafc;outline-offset:2px}
      .wf-tour-target-label{position:fixed;z-index:99999;pointer-events:none;padding:6px 9px;border-radius:999px;background:#a78bfa;color:#111827;font:800 11px 'Montserrat',sans-serif;box-shadow:0 0 0 4px rgba(167,139,250,.22),0 7px 18px rgba(0,0,0,.4);animation:wfTargetPulse 1.4s ease-in-out infinite}
      @keyframes wfTargetPulse{50%{box-shadow:0 0 0 9px rgba(167,139,250,0),0 7px 18px rgba(0,0,0,.4)}}
      @media(max-width:440px){.wf-tour-tooltip{padding:16px;gap:10px}.wf-tour-footer{gap:6px}.wf-tour-actions{gap:5px}.wf-tour-btn{padding:7px 8px;font-size:11px}.wf-tour-progress{font-size:10px}}
      @media(max-height:600px){.wf-tour-tooltip{padding:14px;gap:8px}.wf-tour-description{line-height:1.4}.wf-tour-location{padding:7px 9px}.wf-tour-footer{padding-top:8px}}
    `;
    appendWhenDocumentReady(style);
  }

  const tourSteps = [
    { icon:'welcome', title:'Bem-vindo ao FLOWhatsapp', description:'Conheça em poucos passos onde ficam as principais ferramentas da extensão.', selector:'#wa-extension-header-root, .wa-profile-dropdown', keywords:['flowhatsapp'], location:'Barra superior e menu principal do FLOWhatsapp', position:'bottom' },
    { icon:'kanban', title:'CRM Kanban de Leads', description:'Organize contatos em etapas e mova oportunidades pelo seu funil comercial.', selector:'.tab-item-v2[data-tab="kanban"], .wa-tab-btn[data-tab="kanban"]', keywords:['kanban','crm'], location:'Barra de ferramentas → CRM Kanban', position:'bottom' },
    { icon:'chatbot', title:'Construtor de Chatbot', description:'Crie respostas automáticas e fluxos para atender clientes com consistência.', selector:'.tab-item-v2[data-tab="chatbot"], .wa-tab-btn[data-tab="chatbot"], [data-tab="fluxo"]', keywords:['chatbot','fluxo'], location:'Barra de ferramentas → Chatbot ou Fluxos', position:'bottom' },
    { icon:'broadcast', title:'Disparador em Massa', description:'Prepare campanhas para listas e etiquetas com os controles de envio da extensão.', selector:'.tab-item-v2[data-tab="mass-sender"], .wa-tab-btn[data-tab="mass"], [data-tab="broadcast"]', keywords:['disparo','campanha','massa'], location:'Barra de ferramentas → Disparos', position:'bottom' },
    { icon:'schedule', title:'Agendamento de Mensagens', description:'Programe uma mensagem para o contato aberto na data e no horário desejados.', selector:'#wf-schedule-btn, [aria-label*="Agendar" i]', keywords:['agendar','agenda'], location:'Conversa aberta → próximo ao campo de mensagem', position:'left' },
    { icon:'settings', title:'Configurações Gerais', description:'Personalize aparência, acessibilidade e preferências de funcionamento.', selector:'.wa-settings-toggle, .wa-menu-toggle, [aria-label*="Configura" i]', keywords:['configurações','configurar'], location:'Menu principal → Configurações', position:'left' },
    { icon:'license', title:'Painel de Licenciamento', description:'Consulte seu plano, a validade e o código da máquina ou ative uma nova chave.', selector:'#wf-license-launcher', keywords:['ativar','licença'], location:'Canto superior direito → botão Ativar ou Licença', position:'left' },
    { icon:'done', title:'Tudo pronto', description:'Agora você já sabe onde encontrar cada área. O menu permanece disponível sempre que precisar.', selector:null, keywords:[], location:'Use o menu do FLOWhatsapp para acessar as ferramentas', position:'center' }
  ];

  let currentStep = 0;
  let overlayEl = null;
  let tooltipEl = null;
  let targetLabelEl = null;
  let activeTarget = null;

  function normalized(value) {
    return String(value || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
  }

  function findTarget(step) {
    const direct = step.selector ? document.querySelector(step.selector) : null;
    if (direct) return direct;
    if (!step.keywords?.length) return null;
    const candidates = document.querySelectorAll('button,[role="button"],[aria-label],[title],a,.wa-menu-item,.tab-item-v2,.wa-tab-btn');
    return Array.from(candidates).find(element => {
      const text = normalized(`${element.textContent || ''} ${element.getAttribute('aria-label') || ''} ${element.getAttribute('title') || ''}`);
      return step.keywords.some(keyword => text.includes(normalized(keyword)));
    }) || null;
  }

  function isUsableTarget(target) {
    if (!target || target === document.body) return false;
    const rect = target.getBoundingClientRect();
    const style = getComputedStyle(target);
    return rect.width > 4 && rect.height > 4 && style.display !== 'none' && style.visibility !== 'hidden';
  }

  function updateSpotlight(target) {
    if (!overlayEl) return;
    if (!isUsableTarget(target)) {
      overlayEl.className = 'wf-tour-overlay is-centered';
      targetLabelEl.style.display = 'none';
      return;
    }
    const rect = target.getBoundingClientRect();
    const gap = 7;
    overlayEl.className = 'wf-tour-overlay';
    overlayEl.style.left = `${Math.max(4, rect.left - gap)}px`;
    overlayEl.style.top = `${Math.max(4, rect.top - gap)}px`;
    overlayEl.style.width = `${Math.min(window.innerWidth - 8, rect.width + gap * 2)}px`;
    overlayEl.style.height = `${Math.min(window.innerHeight - 8, rect.height + gap * 2)}px`;
    targetLabelEl.style.display = 'block';
    targetLabelEl.style.left = `${Math.max(8, Math.min(rect.left, window.innerWidth - 72))}px`;
    targetLabelEl.style.top = `${Math.max(8, rect.top - 34)}px`;
  }

  function setupTourDOM() {
    overlayEl = document.createElement('div');
    overlayEl.className = 'wf-tour-overlay is-centered';
    tooltipEl = document.createElement('section');
    tooltipEl.className = 'wf-tour-tooltip';
    tooltipEl.setAttribute('role', 'dialog');
    tooltipEl.setAttribute('aria-modal', 'true');
    targetLabelEl = document.createElement('div');
    targetLabelEl.className = 'wf-tour-target-label';
    targetLabelEl.textContent = 'É aqui';
    document.body.append(overlayEl, targetLabelEl, tooltipEl);
  }

  function showStep(stepIndex) {
    if (stepIndex < 0 || stepIndex >= tourSteps.length) return finishTour();
    currentStep = stepIndex;
    const step = tourSteps[stepIndex];
    activeTarget = findTarget(step);
    if (isUsableTarget(activeTarget)) activeTarget.scrollIntoView({ behavior:'smooth', block:'center', inline:'center' });

    const pinIcon = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 10c0 5-8 11-8 11S4 15 4 10a8 8 0 1 1 16 0Z"/><circle cx="12" cy="10" r="2.5"/></svg>';
    tooltipEl.innerHTML = `
      <div class="wf-tour-title">${outlineIcon(step.icon)}<span>${step.title}</span></div>
      <div class="wf-tour-description">${step.description}</div>
      <div class="wf-tour-location">${pinIcon}<span><strong>Onde encontrar:</strong> ${step.location}.${isUsableTarget(activeTarget) ? ' O local está destacado na tela.' : ' Abra esse menu para visualizar o recurso.'}</span></div>
      <div class="wf-tour-footer">
        <span class="wf-tour-progress">Passo ${stepIndex + 1} de ${tourSteps.length}</span>
        <div class="wf-tour-actions">
          <button type="button" id="wf-tour-skip" class="wf-tour-btn">Pular</button>
          ${stepIndex > 0 ? '<button type="button" id="wf-tour-prev" class="wf-tour-btn">Voltar</button>' : ''}
          <button type="button" id="wf-tour-next" class="wf-tour-btn wf-tour-btn-primary">${stepIndex === tourSteps.length - 1 ? 'Concluir' : 'Próximo'}</button>
        </div>
      </div>`;

    updateSpotlight(activeTarget);
    requestAnimationFrame(() => positionTooltip(activeTarget, step.position));
    tooltipEl.querySelector('#wf-tour-skip')?.addEventListener('click', finishTour);
    tooltipEl.querySelector('#wf-tour-next')?.addEventListener('click', () => showStep(currentStep + 1));
    tooltipEl.querySelector('#wf-tour-prev')?.addEventListener('click', () => showStep(currentStep - 1));
  }

  function positionTooltip(target, preferredPosition) {
    const tooltipRect = tooltipEl.getBoundingClientRect();
    const width = tooltipRect.width || 392;
    const height = tooltipRect.height || 240;
    const padding = 12;
    const gap = 16;
    if (!isUsableTarget(target) || preferredPosition === 'center') {
      tooltipEl.style.left = `${Math.max(padding, (window.innerWidth - width) / 2)}px`;
      tooltipEl.style.top = `${Math.max(padding, (window.innerHeight - height) / 2)}px`;
      tooltipEl.style.transform = 'none';
      return;
    }
    const rect = target.getBoundingClientRect();
    const placements = {
      bottom:[rect.left + rect.width / 2 - width / 2, rect.bottom + gap],
      top:[rect.left + rect.width / 2 - width / 2, rect.top - height - gap],
      left:[rect.left - width - gap, rect.top + rect.height / 2 - height / 2],
      right:[rect.right + gap, rect.top + rect.height / 2 - height / 2]
    };
    let [left, top] = placements[preferredPosition] || placements.bottom;
    if (top + height > window.innerHeight - padding) top = rect.top - height - gap;
    if (top < padding) top = Math.min(window.innerHeight - height - padding, rect.bottom + gap);
    if (left + width > window.innerWidth - padding) left = window.innerWidth - width - padding;
    if (left < padding) left = padding;
    tooltipEl.style.left = `${Math.max(padding, left)}px`;
    tooltipEl.style.top = `${Math.max(padding, top)}px`;
    tooltipEl.style.transform = 'none';
  }

  function finishTour() {
    chrome.storage.local.set({ [STORAGE_KEY]: true });
    overlayEl?.remove();
    tooltipEl?.remove();
    targetLabelEl?.remove();
    overlayEl = tooltipEl = targetLabelEl = activeTarget = null;
  }

  function licenseIsValid() {
    return new Promise(resolve => {
      chrome.runtime.sendMessage({ type:'FLOWHATSAPP_LICENSE_GET_STATE' }, response => {
        resolve(!chrome.runtime.lastError && response?.result?.valid === true);
      });
    });
  }

  async function startTour() {
    const completed = await new Promise(resolve => chrome.storage.local.get([STORAGE_KEY], data => resolve(Boolean(data?.[STORAGE_KEY]))));
    if (completed || !(await licenseIsValid())) return;
    setTimeout(() => {
      if (!document.body || tooltipEl) return;
      setupTourDOM();
      showStep(0);
    }, 3500);
  }

  window.addEventListener('resize', () => {
    if (!tooltipEl) return;
    const step = tourSteps[currentStep];
    activeTarget = findTarget(step);
    updateSpotlight(activeTarget);
    positionTooltip(activeTarget, step.position);
  });

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', startTour, { once:true });
  else startTour();
})();
