/* screen_marketing_tutorial.jsx
   Sistema de Tutorial — Spotlight Tour v2
   Estratégia: P1 (auto-onboarding 1ª visita) + P3 (sempre acessível via botão).
   Design: N2 (Confident Standard), T2 (4 divs backdrop), P2 (auto-position), W1+D1.
   NÃO usa emojis. NÃO usa import/export. NÃO usa process.env.
*/

// ── Steps por módulo ──────────────────────────────────────────────────────────

const TUTORIAL_STEPS = {
  briefings: [
    {
      id: 'select_brand_product',
      title: 'Seleccionar marca e produto',
      description: 'Clica em "+ Criar" para criar um novo briefing. Escolhe a marca (ex: Mimaki, BIOND, Decal) e o produto da base de dados no topo do formulário.',
      autoCheck: (s) => !!(s.briefing?.brand_id || s.briefing?.brand_slug),
    },
    {
      id: 'fill_block1',
      title: 'Bloco 1 — Produto',
      description: 'Preenche o nome comercial, elevator pitch (proposta de valor resumida) e lista as USPs principais do produto. Mínimo 3 USPs para uma boa análise AI.',
      autoCheck: (s) => !!(s.briefing?.block1?.commercial_name && s.briefing?.block1?.elevator_pitch && s.briefing?.block1?.usps?.length > 0),
    },
    {
      id: 'fill_block2_block3',
      title: 'Blocos 2 e 3 — Cliente e Mercado',
      description: 'Descreve o decisor de compra, o utilizador final e as dores do cliente (Bloco 2). Depois define a narrativa de posicionamento e os argumentos de diferenciação (Bloco 3).',
      autoCheck: (s) => !!(s.briefing?.block2?.decision_maker && s.briefing?.block3?.positioning_narrative),
    },
    {
      id: 'fill_block4',
      title: 'Bloco 4 — Campanha',
      description: 'Define o objectivo da campanha, escolhe os canais (LinkedIn, Meta Ads, Email, etc.), escreve a mensagem-chave e define o período de duração.',
      autoCheck: (s) => !!(s.briefing?.block4?.objective && s.briefing?.block4?.key_message && s.briefing?.block4?.channels?.length > 0),
    },
    {
      id: 'ai_analysis',
      title: 'Análise AI — score ≥ 80',
      description: 'Vai ao Bloco 6 e clica em "Analisar". A Digi AI avalia o briefing e sugere melhorias campo a campo. Aplica as sugestões até o score global atingir 80% ou mais.',
      autoCheck: (s) => (s.apreciation?.quality_score || 0) >= 80,
    },
    {
      id: 'submit',
      title: 'Submeter para aprovação',
      description: 'Com score ≥ 80%, o botão "Submeter →" fica activo. Clica para enviar ao CEO para aprovação. O fluxo é sequencial: CEO aprova → Chairman aprova → Briefing pronto para campanha.',
      autoCheck: (s) => !!(s.briefing?.status && s.briefing.status !== 'rascunho' && s.briefing.status !== 'rejeitado'),
    },
    {
      id: 'approved',
      title: 'Aprovação completa',
      description: 'Quando o briefing fica com status "Aprovado", já podes criar a campanha. Clica em "+ Criar Campanha" para avançar para o módulo Campanhas.',
      autoCheck: (s) => s.briefing?.status === 'aprovado' || s.briefing?.status === 'em_campanha',
    },
  ],

  campanhas: [
    {
      id: 'create_campaign',
      title: 'Criar campanha a partir de briefing',
      description: 'Clica em "+ Nova Campanha" para criar a tua primeira campanha a partir de um briefing aprovado. Todos os dados do briefing são transferidos automaticamente.',
      autoCheck: (s) => !!s.detail?.id,
    },
    {
      id: 'generate_conceito',
      title: 'Gerar Conceito',
      description: 'Abre a campanha e vai ao tab Conceito. Clica em "Gerar Conceito" — a Digi AI vai criar a Big Idea, narrativa criativa, ângulos de mensagem e personas baseadas no briefing.',
      autoCheck: (s) => !!s.detail?.big_idea,
    },
    {
      id: 'approve_conceito_canais',
      title: 'Aprovar Conceito e gerar Canais',
      description: 'Revê o conceito gerado. Se estiver bom, clica "Aprovar Conceito" → avança para o tab Canais. Clica "Gerar Setup de Canais" para a AI configurar audiências e formatos por canal.',
      autoCheck: (s) => !!s.detail?.canais_setup,
    },
    {
      id: 'copy',
      title: 'Gerar e aprovar Copy',
      description: 'No tab Copy, clica "Gerar Copy" — a AI escreve copy específico para cada canal com specs de anúncio. Revê cada peça e aprova individualmente ou usa "Aprovar todos".',
      autoCheck: (s) => (s.detail?.copy?.length || 0) > 0 && (s.detail?.copy || []).every(c => c.status === 'aprovado'),
    },
    {
      id: 'idiomas',
      title: 'Gerar Idiomas',
      description: 'No tab Idiomas, clica "Gerar Idiomas →" para traduzir o copy aprovado para Espanhol (e outros mercados configurados no briefing). Revê as traduções e aprova.',
      autoCheck: (s) => (s.detail?.idiomas?.length || 0) > 0,
    },
    {
      id: 'prompts',
      title: 'Gerar e aprovar Prompts AI',
      description: 'No tab Prompts AI, clica "Gerar Prompts Visuais" — a AI cria prompts para FLUX (imagens) e Kling (vídeos) por canal. Aprova os prompts para avançar para Aprovação.',
      autoCheck: (s) => (s.detail?.prompts?.length || 0) > 0 && (s.detail?.prompts || []).every(p => p.status === 'aprovado'),
    },
    {
      id: 'aprovacao',
      title: 'Aprovação Executiva',
      description: 'No tab Aprovação, Fábio Costa, Rui Leitão ou Armando Mota revêm a campanha completa (estratégia, conteúdo, calendarização) e clicam "Aprovar e Enviar para Produção" para avançar.',
      autoCheck: (s) => ['em_producao', 'publicado'].includes(s.detail?.status),
    },
    {
      id: 'producao',
      title: 'Campanha em Produção',
      description: 'Com a campanha aprovada, o tab Produção mostra o estado de execução. O Módulo Produção de Conteúdos vai gerar os assets visuais (imagens e vídeos) com base nos prompts aprovados.',
      autoCheck: (s) => ['em_producao', 'publicado'].includes(s.detail?.status),
    },
  ],
};

