// onboarding.jsx — fluxo: welcome → nível → nome+objetivo → anamnese → plano → zenith → lembrete
const { useState: useStateOb } = React;

/* ---------- header com barra de progresso ---------- */
function OnboardHeader({ frac, onBack, showBack }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '6px 22px 12px' }}>
      {showBack ? (
        <button onClick={onBack} style={{ color: 'var(--muted)', display: 'flex' }}><Icon name="back" size={24} /></button>
      ) : <span style={{ width: 24 }} />}
      <div style={{ flex: 1, height: 5, borderRadius: 3, background: 'var(--surface-2)', overflow: 'hidden' }}>
        <div style={{ height: '100%', width: `${Math.round(frac * 100)}%`, background: 'var(--accent)',
          borderRadius: 3, transition: 'width .35s cubic-bezier(.2,.7,.3,1)' }} />
      </div>
    </div>
  );
}

function SelectCard({ active, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      width: '100%', textAlign: 'left', borderRadius: 'var(--r-lg)', padding: '18px 18px',
      background: active ? 'var(--accent-soft)' : 'var(--surface)',
      boxShadow: active ? 'inset 0 0 0 2px var(--accent)' : 'inset 0 0 0 1px var(--line)',
      transition: 'all .18s', display: 'flex', alignItems: 'center', gap: 16,
    }}>{children}</button>
  );
}

/* ---------- slider de métrica com número grande ---------- */
function MetricSlider({ label, value, min, max, step = 1, unit, onChange }) {
  return (
    <div className="card" style={{ padding: '16px 18px' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
        <span className="kicker">{label}</span>
        <span style={{ display: 'flex', alignItems: 'baseline', gap: 5 }}>
          <span style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 32, color: 'var(--accent)', lineHeight: 1 }}>{value}</span>
          <span className="mono" style={{ fontSize: 12, color: 'var(--muted)' }}>{unit}</span>
        </span>
      </div>
      <input className="zr" type="range" min={min} max={max} step={step} value={value}
        onChange={(e) => onChange(Number(e.target.value))} />
    </div>
  );
}

/* ---------- cartão de tipo de corpo (placeholder silhueta) ---------- */
function BodyCard({ active, label, onClick }) {
  return (
    <button onClick={onClick} style={{
      borderRadius: 'var(--r-lg)', padding: 10, background: active ? 'var(--accent-soft)' : 'var(--surface)',
      boxShadow: active ? 'inset 0 0 0 2px var(--accent)' : 'inset 0 0 0 1px var(--line)',
      transition: 'all .18s', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
    }}>
      <div className="slot" style={{ width: '100%', height: 118, borderRadius: 'var(--r-md)', flexDirection: 'column', gap: 4 }}>
        <span style={{ fontSize: 8 }}>SILHUETA</span>
        <span style={{ opacity: .6, fontSize: 7 }}>{label.toUpperCase()}</span>
      </div>
      <span style={{ fontFamily: 'var(--ff-display)', fontWeight: 700, fontSize: 17, textTransform: 'uppercase',
        color: active ? 'var(--accent)' : 'var(--text)' }}>{label}</span>
    </button>
  );
}

