// Onboarding do cliente: tela "Primeiros passos" (checklist com progresso), boas-vindas do primeiro acesso,
// atalho de progresso na barra lateral e o tour guiado (destaque passo a passo sobre uma tela real).
// Os passos e o progresso vêm de window.VxOnboarding (onboarding.js); os tutoriais, de Tutorials.jsx.
let vxOnbFacts = null, vxOnbPending = null;
function vxOnbLoad(force) {
  if (vxOnbPending && !force) return vxOnbPending;
  const p = window.VxOnboarding.facts().then(f => { vxOnbFacts = f; setTimeout(() => { if (vxOnbPending === p) vxOnbPending = null; }, 1500); return f; });
  vxOnbPending = p;
  return p;
}
function useOnboarding() {
  const { allows, status, orgKind } = useAccess();
  const [facts, setFacts] = React.useState(vxOnbFacts), [, bump] = React.useState(0);
  React.useEffect(() => {
    let alive = true;
    const load = force => vxOnbLoad(force).then(f => { if (alive) setFacts(f); });
    const local = () => bump(x => x + 1), refresh = () => load(true), ctx = () => { vxOnbFacts = null; setFacts(null); load(true); };
    load(false);
    window.addEventListener('vx-onboarding-changed', local);
    window.addEventListener('vx-onboarding-refresh', refresh);
    window.addEventListener('vx-context-changed', ctx);
    return () => { alive = false; window.removeEventListener('vx-onboarding-changed', local); window.removeEventListener('vx-onboarding-refresh', refresh); window.removeEventListener('vx-context-changed', ctx); };
  }, []);
  const isClient = status === 'ready' && !!orgKind && orgKind !== 'VERTICE';
  return { ...window.VxOnboarding.progress(facts, allows), loading: !facts, isClient };
}
const vxOnbRefresh = () => { try { window.dispatchEvent(new CustomEvent('vx-onboarding-refresh')); } catch (e) {} };

// Fica dentro do Shell: define o escopo do progresso, manda o cliente para "Primeiros passos" em vez do Dashboard
// de exemplo e, no primeiro acesso, abre a animação de boas-vindas seguida do tutorial de configuração.
function OnboardingBoot({ page, go, env }) {
  const { status, orgKind, allows } = useAccess();
  const ob = useOnboarding();
  const client = status === 'ready' && !!orgKind && orgKind !== 'VERTICE';
  const canStart = allows(window.VX_NAV.meta.inicio);
  React.useEffect(() => { if (env && env.id) window.VxOnboarding.setScope(env.id); }, [env && env.id]);
  React.useEffect(() => {
    if (!client || page !== 'dash') return;
    const home = canStart ? window.VX_NAV.meta.inicio : window.VX_NAV.groups.flatMap(g => g.items).find(allows);
    if (home) go(home.id, undefined, { replace: true });
  }, [client, page, canStart]);
  React.useEffect(() => { if (client) vxOnbRefresh(); }, [page, client]);
  React.useEffect(() => {
    if (!client || !canStart || !env || !env.id || ob.loading) return;
    const perfil = ob.steps.find(s => s.id === 'perfil');
    if (window.VxOnboarding.state().welcomed || (perfil && perfil.done)) return;
    // Espera a abertura da marca terminar para a boas-vindas não tocar por baixo dela.
    let tries = 0;
    const iv = setInterval(() => {
      if (window.__vxIntroOpen && ++tries < 40) return;
      clearInterval(iv);
      window.VxOnboarding.flag('welcomed');
      window.VxTutorials.openSequence(['boas-vindas', 'perfil'], { welcome: true });
    }, 300);
    return () => clearInterval(iv);
  }, [client, canStart, env && env.id, ob.loading]);
  return null;
}