// ── localStorage helpers ──────────────────────────────────────────────────────

function getTutorialState(moduleName) {
  try {
    const raw = localStorage.getItem(`mkt-tutorial-${moduleName}`);
    return raw ? JSON.parse(raw) : { dismissed: false, manualChecks: [], firstSeen: null };
  } catch { return { dismissed: false, manualChecks: [], firstSeen: null }; }
}

function saveTutorialState(moduleName, state) {
  try { localStorage.setItem(`mkt-tutorial-${moduleName}`, JSON.stringify(state)); } catch {}
}

// ── SVG Icons ─────────────────────────────────────────────────────────────────

const IconBook = () => (
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/>
  </svg>
);

const IconCheck = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
    <polyline points="20 6 9 17 4 12"/>
  </svg>
);

const IconX = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
    <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
  </svg>
);

const IconCheckCircle = () => (
  <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="#22c55e" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
    <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
    <polyline points="22 4 12 14.01 9 11.01"/>
  </svg>
);

// ── computeCardPosition ───────────────────────────────────────────────────────

function computeCardPosition(targetRect, cardW, cardH, gap) {
  const vw = window.innerWidth;
  const vh = window.innerHeight;
  const clampY = (y) => Math.max(10, Math.min(y, vh - cardH - 10));
  const clampX = (x) => Math.max(10, Math.min(x, vw - cardW - 10));
  const midY = clampY(targetRect.top + targetRect.height / 2 - cardH / 2);
  const midX = clampX(targetRect.left + targetRect.width / 2 - cardW / 2);

  if (targetRect.right + gap + cardW < vw)
    return { left: targetRect.right + gap, top: midY, side: 'right' };
  if (targetRect.left - gap - cardW > 0)
    return { left: targetRect.left - gap - cardW, top: midY, side: 'left' };
  if (targetRect.bottom + gap + cardH < vh)
    return { top: targetRect.bottom + gap, left: midX, side: 'bottom' };
  if (targetRect.top - gap - cardH > 0)
    return { top: targetRect.top - gap - cardH, left: midX, side: 'top' };
  return { top: vh / 2 - cardH / 2, left: vw / 2 - cardW / 2, side: 'center' };
}

