/* global React, Reveal, Icon, Logo, CountUp */
const { useState: useSP, useEffect: useEffSP, useRef: useRefSP } = React;

// ════════════════════════════════════════════════════════════
//  DESIGNAÇÃO — animated handoff flow
// ════════════════════════════════════════════════════════════
const FLOW = [
  { name: 'Ana', role: 'Comercial', initial: 'a', task: 'Fechou a proposta', next: 'Bruno' },
  { name: 'Bruno', role: 'Operação', initial: 'b', task: 'Tocou a entrega', next: 'Carla' },
  { name: 'Carla', role: 'Financeiro', initial: 'c', task: 'Emitiu e recebeu', next: 'Ana' },
];
const LOG_LINES = [
  ['Ana', 'concluiu a proposta do Café Origem', 'Bruno foi designado automaticamente'],
  ['Bruno', 'finalizou a entrega do projeto', 'Carla foi designada automaticamente'],
  ['Carla', 'registrou o recebimento', 'ciclo fechado — rentabilidade calculada'],
];

function Designacao() {
  const [step, setStep] = useSP(0);
  const [paused, setPaused] = useSP(false);
  const [ref, setRef] = useSP(null);
  const inView = useElementInView(ref);

  useEffSP(() => {
    if (!inView || paused) return;
    const t = setInterval(() => setStep(s => (s + 1) % 3), 2900);
    return () => clearInterval(t);
  }, [inView, paused]);

  return (
    <section id="designacao" className="section section-paper">
      <div aria-hidden="true" data-px="-65" style={{ position: 'absolute', top: '6%', right: '5%', width: 260, height: 260, borderRadius: '50%', background: 'radial-gradient(circle, rgba(231,193,164,0.4), rgba(231,193,164,0) 68%)', pointerEvents: 'none', zIndex: 0, willChange: 'transform' }} />
      <div aria-hidden="true" data-px="48" data-px-rot="-14" style={{ position: 'absolute', bottom: '10%', left: '3%', width: 130, height: 130, borderRadius: '42% 58% 60% 40% / 50% 45% 55% 50%', border: '2px solid rgba(195,106,77,0.18)', pointerEvents: 'none', zIndex: 0, willChange: 'transform' }} />
      <div className="wrap" style={{ position: 'relative', zIndex: 1 }}>
        <div className="sec-head">
          <Reveal as="div" className="eyebrow">O diferencial · fluxo de designação</Reveal>
          <Reveal as="h2" delay={60} className="sec-title">
            Cada um termina a sua parte.<br />O sistema <em className="it" style={{ color: 'var(--terra)' }}>passa adiante</em>.
          </Reveal>
          <Reveal as="p" delay={120} className="sec-lead">
            Sem grupo de WhatsApp pra cobrar ninguém. Quando você conclui, a próxima pessoa é avisada na hora — e todo mundo sabe exatamente o que está na sua mão.
          </Reveal>
        </div>

        <Reveal delay={120} style={{ marginTop: 50 }}>
          <div ref={setRef} className="card" style={{ padding: 'clamp(22px, 4vw, 44px)', background: 'var(--white)', boxShadow: 'var(--shadow-md)' }}
               onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}>

            {/* flow track */}
            <div style={{ position: 'relative', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0 }}>
              {/* connector line */}
              <div aria-hidden="true" style={{ position: 'absolute', top: 36, left: '16.66%', right: '16.66%', height: 3, background: 'var(--line)', borderRadius: 2 }} />
              <div aria-hidden="true" style={{ position: 'absolute', top: 36, left: '16.66%', height: 3, background: 'var(--terra)', borderRadius: 2, transition: 'width .7s cubic-bezier(.4,.1,.2,1)', width: `calc(${(step) * 33.33}% )`, maxWidth: '66.66%' }} />

              {FLOW.map((p, i) => {
                const state = i === step ? 'active' : i < step ? 'done' : 'wait';
                return <FlowNode key={p.name} p={p} state={state} active={i === step} />;
              })}
            </div>

            {/* status banner */}
            <div style={{ marginTop: 34, display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 13, background: 'var(--peach-soft)', border: '1px solid var(--peach)', borderRadius: 14, padding: '13px 18px' }}>
                <span style={{ width: 38, height: 38, borderRadius: '50%', background: 'var(--terra)', color: 'var(--paper)', display: 'grid', placeItems: 'center', fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 19, flexShrink: 0 }}>{FLOW[step].initial}</span>
                <div style={{ lineHeight: 1.3 }}>
                  <div style={{ fontSize: 13, color: 'var(--terra-deep)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.05em' }}>Esperando por {FLOW[step].name}</div>
                  <div style={{ fontSize: 15, color: 'var(--ink)', fontWeight: 500 }}>{FLOW[step].role} · está na mão dele(a) agora</div>
                </div>
              </div>

              {/* step dots */}
              <div style={{ display: 'flex', gap: 9, alignItems: 'center' }}>
                {FLOW.map((_, i) => (
                  <button key={i} onClick={() => setStep(i)} aria-label={`Etapa ${i + 1}`}
                    style={{ width: i === step ? 30 : 11, height: 11, borderRadius: 999, border: 0, padding: 0, background: i === step ? 'var(--terra)' : 'var(--line)', transition: 'all .3s' }} />
                ))}
              </div>
            </div>

            {/* activity log */}
            <div style={{ marginTop: 26, background: 'var(--cream)', borderRadius: 14, padding: '6px 6px', border: '1px solid var(--line-soft)' }}>
              <FlowLog step={step} />
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

function FlowNode({ p, state, active }) {
  const ring = state === 'active' ? 'var(--terra)' : state === 'done' ? 'var(--done)' : 'var(--line)';
  const bg = state === 'active' ? 'var(--terra)' : state === 'done' ? 'var(--done)' : 'var(--sand)';
  const fg = state === 'wait' ? 'var(--ink-faint)' : 'var(--paper)';
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 9, position: 'relative', zIndex: 1 }}>
      <div style={{ position: 'relative' }}>
        <span style={{
          width: 72, height: 72, borderRadius: '50%', background: bg, color: fg,
          display: 'grid', placeItems: 'center', fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 34,
          boxShadow: active ? '0 0 0 6px rgba(195,106,77,0.16)' : 'none',
          transition: 'all .5s cubic-bezier(.2,.7,.2,1)', transform: active ? 'scale(1.08)' : 'scale(1)',
          border: `2px solid ${ring}`,
        }}>{p.initial}</span>
        {state === 'done' && (
          <span style={{ position: 'absolute', right: -2, bottom: -2, width: 26, height: 26, borderRadius: '50%', background: 'var(--done)', color: 'var(--paper)', display: 'grid', placeItems: 'center', border: '3px solid var(--white)' }}><Icon name="check" size={14} stroke={2.6} /></span>
        )}
      </div>
      <div>
        <div style={{ fontSize: 17, fontWeight: 600 }}>{p.name}</div>
        <div style={{ fontSize: 13, color: 'var(--ink-faint)', fontWeight: 500 }}>{p.role}</div>
      </div>
      <div style={{
        fontSize: 12.5, fontWeight: 600, padding: '5px 12px', borderRadius: 999,
        background: active ? 'var(--peach-soft)' : 'transparent',
        color: active ? 'var(--terra-deep)' : state === 'done' ? 'var(--done)' : 'var(--ink-faint)',
        opacity: state === 'wait' ? 0.6 : 1, transition: 'all .4s',
      }}>
        {active ? 'na sua mão' : state === 'done' ? p.task : 'aguardando'}
      </div>
    </div>
  );
}