function OnbRing({ done, total, size = 88, stroke = 8, dark }) {
  const r = (size - stroke) / 2, len = 2 * Math.PI * r, p = total ? done / total : 0;
  return <span style={{ position: 'relative', width: size, height: size, flex: 'none', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
    <svg width={size} height={size} style={{ position: 'absolute', inset: 0, transform: 'rotate(-90deg)' }}>
      <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--overlay-10)" strokeWidth={stroke} />
      <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke={p >= 1 ? 'var(--status-success)' : 'var(--action-primary)'} strokeWidth={stroke} strokeLinecap="round" strokeDasharray={len} strokeDashoffset={len * (1 - p)} style={{ transition: 'stroke-dashoffset .6s ease' }} />
    </svg>
    <span style={{ fontFamily: 'var(--font-mono)', fontSize: size > 60 ? 20 : 11, fontWeight: 600 }}>{done}/{total}</span>
  </span>;
}

// Atalho na barra lateral: progresso dos primeiros passos, até concluir ou dispensar.
function OnboardingNavCard({ go, collapsed }) {
  const ob = useOnboarding();
  if (!ob.isClient || ob.loading || !ob.total || ob.complete || ob.dismissed) return null;
  if (collapsed) return <a href="#" title={'Primeiros passos · ' + ob.done + ' de ' + ob.total} onClick={e => { e.preventDefault(); go('inicio'); }} style={{ display: 'flex', justifyContent: 'center', padding: '10px 0', textDecoration: 'none', color: 'var(--text-primary)' }}><OnbRing done={ob.done} total={ob.total} size={40} stroke={4} /></a>;
  return <a href="#" onClick={e => { e.preventDefault(); go('inicio'); }} style={{ margin: '0 14px 14px', padding: 14, borderRadius: 12, background: 'var(--overlay-04)', border: '1px solid var(--border-default)', display: 'flex', flexDirection: 'column', gap: 8, textDecoration: 'none', color: 'var(--text-primary)' }}>
    <span style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 13, fontWeight: 600 }}>Primeiros passos<span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)' }}>{ob.done}/{ob.total}</span></span>
    <span style={{ height: 5, borderRadius: 3, background: 'var(--overlay-10)', overflow: 'hidden' }}><span style={{ display: 'block', height: '100%', width: (100 * ob.done / ob.total) + '%', background: 'var(--action-primary)', borderRadius: 3, transition: 'width .6s ease' }} /></span>
    {ob.next && <span style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.35 }}>Próximo: {ob.next.title}</span>}
  </a>;
}