// ── MktSpotlightTour ──────────────────────────────────────────────────────────

const SPOTLIGHT_PADDING = 10;
const CARD_W = 320;
const CARD_H = 240;
const CARD_GAP = 20;

const MktSpotlightTour = ({ steps, currentIdx, totalSteps, onNext, onPrev, onSkip }) => {
  const [targetRect, setTargetRect] = React.useState(null);
  const currentStep = steps[currentIdx] || null;

  React.useEffect(() => {
    if (!currentStep) { setTargetRect(null); return; }
    const update = () => {
      const el = document.querySelector(`[data-tutorial-step="${currentStep.id}"]`);
      if (!el) { setTargetRect(null); return; }
      el.scrollIntoView({ behavior: 'smooth', block: 'center' });
      setTimeout(() => {
        const r = el.getBoundingClientRect();
        setTargetRect({ top: r.top, left: r.left, width: r.width, height: r.height, bottom: r.bottom, right: r.right });
      }, 320);
    };
    update();
    window.addEventListener('resize', update);
    return () => window.removeEventListener('resize', update);
  }, [currentIdx, currentStep?.id]);

  const P = SPOTLIGHT_PADDING;
  const pos = targetRect ? computeCardPosition(targetRect, CARD_W, CARD_H, CARD_GAP) : {
    top: window.innerHeight / 2 - CARD_H / 2,
    left: window.innerWidth / 2 - CARD_W / 2,
    side: 'center',
  };

  return (
    <>
      {/* Backdrop — 4 divs */}
      {targetRect ? (
        <>
          <div style={{ position:'fixed', top:0, left:0, right:0, height: Math.max(0, targetRect.top - P), background:'rgba(0,0,0,0.65)', zIndex:9050, transition:'all .3s ease', pointerEvents:'auto' }} onClick={onSkip} />
          <div style={{ position:'fixed', top: targetRect.bottom + P, left:0, right:0, bottom:0, background:'rgba(0,0,0,0.65)', zIndex:9050, transition:'all .3s ease', pointerEvents:'auto' }} onClick={onSkip} />
          <div style={{ position:'fixed', top: targetRect.top - P, left:0, width: Math.max(0, targetRect.left - P), height: targetRect.height + 2*P, background:'rgba(0,0,0,0.65)', zIndex:9050, transition:'all .3s ease', pointerEvents:'auto' }} onClick={onSkip} />
          <div style={{ position:'fixed', top: targetRect.top - P, left: targetRect.right + P, right:0, height: targetRect.height + 2*P, background:'rgba(0,0,0,0.65)', zIndex:9050, transition:'all .3s ease', pointerEvents:'auto' }} onClick={onSkip} />
          {/* Ring */}
          <div style={{ position:'fixed', top: targetRect.top - P, left: targetRect.left - P, width: targetRect.width + 2*P, height: targetRect.height + 2*P, border:'2px solid #3859D0', borderRadius:8, pointerEvents:'none', zIndex:9051, animation:'spotlightPulse 1.6s ease-in-out infinite', transition:'all .3s ease' }} />
        </>
      ) : (
        <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.65)', zIndex:9050, pointerEvents:'auto' }} onClick={onSkip} />
      )}

      {/* Step Card */}
      {currentStep && (
        <div key={currentIdx} style={{ position:'fixed', zIndex:9060, top: pos.top, left: pos.left, width: CARD_W, background:'#fff', borderRadius:14, padding:'20px 22px', boxShadow:'0 20px 60px rgba(0,0,0,0.28)', animation:'cardSlideIn .35s cubic-bezier(0.34, 1.56, 0.64, 1)', fontFamily:'var(--font-body, Inter, sans-serif)' }}>

          {/* Header */}
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:12 }}>
            <div style={{ fontSize:10, fontFamily:'var(--font-mono, monospace)', letterSpacing:'0.09em', color:'var(--ai-500, #3859D0)', fontWeight:700 }}>
              PASSO {currentIdx + 1} DE {totalSteps}
            </div>
            <button onClick={onSkip} style={{ background:'none', border:'none', cursor:'pointer', color:'#94a3b8', padding:2, lineHeight:1, display:'flex' }} title="Saltar tour">
              <IconX size={13} />
            </button>
          </div>

          {/* Title */}
          <div style={{ fontSize:16, fontWeight:700, color:'var(--text, #1d2e38)', fontFamily:'var(--font-display, Montserrat, sans-serif)', marginBottom:8, lineHeight:1.3 }}>
            {currentStep.title}
          </div>

          {/* Description */}
          <div style={{ fontSize:13, color:'var(--text-muted, #64748b)', lineHeight:1.65, marginBottom:16 }}>
            {currentStep.description}
          </div>

          {/* Progress bar */}
          <div style={{ display:'flex', gap:4, marginBottom:18 }}>
            {steps.map((_, i) => (
              <div key={i} style={{ flex:1, height:3, borderRadius:99, background: i <= currentIdx ? '#3859D0' : '#e2e8f0', transition:'background .3s ease' }} />
            ))}
          </div>

          {/* Buttons */}
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
            <button onClick={onSkip} style={{ background:'none', border:'none', cursor:'pointer', fontSize:11, color:'#94a3b8', fontFamily:'var(--font-body, Inter, sans-serif)', padding:'2px 0' }}>
              Saltar tour
            </button>
            <div style={{ display:'flex', gap:6 }}>
              {currentIdx > 0 && (
                <button onClick={onPrev} className="btn" style={{ fontSize:12, height:30, padding:'0 12px' }}>
                  ← Anterior
                </button>
              )}
              <button onClick={onNext} className="btn btn-ai" style={{ fontSize:12, height:30, padding:'0 14px' }}>
                {currentIdx === totalSteps - 1 ? 'Concluir' : 'Próximo →'}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

// ── MktTutorialWelcome ────────────────────────────────────────────────────────

const MktTutorialWelcome = ({ moduleLabel, stepCount, userName, onStart, onSkip }) => {
  const firstName = userName ? userName.split(' ')[0] : null;
  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.55)', zIndex:9070, display:'flex', alignItems:'center', justifyContent:'center', animation:'fadeIn .25s ease' }}>
      <div style={{ width:420, background:'#fff', borderRadius:18, padding:'32px 36px', boxShadow:'0 30px 80px rgba(0,0,0,0.3)', textAlign:'center', animation:'cardSlideIn .4s cubic-bezier(0.34, 1.56, 0.64, 1)', fontFamily:'var(--font-body, Inter, sans-serif)' }}>
        {/* Badge */}
        <div style={{ display:'inline-flex', alignItems:'center', gap:6, background:'color-mix(in srgb, #3859D0 10%, transparent)', border:'1px solid color-mix(in srgb, #3859D0 25%, transparent)', borderRadius:99, padding:'4px 12px', marginBottom:16 }}>
          <IconBook />
          <span style={{ fontSize:11, fontFamily:'var(--font-mono, monospace)', letterSpacing:'0.09em', color:'var(--ai-500, #3859D0)', fontWeight:700 }}>
            TUTORIAL — {moduleLabel.toUpperCase()}
          </span>
        </div>

        {/* Title */}
        <h2 style={{ fontSize:24, fontWeight:700, margin:'0 0 12px', fontFamily:'var(--font-display, Montserrat, sans-serif)', color:'var(--text, #1d2e38)', letterSpacing:'-0.02em' }}>
          {firstName ? `Olá, ${firstName}.` : 'Bem-vindo.'}
        </h2>

        {/* Description */}
        <p style={{ fontSize:14, color:'var(--text-muted, #64748b)', lineHeight:1.7, margin:'0 0 28px' }}>
          Vou guiar-te pelos <strong style={{ color:'var(--text, #1d2e38)' }}>{stepCount} passos</strong> para usares os {moduleLabel} como é suposto. Demora menos de 2 minutos.
        </p>

        {/* Buttons */}
        <div style={{ display:'flex', gap:10, justifyContent:'center' }}>
          <button onClick={onSkip} className="btn" style={{ fontSize:13, height:36, padding:'0 18px' }}>
            Saltar por agora
          </button>
          <button onClick={onStart} className="btn btn-ai" style={{ fontSize:13, height:36, padding:'0 20px' }}>
            Começar tour →
          </button>
        </div>
      </div>
    </div>
  );
};

