// Prodz — Onboarding. Minimal required fields (role, city), progressive
// enrichment after (brief §2.5 / §3.1). Bilingual; language is chosen first.
function Onboarding({ onComplete }) {
  const { L, lang, setLang } = useL();
  const { Button } = window.ProdzDesignSystem_d0b87b;
  const [step, setStep] = useStateS(0);          // 0 = welcome, 1..4 = fields
  const [role, setRole] = useStateS(null);
  const [city, setCity] = useStateS(null);
  const [cityQ, setCityQ] = useStateS('');
  const [interests, setInterests] = useStateS([]);
  const [goal, setGoal] = useStateS(null);

  const TOTAL = 4;
  const finish = () => onComplete({ role, city, interests, goal });

  // ---- Welcome / language ----
  if (step === 0) {
    return (
      <div className="pz-screen-enter" style={{ position: 'relative', height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0, background: `url(${IMG.fashion}) center/cover` }} />
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(5,5,6,0.45) 0%, rgba(5,5,6,0.78) 52%, var(--surface-canvas) 100%)' }} />
        <div style={{ position: 'relative', flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', padding: '0 24px 30px' }}>
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 40, letterSpacing: '-0.03em', color: 'var(--text-primary)', lineHeight: 1 }}>
            Prodz<span style={{ color: 'var(--prodz-teal)' }}>.</span>
          </span>
          <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 25, letterSpacing: '-0.02em', color: 'var(--text-primary)', margin: '18px 0 8px', lineHeight: 1.2 }}>
            {L('La rete di chi fa cinema e fotografia.', 'The network for film & photo people.')}
          </h1>
          <p style={{ fontSize: 14.5, lineHeight: 1.55, color: 'var(--text-muted)', margin: '0 0 22px', maxWidth: 320 }}>
            {L('Portfolio, opportunità e collaborazioni in un solo posto. Costruisci il profilo in un minuto.', 'Portfolio, opportunities and collaborations in one place. Build your profile in a minute.')}
          </p>

          <div style={{ marginBottom: 18 }}>
            <Eyebrow style={{ marginBottom: 10 }}>{L('Lingua', 'Language')}</Eyebrow>
            <div style={{ display: 'flex', gap: 10 }}>
              {[{ id: 'it', label: 'Italiano', flag: '🇮🇹' }, { id: 'en', label: 'English', flag: '🇬🇧' }].map((o) => (
                <button key={o.id} onClick={() => setLang(o.id)} style={{
                  flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, height: 50, cursor: 'pointer',
                  borderRadius: 'var(--radius-md)', border: 'none',
                  background: lang === o.id ? 'var(--teal-surface)' : 'var(--surface-card)',
                  boxShadow: lang === o.id ? 'var(--ring-teal)' : 'var(--ring-inset-hairline)',
                  color: lang === o.id ? 'var(--prodz-teal)' : 'var(--text-muted)', fontSize: 14.5, fontWeight: 700,
                }}>
                  <span style={{ fontSize: 18 }}>{o.flag}</span>{o.label}
                </button>
              ))}
            </div>
          </div>

          <Button variant="primary" glow fullWidth size="lg" trailingIcon={<Ic n="ArrowRight" s={18} color="var(--text-on-accent)" />} onClick={() => setStep(1)}>
            {L('Inizia', 'Get started')}
          </Button>
          <button onClick={() => onComplete(null)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-muted)', fontSize: 13, fontWeight: 600, margin: '14px auto 0', display: 'block' }}>
            {L('Esplora l’app →', 'Explore the app →')}
          </button>
        </div>
      </div>
    );
  }

  // ---- Field steps ----
  const canNext = step === 1 ? !!role : step === 2 ? !!city : true;
  const optional = step >= 3;

  return (
    <div className="pz-screen-enter" style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* header: progress */}
      <div style={{ padding: '18px 20px 8px', flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
          <button onClick={() => setStep((s) => s - 1)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-muted)', display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 13, fontWeight: 600, padding: 0 }}>
            <Ic n="ChevronLeft" s={18} color="currentColor" />{L('Indietro', 'Back')}
          </button>
          <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-subtle)' }}>{L('Passo', 'Step')} {step}/{TOTAL}</span>
        </div>
        <div style={{ display: 'flex', gap: 5 }}>
          {Array.from({ length: TOTAL }).map((_, i) => (
            <span key={i} style={{ flex: 1, height: 4, borderRadius: 2, background: i < step ? 'var(--prodz-teal)' : 'var(--ink-700)', transition: 'background var(--dur-base)' }} />
          ))}
        </div>
      </div>

      <div className="prodz-scroll" style={{ position: 'static', flex: 1, padding: '14px 20px 8px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 25, fontWeight: 800, letterSpacing: '-0.02em', color: 'var(--text-primary)', margin: 0 }}>
            {step === 1 && L('Cosa fai?', 'What do you do?')}
            {step === 2 && L('Dove ti trovi?', 'Where are you based?')}
            {step === 3 && L('Cosa ti interessa?', 'What are you into?')}
            {step === 4 && L('Perché sei qui?', 'Why are you here?')}
          </h1>
          <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', padding: '3px 8px', borderRadius: 'var(--radius-pill)',
            color: optional ? 'var(--text-subtle)' : 'var(--prodz-teal)', background: optional ? 'var(--surface-raised)' : 'var(--teal-surface)', boxShadow: optional ? 'var(--ring-inset-hairline)' : 'var(--ring-teal)' }}>
            {optional ? L('Opzionale', 'Optional') : L('Obbligatorio', 'Required')}
          </span>
        </div>
        <p style={{ fontSize: 13.5, color: 'var(--text-muted)', margin: '6px 0 0', lineHeight: 1.5 }}>
          {step === 1 && L('Il tuo ruolo principale. Personalizza feed e Shoutouts.', 'Your primary role. It tunes your feed and Shoutouts.')}
          {step === 2 && L('Per connetterti con chi lavora vicino a te.', 'To connect you with people working nearby.')}
          {step === 3 && L('Scegli almeno 3. Affina le opportunità che vedi.', 'Pick at least 3. It sharpens the opportunities you see.')}
          {step === 4 && L('Ci aiuta a darti la versione giusta della piattaforma.', 'Helps us give you the right version of the platform.')}
        </p>

        {/* STEP 1 — role */}
        {step === 1 && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9, marginTop: 20 }}>
            {ROLES.map((r) => {
              const sel = role && role.it === r.it;
              return <Chip key={r.it} selected={sel} onClick={() => setRole(r)}>{tr(L, r)}</Chip>;
            })}
          </div>
        )}

        {/* STEP 2 — city */}
        {step === 2 && (
          <div style={{ marginTop: 18 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, height: 46, padding: '0 14px', background: 'var(--surface-input)', borderRadius: 'var(--radius-md)', boxShadow: 'var(--ring-inset-hairline)', marginBottom: 16 }}>
              <Ic n="Search" s={18} color="var(--text-subtle)" />
              <input value={cityQ} onChange={(e) => setCityQ(e.target.value)} placeholder={L('Cerca la tua città…', 'Search your city…')}
                style={{ flex: 1, background: 'none', border: 'none', outline: 'none', color: 'var(--text-body)', fontSize: 14 }} />
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9 }}>
              {CITIES.filter((c) => c.toLowerCase().includes(cityQ.toLowerCase())).map((c) => (
                <Chip key={c} selected={city === c} onClick={() => setCity(c)} icon="MapPin">{c}</Chip>
              ))}
            </div>
          </div>
        )}

        {/* STEP 3 — interests */}
        {step === 3 && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9, marginTop: 20 }}>
            {INTERESTS.map((it) => {
              const sel = interests.some((x) => x.it === it.it);
              return <Chip key={it.it} selected={sel} onClick={() => setInterests((arr) => sel ? arr.filter((x) => x.it !== it.it) : [...arr, it])}>{tr(L, it)}</Chip>;
            })}
          </div>
        )}

        {/* STEP 4 — goal */}
        {step === 4 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 20 }}>
            {GOALS.map((g) => {
              const sel = goal && goal.label.it === g.label.it;
              return (
                <button key={g.label.it} onClick={() => setGoal(g)} style={{
                  display: 'flex', alignItems: 'center', gap: 13, padding: '14px 15px', cursor: 'pointer', textAlign: 'left',
                  borderRadius: 'var(--radius-md)', border: 'none', width: '100%',
                  background: sel ? 'var(--teal-surface)' : 'var(--surface-card)',
                  boxShadow: sel ? 'var(--ring-teal)' : 'var(--ring-inset-hairline)',
                }}>
                  <span style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--surface-raised)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <Ic n={g.icon} s={19} color={sel ? 'var(--prodz-teal)' : 'var(--text-muted)'} />
                  </span>
                  <span style={{ flex: 1, fontSize: 14.5, fontWeight: 600, color: sel ? 'var(--text-primary)' : 'var(--text-body)' }}>{tr(L, g.label)}</span>
                  {sel && <Ic n="Check" s={18} color="var(--prodz-teal)" />}
                </button>
              );
            })}
          </div>
        )}

        {step === TOTAL && (
          <p style={{ display: 'flex', gap: 7, alignItems: 'flex-start', fontSize: 12, color: 'var(--text-subtle)', margin: '22px 2px 0', lineHeight: 1.45 }}>
            <Ic n="Sparkles" s={14} color="var(--text-subtle)" />
            {L('Potrai arricchire il profilo più avanti, mentre usi l’app.', 'You can enrich your profile later, as you use the app.')}
          </p>
        )}
      </div>

      {/* footer */}
      <div style={{ flexShrink: 0, padding: '12px 20px calc(16px + env(safe-area-inset-bottom))', borderTop: '1px solid var(--border-hairline)', background: 'var(--surface-chrome)', backdropFilter: 'var(--blur-chrome)', WebkitBackdropFilter: 'var(--blur-chrome)' }}>
        {step < TOTAL ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            {optional && <button onClick={() => setStep((s) => s + 1)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-muted)', fontSize: 13.5, fontWeight: 600, whiteSpace: 'nowrap' }}>{L('Salta', 'Skip')}</button>}
            <div style={{ flex: 1 }}>
              <Button variant="primary" glow={canNext} fullWidth size="lg" disabled={!canNext}
                trailingIcon={<Ic n="ArrowRight" s={18} color="var(--text-on-accent)" />} onClick={() => setStep((s) => s + 1)}>
                {L('Avanti', 'Next')}
              </Button>
            </div>
          </div>
        ) : (
          <Button variant="primary" glow fullWidth size="lg" leadingIcon={<Ic n="Check" s={18} color="var(--text-on-accent)" />} onClick={finish}>
            {L('Entra in Prodz', 'Enter Prodz')}
          </Button>
        )}
      </div>
    </div>
  );
}

function Chip({ children, selected, onClick, icon }) {
  return (
    <button onClick={onClick} style={{
      display: 'inline-flex', alignItems: 'center', gap: 7, padding: '10px 15px', cursor: 'pointer',
      borderRadius: 'var(--radius-pill)', border: 'none', fontSize: 13.5, fontWeight: 600,
      background: selected ? 'var(--prodz-teal)' : 'var(--surface-card)',
      color: selected ? 'var(--text-on-accent)' : 'var(--text-body)',
      boxShadow: selected ? 'var(--glow-teal-soft)' : 'var(--ring-inset-hairline)',
      transition: 'background var(--dur-base), color var(--dur-base)',
    }}>
      {icon && <Ic n={icon} s={15} color="currentColor" />}
      {children}
      {selected && !icon && <Ic n="Check" s={15} color="currentColor" />}
    </button>
  );
}

Object.assign(window, { Onboarding, Chip });