// Tour guiado: destaca um elemento por vez na tela real e explica o que fazer ali.
// steps = [{ sel, title, text }]; `sel` aponta para um marcador [data-tour]; com data-tour-parent o alvo é o pai do marcador.
function GuidedTour({ steps, onClose }) {
  const [i, setI] = React.useState(0), [rect, setRect] = React.useState(null);
  const step = steps[i];
  React.useEffect(() => {
    let alive = true;
    const target = () => { const m = document.querySelector(step.sel); return m && (m.hasAttribute('data-tour-parent') ? m.parentElement : m); };
    const measure = () => { const el = target(); if (!alive) return; if (!el) { setRect(null); return; } const r = el.getBoundingClientRect(); setRect({ top: r.top, left: r.left, width: r.width, height: r.height }); };
    const el = target();
    if (el && el.scrollIntoView) el.scrollIntoView({ block: 'center', behavior: 'smooth' });
    const t1 = setTimeout(measure, 60), t2 = setTimeout(measure, 450);
    window.addEventListener('resize', measure); window.addEventListener('scroll', measure, true);
    const k = e => { if (e.key === 'Escape') onClose(); else if (e.key === 'ArrowRight') setI(x => Math.min(steps.length - 1, x + 1)); else if (e.key === 'ArrowLeft') setI(x => Math.max(0, x - 1)); };
    window.addEventListener('keydown', k);
    return () => { alive = false; clearTimeout(t1); clearTimeout(t2); window.removeEventListener('resize', measure); window.removeEventListener('scroll', measure, true); window.removeEventListener('keydown', k); };
  }, [i]);
  const { Button } = window.VRticeDesignSystem_d763eb;
  const vw = window.innerWidth, vh = window.innerHeight, pad = 8, w = Math.min(380, vw - 24);
  const below = rect ? rect.top + rect.height + pad + 12 + 210 < vh : true;
  const pop = rect
    ? { left: Math.max(12, Math.min(vw - w - 12, rect.left)), ...(below ? { top: rect.top + rect.height + pad + 12 } : { bottom: Math.max(12, vh - rect.top + pad + 12) }) }
    : { left: (vw - w) / 2, top: vh / 2 - 100 };
  const last = i === steps.length - 1;
  return <div role="dialog" aria-modal="true" aria-label="Tour guiado" style={{ position: 'fixed', inset: 0, zIndex: 380 }}>
    <div onClick={onClose} style={{ position: 'absolute', inset: 0 }} />
    {rect
      ? <div style={{ position: 'absolute', top: rect.top - pad, left: rect.left - pad, width: rect.width + pad * 2, height: rect.height + pad * 2, borderRadius: 22, boxShadow: '0 0 0 9999px var(--bg-overlay)', outline: '2px solid var(--focus-ring)', pointerEvents: 'none', transition: 'all .3s ease' }} />
      : <div style={{ position: 'absolute', inset: 0, background: 'var(--bg-overlay)' }} />}
    <div style={{ position: 'absolute', width: w, boxSizing: 'border-box', padding: 20, borderRadius: 16, background: 'var(--surface-dialog)', border: '1px solid var(--border-default)', boxShadow: '0 24px 60px rgba(0,0,0,.45)', display: 'flex', flexDirection: 'column', gap: 10, ...pop }}>
      <span style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--text-subtle)', fontWeight: 600 }}>Passo {i + 1} de {steps.length}</span>
      <strong style={{ fontSize: 17, letterSpacing: '-0.01em' }}>{step.title}</strong>
      <span style={{ fontSize: 14, lineHeight: 1.5, color: 'var(--text-secondary)' }}>{step.text}</span>
      <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginTop: 6 }}>
        <button type="button" onClick={onClose} style={{ all: 'unset', cursor: 'pointer', fontSize: 13, color: 'var(--text-muted)', marginRight: 'auto' }}>Sair do tour</button>
        {i > 0 && <Button size="sm" variant="secondary" onClick={() => setI(i - 1)}>Voltar</Button>}
        <Button size="sm" onClick={() => last ? onClose() : setI(i + 1)}>{last ? 'Entendi' : 'Próximo'}</Button>
      </div>
    </div>
  </div>;
}
GuidedTour.vxOverlay = true;