// ── MktTutorialCelebration ────────────────────────────────────────────────────

const MktTutorialCelebration = ({ moduleLabel, onClose }) => {
  const CONFETTI_COLORS = ['#3859D0', '#22c55e', '#f59e0b', '#ec4899', '#8b5cf6'];
  const pieces = React.useMemo(() =>
    Array.from({ length: 15 }, (_, i) => ({
      id: i,
      left: `${5 + Math.random() * 90}%`,
      color: CONFETTI_COLORS[i % CONFETTI_COLORS.length],
      duration: 1.8 + Math.random() * 0.8,
      delay: Math.random() * 0.4,
      rotate: Math.random() > 0.5,
    })), []
  );

  return (
    <>
      {/* Confetti */}
      <div style={{ position:'fixed', inset:0, zIndex:9078, pointerEvents:'none', overflow:'hidden' }}>
        {pieces.map(p => (
          <div key={p.id} style={{ position:'absolute', top:-20, left:p.left, width: p.rotate ? 10 : 8, height: p.rotate ? 8 : 12, background:p.color, borderRadius: p.rotate ? 2 : 3, animation:`confettiFall ${p.duration}s ease-in forwards`, animationDelay:`${p.delay}s`, opacity:0 }} />
        ))}
      </div>

      {/* Success modal */}
      <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.5)', zIndex:9079, display:'flex', alignItems:'center', justifyContent:'center', animation:'fadeIn .25s ease' }}>
        <div style={{ width:380, background:'#fff', borderRadius:18, padding:'36px 32px', textAlign:'center', boxShadow:'0 30px 80px rgba(0,0,0,0.25)', animation:'cardSlideIn .4s cubic-bezier(0.34, 1.56, 0.64, 1)', fontFamily:'var(--font-body, Inter, sans-serif)' }}>
          <div style={{ display:'flex', justifyContent:'center', marginBottom:20, animation:'cardSlideIn .5s cubic-bezier(0.34, 1.56, 0.64, 1)' }}>
            <IconCheckCircle />
          </div>
          <h2 style={{ fontSize:22, fontWeight:700, margin:'0 0 10px', fontFamily:'var(--font-display, Montserrat, sans-serif)', color:'var(--text, #1d2e38)' }}>
            Módulo dominado!
          </h2>
          <p style={{ fontSize:13, color:'var(--text-muted, #64748b)', lineHeight:1.65, margin:'0 0 24px' }}>
            Completaste todos os passos dos {moduleLabel}. Podes usar o botão <strong>Guia</strong> sempre que precisares de rever.
          </p>
          <button onClick={onClose} className="btn btn-ai" style={{ fontSize:13, height:36, padding:'0 24px' }}>
            Fechar
          </button>
        </div>
      </div>
    </>
  );
};