function FlowLog({ step }) {
  const [who, did, auto] = LOG_LINES[step];
  return (
    <div key={step} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 16px', animation: 'logIn .5s cubic-bezier(.2,.7,.2,1)' }}>
      <span style={{ width: 34, height: 34, borderRadius: 9, background: 'var(--white)', border: '1px solid var(--line)', display: 'grid', placeItems: 'center', color: 'var(--terra)', flexShrink: 0 }}><Icon name="route" size={18} /></span>
      <div style={{ fontSize: 14.5, lineHeight: 1.35 }}>
        <strong style={{ fontWeight: 600 }}>{who}</strong> <span style={{ color: 'var(--ink-soft)' }}>{did}.</span>{' '}
        <span style={{ color: 'var(--terra-deep)', fontWeight: 600 }}>→ {auto}.</span>
      </div>
      <style>{`@keyframes logIn{from{opacity:0;transform:translateX(-10px)}to{opacity:1;transform:none}}`}</style>
    </div>
  );
}

// generic in-view (works with state-stored node)
function useElementInView(el) {
  const [seen, setSeen] = useSP(false);
  useEffSP(() => {
    if (!el || seen) return;
    if (typeof IntersectionObserver === 'undefined') { setSeen(true); return; }
    const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } }, { threshold: 0.3 });
    io.observe(el);
    const t = setTimeout(() => setSeen(true), 1400);
    return () => { clearTimeout(t); io.disconnect(); };
  }, [el, seen]);
  return seen;
}