function OnboardingScreen({ go }) {
  const { PageHeader, Card, Button, Badge } = window.VRticeDesignSystem_d763eb;
  const shell = useShell(), ob = useOnboarding();
  const first = ((shell.user && shell.user.name) || '').trim().split(/\s+/)[0] || '';
  const open = id => window.VxTutorials.open(id);
  const welcome = window.VxTutorials.byId('boas-vindas');
  const act = s => { if (s.id === 'equipe') window.VxOnboarding.flag('teamSeen'); go(s.page); };
  return <div style={{ display: 'flex', flexDirection: 'column', gap: 28 }}>
    <PageHeader eyebrow="Bem-vindo ao Vértice OS" title={first ? 'Primeiros passos, ' + first : 'Primeiros passos'}
      description="Em poucos minutos o Vértice começa a encontrar licitações para a sua empresa. Siga os passos abaixo na ordem; cada um tem um tutorial curto se você quiser ver antes de fazer."
      actions={<Button variant="secondary" icon="ph-lifebuoy" onClick={() => go('ajuda')}>Central de Ajuda</Button>} />

    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 20, alignItems: 'stretch' }}>
      <Card variant="analysis" padding={24} gap={20} style={{ flex: '999 1 420px', minWidth: 0, justifyContent: 'center' }}>
        <div style={{ display: 'flex', gap: 20, alignItems: 'center', flexWrap: 'wrap' }}>
          <OnbRing done={ob.done} total={ob.total || 4} />
          <div style={{ flex: '1 1 240px', minWidth: 0, display: 'flex', flexDirection: 'column', gap: 6 }}>
            <strong style={{ fontSize: 20, letterSpacing: '-0.02em' }}>{ob.loading ? 'Conferindo o que você já fez…' : ob.complete ? 'Tudo pronto. O Vértice já trabalha por você.' : ob.done === 0 ? 'Vamos começar pelo seu perfil' : 'Você está no caminho. Falta pouco.'}</strong>
            <span style={{ fontSize: 14, lineHeight: 1.5, color: 'var(--text-muted)' }}>{ob.complete ? 'Acompanhe as recomendações novas e registre suas decisões no Go/No-Go.' : ob.next ? 'Próximo passo: ' + ob.next.title + ' (cerca de ' + ob.next.minutes + ' min).' : 'Siga os passos abaixo.'}</span>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          {ob.next && <Button onClick={() => act(ob.next)}>{ob.next.cta}</Button>}
          {ob.complete && <Button onClick={() => go('recomendacoes')}>Abrir recomendações</Button>}
          {ob.next && ob.next.tutorial && <Button variant="secondary" icon="ph-play" onClick={() => open(ob.next.tutorial)}>Ver tutorial desta etapa</Button>}
        </div>
      </Card>
      {welcome && <div style={{ flex: '1 1 300px', minWidth: 0, maxWidth: 460 }}><TutorialCard tutorial={welcome} onOpen={() => window.VxTutorials.openSequence(['boas-vindas', 'perfil'], { welcome: true })} /></div>}
    </div>

    <Card variant="flat" padding={8} gap={0}>
      {ob.steps.map((s, i) => {
        const current = ob.next && ob.next.id === s.id;
        return <div key={s.id} style={{ display: 'flex', gap: 16, alignItems: 'flex-start', padding: '18px 16px', borderRadius: 14, background: current ? 'var(--action-selected-bg)' : 'transparent', borderTop: i && !current ? '1px solid var(--border-faint)' : '1px solid transparent', flexWrap: 'wrap' }}>
          <span aria-hidden="true" style={{ width: 36, height: 36, borderRadius: '50%', flex: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-mono)', fontSize: 14, fontWeight: 700, background: s.done ? 'var(--status-success)' : current ? 'var(--action-primary)' : 'var(--overlay-06)', color: s.done || current ? '#fff' : 'var(--text-muted)' }}>{s.done ? <i className="ph ph-check" style={{ fontSize: 18 }} /> : i + 1}</span>
          <div style={{ flex: '1 1 300px', minWidth: 0, display: 'flex', flexDirection: 'column', gap: 4 }}>
            <span style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
              <strong style={{ fontSize: 16, color: s.done ? 'var(--text-secondary)' : 'var(--text-primary)' }}>{s.title}</strong>
              {s.done && <Badge tone="success">Feito</Badge>}
              {s.optional && !s.done && <Badge variant="meta" tone="neutral">Opcional</Badge>}
              {!s.done && <span style={{ fontSize: 12, color: 'var(--text-subtle)' }}>cerca de {s.minutes} min</span>}
            </span>
            <span style={{ fontSize: 14, lineHeight: 1.5, color: 'var(--text-muted)' }}>{s.text}</span>
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
            {s.tutorial && <Button size="sm" variant="secondary" icon="ph-play" onClick={() => open(s.tutorial)}>Tutorial</Button>}
            <Button size="sm" variant={current ? 'primary' : 'secondary'} onClick={() => act(s)}>{s.done ? 'Abrir' : s.cta}</Button>
          </div>
        </div>;
      })}
      {!ob.steps.length && !ob.loading && <span style={{ padding: 20, fontSize: 14, color: 'var(--text-muted)' }}>Seu acesso não inclui os módulos de inteligência. Fale com o administrador da sua organização.</span>}
    </Card>

    <span style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.5 }}>
      Os passos se marcam sozinhos conforme você usa o sistema. Dúvidas? Escreva para <a href="mailto:contato@verticeops.app" style={{ color: 'var(--text-link)' }}>contato@verticeops.app</a> ou abra a <a href="#" onClick={e => { e.preventDefault(); go('ajuda'); }} style={{ color: 'var(--text-link)' }}>Central de Ajuda</a>.
    </span>
  </div>;
}

Object.assign(window, { useOnboarding, vxOnbRefresh, OnboardingBoot, OnboardingNavCard, GuidedTour, OnboardingScreen, OnbRing });