// ── MktTutorialDrawer ─────────────────────────────────────────────────────────

const MktTutorialDrawer = ({ moduleName, moduleLabel, steps, doneSet, onManualCheck, onDismiss, onMarkAllDone, onReset, onClose, onRestartTour }) => {
  const total = steps.length;
  const doneCount = steps.filter(s => doneSet.has(s.id)).length;
  const pct = Math.round((doneCount / total) * 100);
  const allDone = doneCount === total;

  const getStatus = (step) => {
    if (doneSet.has(step.id)) return 'done';
    const firstPending = steps.find(s => !doneSet.has(s.id));
    return firstPending?.id === step.id ? 'current' : 'future';
  };

  return (
    <>
      <div onClick={onClose} style={{ position:'fixed', inset:0, zIndex:9001, background:'rgba(0,0,0,0.25)', backdropFilter:'blur(1px)', animation:'fadeIn .15s ease' }} />
      <div style={{ position:'fixed', top:0, right:0, bottom:0, zIndex:9002, width:320, background:'#fff', boxShadow:'-4px 0 32px rgba(17,41,84,.14)', display:'flex', flexDirection:'column', animation:'slideInRight .2s ease', fontFamily:'var(--font-body, Inter, sans-serif)' }}>

        {/* Header */}
        <div style={{ padding:'18px 18px 14px', borderBottom:'1px solid var(--border, #e2e8f0)', flexShrink:0 }}>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:10 }}>
            <div>
              <div style={{ fontSize:10, fontFamily:'var(--font-mono, monospace)', letterSpacing:'0.08em', color:'var(--text-dim, #94a3b8)', marginBottom:3 }}>GUIA PASSO A PASSO</div>
              <div style={{ fontSize:15, fontWeight:700, color:'var(--text, #1d2e38)', fontFamily:'var(--font-display, Montserrat, sans-serif)' }}>{moduleLabel}</div>
            </div>
            <button onClick={onDismiss} title="Fechar e não mostrar automaticamente" style={{ background:'none', border:'none', cursor:'pointer', color:'var(--text-muted, #94a3b8)', padding:4, borderRadius:4, lineHeight:1, display:'flex' }}>
              <IconX size={16} />
            </button>
          </div>
          <div>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:6 }}>
              <span style={{ fontSize:11, color:'var(--text-muted, #64748b)' }}>{allDone ? 'Concluído!' : `${doneCount} de ${total} passos`}</span>
              <span style={{ fontSize:11, fontWeight:600, color: allDone ? 'var(--success, #22c55e)' : 'var(--ai-500, #3859D0)', fontFamily:'var(--font-mono, monospace)' }}>{pct}%</span>
            </div>
            <div style={{ height:4, borderRadius:99, background:'var(--bg-sunken, #f1f5f9)', overflow:'hidden' }}>
              <div style={{ height:'100%', borderRadius:99, width:`${pct}%`, background: allDone ? 'var(--success, #22c55e)' : 'var(--ai-500, #3859D0)', transition:'width 400ms ease' }} />
            </div>
          </div>
        </div>

        {/* Steps */}
        <div className="scrollbar" style={{ flex:1, overflowY:'auto', padding:'10px 8px' }}>
          {steps.map(step => {
            const status = getStatus(step);
            const isDone = status === 'done';
            const isCurrent = status === 'current';
            return (
              <div key={step.id} style={{ padding: isCurrent ? '12px 14px' : '8px 14px', borderRadius:8, border: isCurrent ? '1px solid color-mix(in srgb, #3859D0 30%, transparent)' : '1px solid transparent', background: isCurrent ? 'color-mix(in srgb, #3859D0 4%, transparent)' : 'transparent', marginBottom:2, opacity: status === 'future' ? 0.55 : 1 }}>
                <div style={{ display:'flex', alignItems:'flex-start', gap:10 }}>
                  <div style={{ width:20, height:20, borderRadius:'50%', flexShrink:0, marginTop:1, background: isDone ? 'color-mix(in srgb, #22c55e 12%, transparent)' : isCurrent ? 'color-mix(in srgb, #3859D0 10%, transparent)' : 'transparent', border: isDone ? '1.5px solid rgba(34,197,94,.3)' : isCurrent ? '1.5px solid #3859D0' : '1.5px solid #e2e8f0', display:'flex', alignItems:'center', justifyContent:'center', color: isDone ? '#22c55e' : isCurrent ? '#3859D0' : '#94a3b8' }}>
                    {isDone ? <IconCheck size={11} /> : <div style={{ width: isCurrent ? 8 : 6, height: isCurrent ? 8 : 6, borderRadius:'50%', background: isCurrent ? '#3859D0' : '#e2e8f0' }} />}
                  </div>
                  <div style={{ flex:1 }}>
                    <div style={{ fontSize:13, fontWeight: isCurrent ? 600 : 500, color: isDone ? 'var(--text-muted, #64748b)' : 'var(--text, #1d2e38)', textDecoration: isDone ? 'line-through' : 'none', fontFamily:'var(--font-display, Montserrat, sans-serif)', lineHeight:1.3 }}>{step.title}</div>
                    {isCurrent && (
                      <>
                        <div style={{ fontSize:12, color:'var(--text-muted, #64748b)', marginTop:5, lineHeight:1.6 }}>{step.description}</div>
                        {!isDone && <button onClick={() => onManualCheck(step.id)} className="btn btn-sm" style={{ marginTop:8, fontSize:11, height:26, padding:'0 10px', display:'flex', alignItems:'center', gap:4 }}><IconCheck size={11} /> Já fiz isto</button>}
                      </>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        {/* Footer */}
        <div style={{ padding:'12px 18px', borderTop:'1px solid var(--border, #e2e8f0)', flexShrink:0, display:'flex', flexDirection:'column', gap:8 }}>
          {!allDone && (
            <button onClick={onRestartTour} className="btn btn-ai" style={{ width:'100%', fontSize:12, justifyContent:'center' }}>
              Retomar tour guiado →
            </button>
          )}
          {!allDone && (
            <button onClick={onMarkAllDone} className="btn" style={{ width:'100%', fontSize:12, justifyContent:'center' }}>
              Marcar todos como vistos
            </button>
          )}
          <button onClick={onReset} style={{ background:'none', border:'none', cursor:'pointer', fontSize:11, color:'var(--text-muted, #94a3b8)', fontFamily:'var(--font-body, Inter, sans-serif)', padding:'2px 0' }}>
            Reiniciar progresso
          </button>
        </div>
      </div>
    </>
  );
};

// ── MktTutorial (componente principal) ────────────────────────────────────────

const MktTutorial = ({ moduleName, moduleLabel, moduleState = {}, userEmail }) => {
  const steps = TUTORIAL_STEPS[moduleName] || [];

  const [open,         setOpen]         = React.useState(false);
  const [tourActive,   setTourActive]   = React.useState(false);
  const [welcomeOpen,  setWelcomeOpen]  = React.useState(false);
  const [tourStepIdx,  setTourStepIdx]  = React.useState(0);
  const [celebrating,  setCelebrating]  = React.useState(false);
  const [showTooltip,  setShowTooltip]  = React.useState(false);
  const [tutState,     setTutState]     = React.useState(() => getTutorialState(moduleName));

  if (!steps.length) return null;

  // Conjunto de steps concluídos
  const doneSet = React.useMemo(() => {
    const s = new Set(tutState.manualChecks || []);
    steps.forEach(step => {
      try { if (step.autoCheck && step.autoCheck(moduleState)) s.add(step.id); } catch {}
    });
    return s;
  }, [steps, tutState.manualChecks, moduleState]);

  const pendingCount = steps.length - doneSet.size;
  const allDone = pendingCount === 0;

  // Índice do primeiro step pendente (para retomar tour)
  const firstPendingIdx = React.useMemo(() =>
    steps.findIndex(s => !doneSet.has(s.id)), [steps, doneSet]
  );

  // P1: auto-open welcome na 1ª visita
  React.useEffect(() => {
    if (!tutState.firstSeen && !tutState.dismissed && pendingCount > 0) {
      const newState = { ...tutState, firstSeen: Date.now() };
      setTutState(newState);
      saveTutorialState(moduleName, newState);
      setTimeout(() => setWelcomeOpen(true), 800);
    }
  }, []);

  const handleDismiss = () => {
    const s = { ...tutState, dismissed: true };
    setTutState(s); saveTutorialState(moduleName, s);
    setOpen(false); setTourActive(false); setWelcomeOpen(false);
  };

  const handleManualCheck = (stepId) => {
    const s = { ...tutState, manualChecks: [...new Set([...(tutState.manualChecks || []), stepId])] };
    setTutState(s); saveTutorialState(moduleName, s);
  };

  const handleMarkAllDone = () => {
    const s = { ...tutState, manualChecks: steps.map(st => st.id), dismissed: true };
    setTutState(s); saveTutorialState(moduleName, s);
    setOpen(false);
  };

  const handleReset = () => {
    const s = { dismissed: false, manualChecks: [], firstSeen: null };
    setTutState(s); saveTutorialState(moduleName, s);
    setOpen(false); setTourActive(false);
  };

  const startTour = () => {
    setWelcomeOpen(false); setOpen(false);
    setTourStepIdx(firstPendingIdx >= 0 ? firstPendingIdx : 0);
    setTourActive(true);
  };

  const handleTourNext = () => {
    if (tourStepIdx < steps.length - 1) {
      setTourStepIdx(i => i + 1);
    } else {
      setTourActive(false);
      setCelebrating(true);
    }
  };

  const handleTourPrev = () => { if (tourStepIdx > 0) setTourStepIdx(i => i - 1); };

  const handleTourSkip = () => {
    setTourActive(false);
    const s = { ...tutState, dismissed: true };
    setTutState(s); saveTutorialState(moduleName, s);
  };

  const handleFloatingClick = () => {
    if (allDone) { setOpen(true); return; }
    setTourStepIdx(firstPendingIdx >= 0 ? firstPendingIdx : 0);
    setTourActive(true);
  };

  return (
    <>
      {/* Welcome modal — 1ª visita */}
      {welcomeOpen && (
        <MktTutorialWelcome
          moduleLabel={moduleLabel}
          stepCount={steps.length}
          userName={(window.currentUser?.nome_apresentar || window.currentUser?.nome || '')}
          onStart={startTour}
          onSkip={handleDismiss}
        />
      )}

      {/* Spotlight tour activo */}
      {tourActive && !welcomeOpen && (
        <MktSpotlightTour
          steps={steps}
          currentIdx={tourStepIdx}
          totalSteps={steps.length}
          onNext={handleTourNext}
          onPrev={handleTourPrev}
          onSkip={handleTourSkip}
        />
      )}

      {/* Celebration */}
      {celebrating && (
        <MktTutorialCelebration
          moduleLabel={moduleLabel}
          onClose={() => setCelebrating(false)}
        />
      )}

      {/* Drawer lateral (referência) */}
      {open && !tourActive && !welcomeOpen && (
        <MktTutorialDrawer
          moduleName={moduleName}
          moduleLabel={moduleLabel}
          steps={steps}
          doneSet={doneSet}
          onManualCheck={handleManualCheck}
          onDismiss={handleDismiss}
          onMarkAllDone={handleMarkAllDone}
          onReset={handleReset}
          onClose={() => setOpen(false)}
          onRestartTour={startTour}
        />
      )}

      {/* Floating button — bottom-right */}
      {!tourActive && !welcomeOpen && !open && (
        <div
          style={{ position:'fixed', bottom:32, right:32, zIndex:9000 }}
          onMouseEnter={() => setShowTooltip(true)}
          onMouseLeave={() => setShowTooltip(false)}
        >
          {showTooltip && (
            <div style={{ position:'absolute', bottom:56, left:'50%', transform:'translateX(-50%)', background:'var(--text, #1d2e38)', color:'#fff', fontSize:11, fontFamily:'var(--font-body, Inter, sans-serif)', padding:'4px 10px', borderRadius:6, whiteSpace:'nowrap', pointerEvents:'none' }}>
              {allDone ? 'Ver guia' : 'Retomar tour'}
            </div>
          )}
          <button
            onClick={handleFloatingClick}
            style={{ width:48, height:48, borderRadius:'50%', background:'linear-gradient(135deg, var(--ai-500, #3859D0), #5b7de8)', border:'none', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', color:'#fff', boxShadow:'0 4px 16px rgba(56,89,208,.35)', position:'relative', transition:'transform 150ms ease, box-shadow 150ms ease' }}
            onMouseEnter={e => { e.currentTarget.style.transform='scale(1.08)'; e.currentTarget.style.boxShadow='0 6px 20px rgba(56,89,208,.45)'; }}
            onMouseLeave={e => { e.currentTarget.style.transform='scale(1)'; e.currentTarget.style.boxShadow='0 4px 16px rgba(56,89,208,.35)'; }}
          >
            <IconBook />
            {pendingCount > 0 && (
              <div style={{ position:'absolute', top:-4, right:-4, width:18, height:18, borderRadius:'50%', background:'#dc2626', color:'#fff', fontSize:9, fontWeight:700, fontFamily:'var(--font-mono, monospace)', display:'flex', alignItems:'center', justifyContent:'center', border:'2px solid #fff' }}>
                {pendingCount}
              </div>
            )}
          </button>
        </div>
      )}

      {/* CSS global */}
      <style>{`
        @keyframes slideInRight { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes cardSlideIn { from { opacity: 0; transform: translateY(20px) scale(0.96); } to { opacity: 1; transform: translateY(0) scale(1); } }
        @keyframes spotlightPulse {
          0%   { box-shadow: 0 0 0 2px rgba(56,89,208,0.7), 0 0 0 5px rgba(56,89,208,0.25); }
          50%  { box-shadow: 0 0 0 6px rgba(56,89,208,0.2), 0 0 0 12px rgba(56,89,208,0.06); }
          100% { box-shadow: 0 0 0 2px rgba(56,89,208,0.7), 0 0 0 5px rgba(56,89,208,0.25); }
        }
        @keyframes confettiFall {
          0%   { transform: translateY(-20px) rotate(0deg); opacity: 1; }
          100% { transform: translateY(100vh) rotate(720deg); opacity: 0; }
        }
      `}</style>
    </>
  );
};

window.MktTutorial = MktTutorial;