// ════════════════════════════════════════════════════════════
//  PRODUTO — tabbed product mockup
// ════════════════════════════════════════════════════════════
function Produto() {
  const [tab, setTab] = useSP('crm');
  const tabs = [
    ['crm', 'kanban', 'Comercial'],
    ['proj', 'route', 'Projetos'],
    ['fin', 'wallet', 'Financeiro'],
  ];
  return (
    <section id="produto" className="section section-ink">
      <div aria-hidden="true" data-px="-75" style={{ position: 'absolute', top: '4%', left: '-2%', width: 300, height: 300, borderRadius: '50%', background: 'radial-gradient(circle, rgba(195,106,77,0.22), rgba(195,106,77,0) 70%)', pointerEvents: 'none', zIndex: 0, willChange: 'transform' }} />
      <div aria-hidden="true" data-px="60" data-px-x="18" style={{ position: 'absolute', bottom: '8%', right: '-1%', width: 200, height: 200, borderRadius: '55% 45% 50% 50% / 45% 55% 45% 55%', background: 'rgba(231,193,164,0.08)', pointerEvents: 'none', zIndex: 0, willChange: 'transform' }} />
      <div className="wrap" style={{ position: 'relative', zIndex: 1 }}>
        <div className="sec-head">
          <Reveal as="div" className="eyebrow" style={{ color: 'var(--peach)' }}>O produto</Reveal>
          <Reveal as="h2" delay={60} className="sec-title" style={{ color: 'var(--paper)' }}>
            Comercial, operação e financeiro.<br /><em className="it" style={{ color: 'var(--peach)' }}>Um lugar só.</em>
          </Reveal>
          <Reveal as="p" delay={120} className="sec-lead">
            A mesma informação atravessa o sistema sem você redigitar nada. Clique nas abas e veja como cada área conversa com a outra.
          </Reveal>
        </div>

        <Reveal delay={120} style={{ marginTop: 44 }}>
          {/* tab switcher */}
          <div style={{ display: 'inline-flex', gap: 6, padding: 6, background: 'rgba(250,244,234,0.08)', borderRadius: 999, marginBottom: 22 }}>
            {tabs.map(([id, ic, label]) => (
              <button key={id} onClick={() => setTab(id)}
                style={{ display: 'inline-flex', alignItems: 'center', gap: 8, border: 0, borderRadius: 999, padding: '10px 18px', fontSize: 14.5, fontWeight: 600, transition: 'all .2s', background: tab === id ? 'var(--paper)' : 'transparent', color: tab === id ? 'var(--ink)' : 'rgba(250,244,234,0.7)' }}>
                <Icon name={ic} size={17} /> {label}
              </button>
            ))}
          </div>

          {/* window */}
          <div style={{ background: 'var(--white)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-lg)', overflow: 'hidden', border: '1px solid rgba(0,0,0,0.06)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 18px', borderBottom: '1px solid var(--line-soft)', background: 'var(--cream)' }}>
              <div style={{ display: 'flex', gap: 7 }}>{['#D98E6F', '#E3C07A', '#9FB07A'].map(c => <span key={c} style={{ width: 12, height: 12, borderRadius: '50%', background: c }} />)}</div>
              <div style={{ flex: 1, maxWidth: 300, margin: '0 auto', height: 26, borderRadius: 8, background: 'var(--white)', border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7, fontFamily: 'var(--mono)', fontSize: 11.5, color: 'var(--ink-faint)' }}>
                <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--done)' }} /> app.convive.tech/{tab}
              </div>
            </div>
            <div style={{ minHeight: 440, background: 'var(--paper)' }}>
              {tab === 'crm' && <PanelCRM />}
              {tab === 'proj' && <PanelProjetos />}
              {tab === 'fin' && <PanelFinanceiro />}
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

function PanelHeader({ title, sub, action }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18, flexWrap: 'wrap', gap: 12 }}>
      <div>
        <div className="serif-display" style={{ fontSize: 24 }}>{title}</div>
        <div style={{ fontSize: 13.5, color: 'var(--ink-faint)' }}>{sub}</div>
      </div>
      {action && <div className="btn btn-ink" style={{ padding: '9px 16px', fontSize: 13.5 }}><Icon name="plus" size={16} /> {action}</div>}
    </div>
  );
}