function Onboarding({ onComplete }) {
  // fluxo linear de telas
  const STEPS = ['welcome','nivel','nome','objetivo','metrics','imc','corpoAtual','corpoAlvo','dias','plano','zenith','lembrete'];
  const [i, setI] = useStateOb(0);
  const key = STEPS[i];

  // dados coletados
  const [level, setLevel]   = useStateOb(null);
  const [name, setName]     = useStateOb('');
  const [objective, setObjective] = useStateOb(null);
  const [sex, setSex]       = useStateOb(null);
  const [weight, setWeight] = useStateOb(75);
  const [height, setHeight] = useStateOb(172);
  const [birth, setBirth]   = useStateOb('2000-01-01');
  const [target, setTarget] = useStateOb(70);
  const [bodyNow, setBodyNow]   = useStateOb(null);
  const [bodyTgt, setBodyTgt]   = useStateOb(null);
  const [days, setDays]     = useStateOb(4);
  const [reminder, setReminder] = useStateOb('07:00');

  const imc = computeIMC(weight, height);
  const imcCat = imcCategory(imc);
  const plan = estimatePlan({ objective, weight, targetWeight: target, days });

  const next = () => setI(s => Math.min(STEPS.length - 1, s + 1));
  const back = () => setI(s => Math.max(0, s - 1));

  const objLabel = (OBJECTIVES.find(o => o.id === objective) || {}).label || '';
  const firstName = name.trim().split(' ')[0];

  const footer = (label, disabled, onClick) => (
    <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '16px 22px 30px',
      background: 'linear-gradient(to top, var(--bg) 72%, transparent)' }}>
      <button className="btn btn--accent" disabled={disabled}
        style={{ opacity: disabled ? .4 : 1, pointerEvents: disabled ? 'none' : 'auto' }}
        onClick={onClick}>{label}<Icon name="arrow" size={20} /></button>
    </div>
  );

  return (
    <div style={{ position: 'relative', flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      {key !== 'welcome' && <OnboardHeader frac={i / (STEPS.length - 1)} onBack={back} showBack={i > 0} />}
      <div className="screen"><div style={{ padding: '0 22px 150px' }}>

        {/* WELCOME */}
        {key === 'welcome' && (
          <div className="fade-in" style={{ paddingTop: 8 }}>
            <div className="slot" style={{ height: 300, borderRadius: 'var(--r-xl)', marginBottom: 30, flexDirection: 'column', gap: 8 }}>
              <span>HERO / ATLETA EM AÇÃO</span><span style={{ opacity: .6 }}>1080 × 1350</span>
            </div>
            <div className="kicker" style={{ color: 'var(--accent)' }}>CALISTENIA · 30 DIAS</div>
            <h1 className="h1" style={{ fontSize: 58, marginTop: 10 }}>Domine o<br/>seu corpo</h1>
            <p className="lead" style={{ marginTop: 16, maxWidth: 300 }}>
              Treinos guiados, sem equipamento. Evolua com o Zenith ao seu lado, um dia de cada vez.
            </p>
          </div>
        )}

        {/* NÍVEL — PASSO 1 */}
        {key === 'nivel' && (
          <div className="slide-up">
            <div className="kicker">PASSO 1 · NÍVEL</div>
            <h2 className="h1" style={{ fontSize: 38, margin: '8px 0 6px' }}>Qual seu<br/>nível?</h2>
            <p className="lead" style={{ marginBottom: 22 }}>Você pode mudar isso depois.</p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {LEVELS.map(l => (
                <SelectCard key={l.id} active={level === l.id} onClick={() => setLevel(l.id)}>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 24, textTransform: 'uppercase' }}>{l.label}</div>
                    <div style={{ fontSize: 13.5, color: 'var(--muted)' }}>{l.desc}</div>
                  </div>
                  <div className="mono" style={{ fontSize: 12, color: level === l.id ? 'var(--accent)' : 'var(--muted-2)' }}>{l.meta}</div>
                </SelectCard>
              ))}
            </div>
          </div>
        )}

        {/* NOME — PASSO 2 */}
        {key === 'nome' && (
          <div className="slide-up" style={{ paddingTop: 6 }}>
            <div className="kicker">PASSO 2 · IDENTIDADE</div>
            <h2 className="h1" style={{ fontSize: 38, margin: '8px 0 6px' }}>Como devo<br/>te chamar?</h2>
            <p className="lead" style={{ marginBottom: 24 }}>O Zenith vai falar diretamente com você.</p>
            <input className="zfield" type="text" placeholder="Seu nome" value={name}
              maxLength={24} autoFocus onChange={(e) => setName(e.target.value)} />
            {firstName && (
              <div className="card" style={{ marginTop: 18, padding: '16px 18px', display: 'flex', gap: 13 }}>
                <div style={{ width: 3, borderRadius: 2, background: 'var(--accent)', flex: 'none' }} />
                <div>
                  <div className="kicker" style={{ marginBottom: 5 }}>ZENITH DIZ</div>
                  <p style={{ fontSize: 15, color: 'var(--text)' }}>Prazer, <b>{firstName}</b>. Vamos construir sua melhor versão.</p>
                </div>
              </div>
            )}
          </div>
        )}

        {/* OBJETIVO — PASSO 2 */}
        {key === 'objetivo' && (
          <div className="slide-up">
            <div className="kicker">PASSO 2 · OBJETIVO</div>
            <h2 className="h1" style={{ fontSize: 38, margin: '8px 0 6px' }}>Qual seu<br/>objetivo?</h2>
            <p className="lead" style={{ marginBottom: 22 }}>{firstName ? `${firstName}, o que ` : 'O que '}você busca?</p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
              {OBJECTIVES.map(g => (
                <SelectCard key={g.id} active={objective === g.id} onClick={() => setObjective(g.id)}>
                  <div style={{ width: 46, height: 46, borderRadius: 12, flex: 'none',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    background: objective === g.id ? 'var(--accent)' : 'var(--surface-2)',
                    color: objective === g.id ? 'var(--accent-ink)' : 'var(--muted)' }}>
                    <Icon name={g.glyph} size={24} />
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 700, fontSize: 21, textTransform: 'uppercase' }}>{g.label}</div>
                    <div style={{ fontSize: 13, color: 'var(--muted)' }}>{g.desc}</div>
                  </div>
                </SelectCard>
              ))}
            </div>
          </div>
        )}

        {/* MÉTRICAS — PASSO 3 */}
        {key === 'metrics' && (
          <div className="slide-up">
            <div className="kicker">PASSO 3 · ANAMNESE</div>
            <h2 className="h1" style={{ fontSize: 38, margin: '8px 0 6px' }}>Seus<br/>dados</h2>
            <p className="lead" style={{ marginBottom: 20 }}>Usamos para calibrar seu plano. Fica só com você.</p>

            <div className="kicker" style={{ marginBottom: 10 }}>SEXO</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 9, marginBottom: 16 }}>
              {SEXES.map(s => (
                <button key={s.id} onClick={() => setSex(s.id)} style={{
                  padding: '14px 6px', borderRadius: 'var(--r-md)', fontSize: 13, fontWeight: 600,
                  background: sex === s.id ? 'var(--accent-soft)' : 'var(--surface)',
                  color: sex === s.id ? 'var(--accent)' : 'var(--text)',
                  boxShadow: sex === s.id ? 'inset 0 0 0 1.5px var(--accent)' : 'inset 0 0 0 1px var(--line)',
                  lineHeight: 1.2 }}>{s.label}</button>
              ))}
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <MetricSlider label="PESO ATUAL" value={weight} min={40} max={150} unit="kg" onChange={setWeight} />
              <MetricSlider label="ALTURA" value={height} min={140} max={210} unit="cm" onChange={setHeight} />
              <div className="card" style={{ padding: '16px 18px' }}>
                <div className="kicker" style={{ marginBottom: 11 }}>DATA DE NASCIMENTO</div>
                <input className="zfield" type="date" value={birth} min="1940-01-01" max="2012-12-31"
                  onChange={(e) => setBirth(e.target.value)} />
              </div>
              <MetricSlider label="PESO ALVO" value={target} min={40} max={150} unit="kg" onChange={setTarget} />
            </div>
          </div>
        )}

        {/* IMC RESULT */}
        {key === 'imc' && (
          <div className="fade-in" style={{ paddingTop: 6 }}>
            <div className="kicker" style={{ color: 'var(--accent)' }}>RESULTADO · IMC</div>
            <h2 className="h1" style={{ fontSize: 36, margin: '8px 0 22px' }}>Seu índice<br/>de massa</h2>
            <div className="card" style={{ padding: '26px 20px', textAlign: 'center', marginBottom: 16 }}>
              <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 84, color: 'var(--accent)', lineHeight: 0.9 }}>
                {imc.toFixed(1)}
              </div>
              <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 700, fontSize: 22, textTransform: 'uppercase', marginTop: 6 }}>{imcCat.label}</div>
              {/* escala */}
              <div style={{ position: 'relative', height: 10, borderRadius: 5, marginTop: 24,
                background: 'linear-gradient(90deg, #2a8fff 0%, var(--good) 32%, #e8c14a 55%, var(--accent) 100%)' }}>
                <div style={{ position: 'absolute', top: -5, left: `calc(${Math.max(2, Math.min(98, imcCat.pos * 100))}% - 10px)`,
                  width: 20, height: 20, borderRadius: '50%', background: '#fff', boxShadow: '0 0 0 3px var(--bg)' }} />
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 9 }}>
                <span className="mono" style={{ fontSize: 9.5, color: 'var(--muted-2)' }}>ABAIXO</span>
                <span className="mono" style={{ fontSize: 9.5, color: 'var(--muted-2)' }}>NORMAL</span>
                <span className="mono" style={{ fontSize: 9.5, color: 'var(--muted-2)' }}>SOBREPESO</span>
                <span className="mono" style={{ fontSize: 9.5, color: 'var(--muted-2)' }}>OBESO</span>
              </div>
            </div>
            <div className="card" style={{ padding: '16px 18px', display: 'flex', gap: 13 }}>
              <div style={{ width: 3, borderRadius: 2, background: 'var(--accent)', flex: 'none' }} />
              <p style={{ fontSize: 14.5, color: 'var(--text)', lineHeight: 1.45 }}>
                {firstName ? `${firstName}, ` : ''}vamos da sua marca de <b>{weight}kg</b> rumo aos <b>{target}kg</b>. Um passo de cada vez.
              </p>
            </div>
          </div>
        )}

        {/* CORPO ATUAL */}
        {key === 'corpoAtual' && (
          <div className="slide-up">
            <div className="kicker">PASSO 3 · CORPO ATUAL</div>
            <h2 className="h1" style={{ fontSize: 36, margin: '8px 0 6px' }}>Como você<br/>está hoje?</h2>
            <p className="lead" style={{ marginBottom: 22 }}>Escolha o tipo mais próximo do seu.</p>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              {BODY_NOW.map(b => <BodyCard key={b.id} label={b.label} active={bodyNow === b.id} onClick={() => setBodyNow(b.id)} />)}
            </div>
          </div>
        )}

        {/* CORPO ALVO */}
        {key === 'corpoAlvo' && (
          <div className="slide-up">
            <div className="kicker" style={{ color: 'var(--accent)' }}>PASSO 3 · CORPO ALVO</div>
            <h2 className="h1" style={{ fontSize: 36, margin: '8px 0 6px' }}>Onde quer<br/>chegar?</h2>
            <p className="lead" style={{ marginBottom: 22 }}>Sua meta visual. Vamos mirar nela.</p>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              {BODY_TARGET.map(b => <BodyCard key={b.id} label={b.label} active={bodyTgt === b.id} onClick={() => setBodyTgt(b.id)} />)}
            </div>
          </div>
        )}

        {/* DIAS POR SEMANA */}
        {key === 'dias' && (
          <div className="slide-up">
            <div className="kicker">PASSO 3 · FREQUÊNCIA</div>
            <h2 className="h1" style={{ fontSize: 36, margin: '8px 0 6px' }}>Quantos dias<br/>por semana?</h2>
            <p className="lead" style={{ marginBottom: 26 }}>Seja realista. Consistência vence intensidade.</p>
            <div style={{ textAlign: 'center', marginBottom: 26 }}>
              <span style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 96, color: 'var(--accent)', lineHeight: 0.9 }}>{days}</span>
              <div className="mono" style={{ fontSize: 12, color: 'var(--muted)', marginTop: 4 }}>DIAS / SEMANA</div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 7 }}>
              {[1,2,3,4,5,6,7].map(d => (
                <button key={d} onClick={() => setDays(d)} style={{
                  padding: '16px 0', borderRadius: 'var(--r-md)', fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 20,
                  background: days >= d ? 'var(--accent)' : 'var(--surface)',
                  color: days >= d ? 'var(--accent-ink)' : 'var(--muted)',
                  boxShadow: days >= d ? 'none' : 'inset 0 0 0 1px var(--line)', transition: 'all .12s' }}>{d}</button>
              ))}
            </div>
          </div>
        )}

        {/* PLANO — resumo */}
        {key === 'plano' && (
          <div className="fade-in" style={{ paddingTop: 6 }}>
            <div className="kicker" style={{ color: 'var(--accent)' }}>SEU PLANO ESTÁ PRONTO</div>
            <h2 className="h1" style={{ fontSize: 38, margin: '8px 0 6px', whiteSpace: 'pre-line' }}>{firstName ? `Vamos lá,\n${firstName}` : 'Vamos lá'}</h2>
            <p className="lead" style={{ marginBottom: 20 }}>Plano calibrado para o seu objetivo.</p>

            {/* destaque: estimativa */}
            <div className="card" style={{ padding: '22px 20px', textAlign: 'center', marginBottom: 14,
              boxShadow: 'inset 0 0 0 1.5px var(--accent)' }}>
              <div className="kicker" style={{ marginBottom: 8 }}>ESTIMATIVA PARA SUA META</div>
              <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 60, color: 'var(--accent)', lineHeight: 0.9 }}>{plan.text}</div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--muted)', marginTop: 8 }}>
                {objLabel.toUpperCase()} · {days}× POR SEMANA
              </div>
            </div>

            {/* grid de resumo */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14 }}>
              {[
                ['IMC ATUAL', imc.toFixed(1), imcCat.label],
                ['META DE PESO', `${target}kg`, `de ${weight}kg`],
                ['OBJETIVO', objLabel, (LEVELS.find(l => l.id === level) || {}).label || ''],
                ['FREQUÊNCIA', `${days}×`, 'por semana'],
              ].map(([k, v, s]) => (
                <div key={k} className="card" style={{ padding: '14px 16px' }}>
                  <div className="kicker" style={{ fontSize: 9.5, marginBottom: 6 }}>{k}</div>
                  <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 22, lineHeight: 1, textTransform: 'uppercase' }}>{v}</div>
                  <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 4 }}>{s}</div>
                </div>
              ))}
            </div>

            <div className="card" style={{ padding: '16px 18px', display: 'flex', gap: 13 }}>
              <div style={{ width: 3, borderRadius: 2, background: 'var(--accent)', flex: 'none' }} />
              <div>
                <div className="kicker" style={{ marginBottom: 5 }}>ZENITH DIZ</div>
                <p style={{ fontSize: 14.5, color: 'var(--text)', lineHeight: 1.45 }}>
                  Tudo pronto{firstName ? `, ${firstName}` : ''}. Eu cuido do plano — você cuida da presença. Bora?
                </p>
              </div>
            </div>
          </div>
        )}

        {/* ZENITH */}
        {key === 'zenith' && (
          <div className="fade-in" style={{ paddingTop: 14, textAlign: 'center' }}>
            <div className="kicker" style={{ color: 'var(--accent)' }}>SEU MENTOR</div>
            <h2 className="h1" style={{ fontSize: 46, margin: '8px 0 22px' }}>Zenith</h2>
            <AvatarSlot size={224} level={1} progress={0.12} />
            <p className="lead" style={{ marginTop: 26 }}>
              O Zenith evolui com você. A cada treino concluído, ele cresce — e desbloqueia
              novas habilidades para te guiar.
            </p>
            <div style={{ display: 'inline-flex', gap: 8, marginTop: 20, padding: '10px 16px',
              background: 'var(--surface)', borderRadius: 999, boxShadow: 'inset 0 0 0 1px var(--line)' }}>
              <span className="mono" style={{ fontSize: 12, color: 'var(--accent)' }}>"</span>
              <span style={{ fontSize: 13.5, color: 'var(--text)' }}>Vamos começar?</span>
            </div>
          </div>
        )}

        {/* LEMBRETE */}
        {key === 'lembrete' && (
          <div className="slide-up">
            <div className="kicker">QUASE LÁ</div>
            <h2 className="h1" style={{ fontSize: 38, margin: '8px 0 6px' }}>Quando<br/>treinar?</h2>
            <p className="lead" style={{ marginBottom: 24 }}>O Zenith vai te lembrar todo dia neste horário.</p>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, margin: '10px 0 26px' }}>
              <Icon name="bell" size={22} />
              <span style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 64, color: 'var(--accent)', letterSpacing: 1 }}>{reminder}</span>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10 }}>
              {['06:00','07:00','08:00','12:00','18:00','20:00'].map(t => (
                <button key={t} onClick={() => setReminder(t)} className="mono" style={{
                  padding: '13px 0', borderRadius: 'var(--r-md)', fontSize: 15,
                  background: reminder === t ? 'var(--accent-soft)' : 'var(--surface)',
                  color: reminder === t ? 'var(--accent)' : 'var(--text)',
                  boxShadow: reminder === t ? 'inset 0 0 0 1.5px var(--accent)' : 'inset 0 0 0 1px var(--line)',
                }}>{t}</button>
              ))}
            </div>
          </div>
        )}

      </div></div>

      {/* footers */}
      {key === 'welcome'    && footer('Começar', false, next)}
      {key === 'nivel'      && footer('Continuar', !level, next)}
      {key === 'nome'       && footer('Continuar', !name.trim(), next)}
      {key === 'objetivo'   && footer('Continuar', !objective, next)}
      {key === 'metrics'    && footer('Calcular meu IMC', !sex, next)}
      {key === 'imc'        && footer('Continuar', false, next)}
      {key === 'corpoAtual' && footer('Continuar', !bodyNow, next)}
      {key === 'corpoAlvo'  && footer('Continuar', !bodyTgt, next)}
      {key === 'dias'       && footer('Gerar meu plano', false, next)}
      {key === 'plano'      && footer('Conhecer o Zenith', false, next)}
      {key === 'zenith'     && footer('Continuar', false, next)}
      {key === 'lembrete'   && footer('Entrar no app', false,
        () => onComplete({ name: name.trim(), level, objective, sex, weight, height, birth, target, bodyNow, bodyTgt, days, reminder, imc, plan }))}
    </div>
  );
}

Object.assign(window, { Onboarding });