function PanelCRM() {
  const cols = [
    { name: 'Lead', tint: 'var(--sand)', deals: [['Café Origem', 'R$ 28.000', 'a'], ['Studio Lumen', 'R$ 12.500', 'b']] },
    { name: 'Proposta', tint: 'var(--peach-soft)', deals: [['Bar do Porto', 'R$ 9.800', 'c'], ['Ótica Vista', 'R$ 16.200', 'a']] },
    { name: 'Negociação', tint: 'var(--peach)', deals: [['Rede Sabor', 'R$ 41.000', 'b']] },
    { name: 'Fechado', tint: 'var(--done)', deals: [['Agência Norte', 'R$ 33.400', 'c'], ['Mercado Vila', 'R$ 7.600', 'a']] },
  ];
  return (
    <div style={{ padding: 'clamp(18px,3vw,28px)', animation: 'panelIn .4s ease' }}>
      <PanelHeader title="Pipeline comercial" sub="8 oportunidades · R$ 166k no funil" action="Nova oportunidade" />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 13, overflowX: 'auto' }} className="crm-cols">
        {cols.map(col => (
          <div key={col.name} style={{ minWidth: 150 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <span style={{ width: 9, height: 9, borderRadius: 3, background: col.tint }} />
              <span style={{ fontSize: 13, fontWeight: 600 }}>{col.name}</span>
              <span style={{ fontSize: 12, color: 'var(--ink-faint)', marginLeft: 'auto' }}>{col.deals.length}</span>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
              {col.deals.map(([n, v, who]) => (
                <div key={n} className="card" style={{ padding: 13, borderRadius: 13, boxShadow: 'none' }}>
                  <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 7 }}>{n}</div>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <span style={{ fontFamily: 'var(--mono)', fontSize: 12.5, color: 'var(--terra-deep)', fontWeight: 600 }}>{v}</span>
                    <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--cream)', border: '1px solid var(--line)', display: 'grid', placeItems: 'center', fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 12 }}>{who}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
      <CrossLink text="Fechou um negócio? Ele já vira projeto na aba" tab="Projetos" />
      <style>{`@keyframes panelIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}} @media(max-width:720px){.crm-cols{grid-template-columns:repeat(4,160px) !important;}}`}</style>
    </div>
  );
}

function PanelProjetos() {
  const lanes = [
    { who: 'Ana · Comercial', tasks: [['Briefing Café Origem', 'concluído', 'done']] },
    { who: 'Bruno · Operação', tasks: [['Layout & build do site', 'na mão dele', 'active'], ['Setup Bar do Porto', 'na mão dele', 'active']] },
    { who: 'Carla · Financeiro', tasks: [['Faturar Agência Norte', 'aguardando', 'wait']] },
  ];
  const tint = s => s === 'done' ? 'var(--done)' : s === 'active' ? 'var(--terra)' : 'var(--ink-faint)';
  const bgt = s => s === 'active' ? 'var(--peach-soft)' : 'var(--white)';
  return (
    <div style={{ padding: 'clamp(18px,3vw,28px)', animation: 'panelIn .4s ease' }}>
      <PanelHeader title="Designação por pessoa" sub="Cada coluna é o que está na mão de alguém" action="Designar tarefa" />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 13 }} className="lane-cols">
        {lanes.map(lane => (
          <div key={lane.who}>
            <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 10, color: 'var(--ink-soft)' }}>{lane.who}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
              {lane.tasks.map(([t, label, s]) => (
                <div key={t} style={{ padding: 14, borderRadius: 13, background: bgt(s), border: `1px solid ${s === 'active' ? 'var(--peach)' : 'var(--line)'}` }}>
                  <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 8 }}>{t}</div>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 600, color: tint(s) }}>
                    {s === 'done' && <Icon name="check" size={14} />}
                    {s === 'active' && <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--terra)' }} />}
                    {label}
                  </span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
      <CrossLink text="Terminou a entrega? O financeiro é avisado na aba" tab="Financeiro" />
      <style>{`@media(max-width:640px){.lane-cols{grid-template-columns:1fr !important;}}`}</style>
    </div>
  );
}

function PanelFinanceiro() {
  const rows = [
    ['Agência Norte', 'R$ 33.400', 'R$ 21.900', '34,4%', 'up'],
    ['Café Origem', 'R$ 28.000', 'R$ 24.600', '12,1%', 'flat'],
    ['Rede Sabor', 'R$ 41.000', 'R$ 25.800', '37,1%', 'up'],
    ['Bar do Porto', 'R$ 9.800', 'R$ 9.100', '7,1%', 'down'],
  ];
  return (
    <div style={{ padding: 'clamp(18px,3vw,28px)', animation: 'panelIn .4s ease' }}>
      <PanelHeader title="Rentabilidade real" sub="Faturamento menos o custo de verdade de cada projeto" action="Exportar" />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 13, marginBottom: 16 }} className="fin-cards">
        {[['Faturado no mês', 'R$ 112,2k', 'var(--ink)'], ['Custo real', 'R$ 81,4k', 'var(--ink)'], ['Margem real', '27,4%', 'var(--terra-deep)']].map(([l, v, c]) => (
          <div key={l} style={{ background: 'var(--cream)', borderRadius: 14, padding: '15px 17px', border: '1px solid var(--line-soft)' }}>
            <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--ink-faint)', textTransform: 'uppercase', letterSpacing: '.05em' }}>{l}</div>
            <div className="serif-display" style={{ fontSize: 30, marginTop: 5, color: c }}>{v}</div>
          </div>
        ))}
      </div>
      <div className="card" style={{ padding: 0, overflow: 'hidden', boxShadow: 'none' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr 1fr 0.9fr', gap: 0, fontSize: 12, fontWeight: 600, color: 'var(--ink-faint)', padding: '12px 16px', borderBottom: '1px solid var(--line-soft)', textTransform: 'uppercase', letterSpacing: '.04em' }}>
          <span>Projeto</span><span>Faturou</span><span>Custou</span><span>Margem</span>
        </div>
        {rows.map(([n, fat, cust, m, dir]) => (
          <div key={n} style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr 1fr 0.9fr', gap: 0, padding: '13px 16px', borderBottom: '1px solid var(--line-soft)', alignItems: 'center', fontSize: 14 }}>
            <span style={{ fontWeight: 600 }}>{n}</span>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 13 }}>{fat}</span>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 13, color: 'var(--ink-soft)' }}>{cust}</span>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 13, fontWeight: 700, color: dir === 'down' ? 'var(--waiting)' : 'var(--done)' }}>{m}</span>
          </div>
        ))}
      </div>
      <CrossLink text="Tudo isso vem sozinho do que foi fechado no" tab="Comercial" />
      <style>{`@media(max-width:560px){.fin-cards{gap:8px !important;}.fin-cards .serif-display{font-size:21px !important;}}`}</style>
    </div>
  );
}

function CrossLink({ text, tab }) {
  return (
    <div style={{ marginTop: 18, display: 'inline-flex', alignItems: 'center', gap: 9, fontSize: 13.5, color: 'var(--ink-soft)', background: 'var(--cream)', border: '1px dashed var(--line)', borderRadius: 999, padding: '8px 16px' }}>
      <Icon name="route" size={16} color="var(--terra)" /> {text} <strong style={{ color: 'var(--terra-deep)' }}>{tab}</strong>.
    </div>
  );
}

Object.assign(window, { Designacao, Produto });
