// M1 — Onboarding posmatrača (Vigilo Mobile)
// Self-serve registracija. 6 koraka, bez koordinatora.
// Nakon završetka, zahtev ide HR koordinaciji na odobrenje.

const V1 = {
  paper:   'oklch(0.985 0.003 60)',
  ink75:   'oklch(0.972 0.004 60)',
  ink100:  'oklch(0.955 0.005 60)',
  ink150:  'oklch(0.930 0.006 60)',
  ink200:  'oklch(0.900 0.007 60)',
  ink300:  'oklch(0.830 0.008 60)',
  ink400:  'oklch(0.700 0.010 60)',
  ink500:  'oklch(0.580 0.011 60)',
  ink600:  'oklch(0.460 0.012 60)',
  ink700:  'oklch(0.340 0.013 60)',
  ink800:  'oklch(0.240 0.014 60)',
  ink900:  'oklch(0.160 0.015 60)',
  ink950:  'oklch(0.110 0.015 60)',
  red500:  'oklch(0.590 0.215 25)',
  red600:  'oklch(0.520 0.215 25)',
  success: 'oklch(0.620 0.155 152)',
  successBg:'oklch(0.960 0.030 152)',
  warning: 'oklch(0.745 0.150 70)',
  info:    'oklch(0.580 0.155 245)',
  infoBg:  'oklch(0.965 0.025 245)',
  font:    'Geist, -apple-system, system-ui, sans-serif',
  mono:    '"Geist Mono", ui-monospace, SF Mono, Menlo, monospace',
};

const I1 = ({ children, size = 18, sw = 1.6, fill = 'none' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={fill} stroke="currentColor" strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>{children}</svg>
);
const ArrowR1 = (p) => <I1 {...p}><path d="M5 12h14M12 5l7 7-7 7"/></I1>;
const Back1   = (p) => <I1 {...p}><path d="m15 18-6-6 6-6"/></I1>;
const Cam1    = (p) => <I1 {...p}><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></I1>;
const Chk1    = (p) => <I1 {...p}><path d="M20 6 9 17l-5-5"/></I1>;
const Info1   = (p) => <I1 {...p}><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></I1>;
const Mail    = (p) => <I1 {...p}><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><path d="m22 6-10 7L2 6"/></I1>;
const Lock    = (p) => <I1 {...p}><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></I1>;
const PhoneIc = (p) => <I1 {...p}><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 22 16.92z"/></I1>;
const Spark1  = (p) => <I1 {...p}><path d="M12 3l1.9 5.6L19.5 10l-5.6 1.9L12 17.5l-1.9-5.6L4.5 10l5.6-1.4z"/></I1>;
const Eye1    = (p) => <I1 {...p}><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></I1>;
const Ring    = (p) => <I1 {...p}><circle cx="12" cy="12" r="10"/></I1>;
const User1   = (p) => <I1 {...p}><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></I1>;

const Tap1 = ({ children, onClick, disabled, style }) => (
  <button onClick={disabled ? null : onClick} disabled={disabled} style={{
    background: 'transparent', border: 0, padding: 0, cursor: disabled ? 'default' : 'pointer',
    font: 'inherit', color: 'inherit', WebkitTapHighlightColor: 'transparent', ...style,
  }}>{children}</button>
);

// ─────────────────────────────────────────────────────────────
// Progress dots header
// ─────────────────────────────────────────────────────────────
function Progress({ step, total, onBack }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', padding: '8px 12px 14px', gap: 12 }}>
      <Tap1 onClick={onBack} style={{ width: 40, height: 40, borderRadius: 10, display: 'grid', placeItems: 'center', color: V1.ink700 }}>
        <Back1 size={20}/>
      </Tap1>
      <div style={{ flex: 1, display: 'flex', gap: 4 }}>
        {Array.from({ length: total }).map((_, i) => (
          <div key={i} style={{
            flex: 1, height: 3, borderRadius: 2,
            background: i < step ? V1.ink900 : i === step ? V1.ink600 : V1.ink200,
          }}/>
        ))}
      </div>
      <div style={{ width: 40, textAlign: 'right', fontSize: 12, color: V1.ink500, fontFamily: V1.mono }}>
        {step + 1}/{total}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Form field (light variant for onboarding)
// ─────────────────────────────────────────────────────────────
function Field1({ label, hint, error, children }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <label style={{ display: 'block', fontSize: 12.5, fontWeight: 500, color: V1.ink600, marginBottom: 8 }}>{label}</label>
      {children}
      {error && <div style={{ marginTop: 6, fontSize: 11.5, color: V1.red500, display: 'flex', alignItems: 'center', gap: 4 }}>{error}</div>}
      {!error && hint && <div style={{ marginTop: 6, fontSize: 11.5, color: V1.ink500 }}>{hint}</div>}
    </div>
  );
}
const InputBase = (props) => (
  <input {...props} style={{
    width: '100%', height: 50, padding: '0 16px',
    background: 'white', border: '1px solid ' + V1.ink200, borderRadius: 12,
    fontFamily: V1.font, fontSize: 16, color: V1.ink900,
    outline: 'none', boxSizing: 'border-box',
    ...(props.style || {}),
  }} onFocus={(e) => { e.target.style.borderColor = V1.ink900; e.target.style.boxShadow = '0 0 0 3px oklch(0.16 0.015 60 / 0.08)'; }}
     onBlur={(e) => { e.target.style.borderColor = V1.ink200; e.target.style.boxShadow = 'none'; }}/>
);

// ─────────────────────────────────────────────────────────────
// Bottom CTA
// ─────────────────────────────────────────────────────────────
function BottomCTA({ label, onClick, disabled, secondary }) {
  return (
    <div style={{ padding: '14px 16px 36px', background: V1.paper, borderTop: '1px solid ' + V1.ink150 }}>
      <Tap1 onClick={onClick} disabled={disabled} style={{
        width: '100%', height: 54,
        background: disabled ? V1.ink200 : V1.ink950,
        color: disabled ? V1.ink500 : 'white',
        borderRadius: 14, fontFamily: V1.font, fontSize: 16, fontWeight: 600,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      }}>{label} <ArrowR1 size={18} sw={2.4}/></Tap1>
      {secondary && (
        <Tap1 onClick={secondary.onClick} style={{
          marginTop: 8, width: '100%', textAlign: 'center', fontSize: 13, color: V1.ink600, padding: '8px 0',
        }}>{secondary.label}</Tap1>
      )}
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// STEP 0 — Welcome
// ═════════════════════════════════════════════════════════════
function StepWelcome({ next }) {
  return (
    <div style={{ background: V1.paper, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: V1.font, color: V1.ink900 }}>
      <div style={{ paddingTop: 80, padding: '80px 24px 0', flex: 1, display: 'flex', flexDirection: 'column' }}>
        <div style={{
          width: 64, height: 64, borderRadius: 18, background: V1.ink950, color: 'white',
          display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 32, letterSpacing: -1, marginBottom: 24,
          backgroundImage: 'radial-gradient(circle at 70% 30%, oklch(0.59 0.215 25 / 0.4), transparent 70%)',
        }}>V</div>

        <div style={{ fontSize: 11, fontFamily: V1.mono, color: V1.red500, textTransform: 'uppercase', letterSpacing: 0.08, marginBottom: 8 }}>
          CRTA · Vigilo
        </div>
        <div style={{ fontSize: 32, fontWeight: 600, letterSpacing: -0.8, lineHeight: 1.05, marginBottom: 12 }}>
          Postani posmatrač izbora
        </div>
        <div style={{ fontSize: 15, color: V1.ink600, lineHeight: 1.55, marginBottom: 32 }}>
          Vigilo je platforma CRTE za posmatranje izbora. Za prijavu trebaju nam tvoji osnovni podaci, fotografija lične karte, i potvrda telefona i email-a.
        </div>

        {/* Steps overview */}
        <div style={{ background: 'white', border: '1px solid ' + V1.ink200, borderRadius: 14, padding: '4px 0' }}>
          {[
            { ic: <User1 size={16}/>, t: 'Osnovni podaci', s: 'ime, prezime, email' },
            { ic: <Lock size={16}/>,  t: 'Identifikacija',  s: 'JMBG i fotografija lične karte' },
            { ic: <PhoneIc size={16}/>, t: 'Telefon',       s: 'SMS verifikacija' },
            { ic: <Mail size={16}/>, t: 'Email',           s: 'verifikacija linka' },
            { ic: <Chk1 size={16}/>, t: 'Saglasnosti',     s: 'GDPR, javni spisak, kodeks' },
          ].map((r, i, arr) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '12px 16px', borderBottom: i === arr.length - 1 ? 'none' : '1px solid ' + V1.ink150 }}>
              <div style={{ width: 30, height: 30, borderRadius: 8, background: V1.ink100, color: V1.ink700, display: 'grid', placeItems: 'center' }}>{r.ic}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13.5, fontWeight: 500, color: V1.ink900 }}>{r.t}</div>
                <div style={{ fontSize: 11.5, color: V1.ink500, marginTop: 1 }}>{r.s}</div>
              </div>
              <div style={{ fontSize: 11, color: V1.ink400, fontFamily: V1.mono }}>{i + 1}</div>
            </div>
          ))}
        </div>

        <div style={{ marginTop: 18, padding: '12px 14px', background: V1.infoBg, border: '1px solid oklch(0.88 0.07 245)', borderRadius: 10, display: 'flex', gap: 10, alignItems: 'flex-start' }}>
          <div style={{ color: V1.info, marginTop: 1 }}><Info1 size={14}/></div>
          <div style={{ fontSize: 12, color: 'oklch(0.32 0.155 245)', lineHeight: 1.5 }}>
            <strong style={{ fontWeight: 600 }}>5–7 minuta.</strong> Posle prijave, koordinator tvog regiona pregledaće zahtev. Dobijaš obaveštenje kada budeš odobren/a.
          </div>
        </div>
        <div style={{ flex: 1 }}/>
      </div>
      <div style={{ padding: '20px 16px 36px' }}>
        <Tap1 onClick={next} style={{
          width: '100%', height: 54, background: V1.ink950, color: 'white',
          borderRadius: 14, fontFamily: V1.font, fontSize: 16, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>Započni <ArrowR1 size={18} sw={2.4}/></Tap1>
        <Tap1 style={{ marginTop: 8, width: '100%', textAlign: 'center', fontSize: 13, color: V1.ink600, padding: '8px 0' }}>
          Već imam nalog · Prijavi se
        </Tap1>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// STEP 1 — Osnovni podaci
// ═════════════════════════════════════════════════════════════
function StepBasic({ data, setData, step, total, prev, next }) {
  const ok = data.ime?.trim() && data.prezime?.trim() && /\S+@\S+\.\S+/.test(data.email || '');
  return (
    <div style={{ background: V1.paper, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: V1.font }}>
      <div style={{ paddingTop: 56 }} />
      <Progress step={step} total={total} onBack={prev}/>
      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 20px 16px' }}>
        <div style={{ fontSize: 24, fontWeight: 600, letterSpacing: -0.5, color: V1.ink900, marginBottom: 6 }}>Ko si ti?</div>
        <div style={{ fontSize: 13.5, color: V1.ink500, lineHeight: 1.5, marginBottom: 24 }}>
          Ime ti se ovako pojavljuje u javnoj listi CRTA posmatrača. Email koristimo za sva obaveštenja.
        </div>

        <Field1 label="Ime"><InputBase value={data.ime || ''} onChange={(e) => setData({ ...data, ime: e.target.value })} placeholder="Jovana"/></Field1>
        <Field1 label="Prezime"><InputBase value={data.prezime || ''} onChange={(e) => setData({ ...data, prezime: e.target.value })} placeholder="Đurović"/></Field1>
        <Field1 label="Email adresa" hint="Koristi onaj koji često otvaraš.">
          <InputBase type="email" value={data.email || ''} onChange={(e) => setData({ ...data, email: e.target.value })} placeholder="jovana@primer.rs"/>
        </Field1>
      </div>
      <BottomCTA label="Dalje" disabled={!ok} onClick={next}/>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// STEP 2 — JMBG + lična karta
// ═════════════════════════════════════════════════════════════
function StepID({ data, setData, step, total, prev, next }) {
  const jmbgOK = (data.jmbg || '').length === 13;
  const ok = jmbgOK && data.idFront && data.idBack;

  const photoSlot = (key, label) => (
    <Tap1 onClick={() => setData({ ...data, [key]: !data[key] })} style={{
      flex: 1, aspectRatio: '1.6 / 1', borderRadius: 12,
      background: data[key] ? V1.successBg : V1.ink100,
      border: '2px dashed ' + (data[key] ? V1.success : V1.ink300),
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8,
      color: data[key] ? V1.success : V1.ink500, position: 'relative', overflow: 'hidden',
    }}>
      {data[key] ? (
        <>
          <Chk1 size={28} sw={2.4}/>
          <span style={{ fontSize: 11.5, fontWeight: 500 }}>Slika učitana</span>
          <span style={{ position: 'absolute', top: 8, right: 8, fontSize: 10, fontFamily: V1.mono, color: V1.success, padding: '2px 6px', background: 'white', borderRadius: 4 }}>{label.toUpperCase()}</span>
        </>
      ) : (
        <>
          <Cam1 size={26}/>
          <span style={{ fontSize: 11.5, fontWeight: 500 }}>{label}</span>
          <span style={{ fontSize: 10, color: V1.ink400, fontFamily: V1.mono }}>tap za slikanje</span>
        </>
      )}
    </Tap1>
  );

  return (
    <div style={{ background: V1.paper, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: V1.font }}>
      <div style={{ paddingTop: 56 }} />
      <Progress step={step} total={total} onBack={prev}/>
      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 20px 16px' }}>
        <div style={{ fontSize: 24, fontWeight: 600, letterSpacing: -0.5, color: V1.ink900, marginBottom: 6 }}>Identifikacija</div>
        <div style={{ fontSize: 13.5, color: V1.ink500, lineHeight: 1.5, marginBottom: 24 }}>
          CRTA mora da potvrdi da si stvarna osoba (zakonski zahtev). Podaci su privatni — vide ih samo HR koordinacija i super admin.
        </div>

        <Field1 label="JMBG" hint="13 cifara · ne deli sa nikim drugim, ne pojavljuje se u listi posmatrača">
          <InputBase
            type="text" inputMode="numeric"
            value={data.jmbg || ''}
            onChange={(e) => setData({ ...data, jmbg: e.target.value.replace(/\D/g, '').slice(0, 13) })}
            placeholder="0102985710029"
            style={{ fontFamily: V1.mono, letterSpacing: 1 }}
          />
        </Field1>

        <div style={{ marginTop: 8 }}>
          <div style={{ fontSize: 12.5, fontWeight: 500, color: V1.ink600, marginBottom: 8 }}>Fotografija lične karte</div>
          <div style={{ display: 'flex', gap: 10 }}>
            {photoSlot('idFront', 'Prednja')}
            {photoSlot('idBack', 'Zadnja')}
          </div>
          <div style={{ marginTop: 8, fontSize: 11.5, color: V1.ink500 }}>
            Postavi karticu na ravnu površinu uz dobru svetlost. Slika treba da bude oštra i bez refleksija.
          </div>
        </div>

        <div style={{ marginTop: 18, padding: '12px 14px', background: V1.ink75, borderRadius: 10, display: 'flex', gap: 10, alignItems: 'flex-start' }}>
          <Lock size={14} style={{ marginTop: 1, color: V1.ink500 }}/>
          <div style={{ fontSize: 11.5, color: V1.ink600, lineHeight: 1.5 }}>
            JMBG i fotografije lične karte se čuvaju enkriptovani. Brišu se trajno 6 meseci posle završetka tvoje aktivnosti.
          </div>
        </div>
      </div>
      <BottomCTA label="Dalje" disabled={!ok} onClick={next}/>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// STEP 3 — Telefon + SMS
// ═════════════════════════════════════════════════════════════
function StepPhone({ data, setData, step, total, prev, next }) {
  const [stage, setStage] = React.useState(data.smsVerified ? 'verified' : 'enter'); // enter | code | verified
  const [code, setCode] = React.useState('');
  const [countdown, setCountdown] = React.useState(0);
  React.useEffect(() => {
    if (countdown <= 0) return;
    const t = setTimeout(() => setCountdown(c => c - 1), 1000);
    return () => clearTimeout(t);
  }, [countdown]);

  const phoneOK = /^[0-9]{8,10}$/.test((data.telefon || '').replace(/\s/g, ''));

  const sendCode = () => { setStage('code'); setCountdown(30); };
  const verifyCode = () => {
    if (code.length === 6) {
      setData({ ...data, smsVerified: true });
      setStage('verified');
    }
  };

  return (
    <div style={{ background: V1.paper, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: V1.font }}>
      <div style={{ paddingTop: 56 }} />
      <Progress step={step} total={total} onBack={prev}/>
      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 20px 16px' }}>
        {stage === 'enter' && (
          <>
            <div style={{ fontSize: 24, fontWeight: 600, letterSpacing: -0.5, color: V1.ink900, marginBottom: 6 }}>Tvoj broj telefona</div>
            <div style={{ fontSize: 13.5, color: V1.ink500, lineHeight: 1.5, marginBottom: 24 }}>
              Šaljemo SMS sa kodom za potvrdu. Broj koristimo za hitne pozive i poruke koordinatora.
            </div>
            <Field1 label="Broj telefona">
              <div style={{ display: 'flex', gap: 8 }}>
                <div style={{
                  width: 78, height: 50, background: 'white', border: '1px solid ' + V1.ink200,
                  borderRadius: 12, display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 15, fontWeight: 500, color: V1.ink900,
                }}>+381</div>
                <InputBase
                  type="text" inputMode="numeric"
                  value={data.telefon || ''}
                  onChange={(e) => setData({ ...data, telefon: e.target.value.replace(/\D/g, '').slice(0, 10) })}
                  placeholder="60 123 4567"
                  style={{ flex: 1, fontFamily: V1.mono }}
                />
              </div>
            </Field1>
          </>
        )}

        {stage === 'code' && (
          <>
            <div style={{ fontSize: 24, fontWeight: 600, letterSpacing: -0.5, color: V1.ink900, marginBottom: 6 }}>Unesi kod</div>
            <div style={{ fontSize: 13.5, color: V1.ink500, lineHeight: 1.5, marginBottom: 24 }}>
              Poslali smo 6-cifreni kod na <strong style={{ color: V1.ink900 }}>+381 {data.telefon}</strong>. SMS može stići za 1 minut.
            </div>

            <div style={{ display: 'flex', gap: 8, justifyContent: 'center', marginBottom: 24 }}>
              {[0, 1, 2, 3, 4, 5].map(i => (
                <div key={i} style={{
                  width: 44, height: 56, borderRadius: 10,
                  background: 'white', border: '1px solid ' + (i === code.length ? V1.ink900 : V1.ink200),
                  boxShadow: i === code.length ? '0 0 0 3px oklch(0.16 0.015 60 / 0.08)' : 'none',
                  display: 'grid', placeItems: 'center',
                  fontFamily: V1.mono, fontSize: 24, fontWeight: 600, color: V1.ink900,
                }}>
                  {code[i] || ''}
                </div>
              ))}
            </div>

            {/* Mock keypad for inputting code */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
              {['1', '2', '3', '4', '5', '6', '7', '8', '9', '', '0', '⌫'].map((k, i) => k === '' ? <div key={i}/> : (
                <Tap1 key={i} onClick={() => {
                  if (k === '⌫') setCode(code.slice(0, -1));
                  else if (code.length < 6) setCode(code + k);
                }} style={{
                  height: 56, background: 'white', border: '1px solid ' + V1.ink200,
                  borderRadius: 12, fontFamily: V1.mono, fontSize: 22, fontWeight: 500, color: V1.ink900,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>{k}</Tap1>
              ))}
            </div>

            <div style={{ textAlign: 'center', marginTop: 20, fontSize: 12.5, color: V1.ink500 }}>
              Nisi dobio SMS? {countdown > 0
                ? <span style={{ fontFamily: V1.mono }}>ponovo za {countdown}s</span>
                : <Tap1 onClick={() => setCountdown(30)} style={{ color: V1.ink900, fontWeight: 500, textDecoration: 'underline' }}>Pošalji ponovo</Tap1>
              }
            </div>
          </>
        )}

        {stage === 'verified' && (
          <>
            <div style={{ width: 64, height: 64, borderRadius: 18, background: V1.successBg, color: V1.success, display: 'grid', placeItems: 'center', marginBottom: 20 }}><Chk1 size={28} sw={2.6}/></div>
            <div style={{ fontSize: 24, fontWeight: 600, letterSpacing: -0.5, color: V1.ink900, marginBottom: 6 }}>Telefon potvrđen</div>
            <div style={{ fontSize: 13.5, color: V1.ink500, lineHeight: 1.5 }}>+381 {data.telefon}</div>
          </>
        )}
      </div>
      <BottomCTA
        label={stage === 'enter' ? 'Pošalji kod' : stage === 'code' ? 'Potvrdi kod' : 'Dalje'}
        disabled={stage === 'enter' ? !phoneOK : stage === 'code' ? code.length !== 6 : false}
        onClick={stage === 'enter' ? sendCode : stage === 'code' ? verifyCode : next}
      />
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// STEP 4 — Email verifikacija
// ═════════════════════════════════════════════════════════════
function StepEmail({ data, setData, step, total, prev, next }) {
  const [checking, setChecking] = React.useState(false);

  const recheck = () => {
    setChecking(true);
    setTimeout(() => { setData({ ...data, emailVerified: true }); setChecking(false); }, 1400);
  };

  return (
    <div style={{ background: V1.paper, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: V1.font }}>
      <div style={{ paddingTop: 56 }} />
      <Progress step={step} total={total} onBack={prev}/>
      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 20px 16px' }}>
        {!data.emailVerified ? (
          <>
            <div style={{ width: 72, height: 72, borderRadius: 20, background: V1.ink100, color: V1.ink700, display: 'grid', placeItems: 'center', marginBottom: 20, marginTop: 24 }}>
              <Mail size={32}/>
            </div>
            <div style={{ fontSize: 24, fontWeight: 600, letterSpacing: -0.5, color: V1.ink900, marginBottom: 6 }}>Potvrdi email</div>
            <div style={{ fontSize: 14, color: V1.ink600, lineHeight: 1.55, marginBottom: 20 }}>
              Poslali smo link za potvrdu na<br/>
              <strong style={{ color: V1.ink900 }}>{data.email}</strong>
            </div>
            <div style={{ padding: '14px 16px', background: 'white', border: '1px solid ' + V1.ink200, borderRadius: 12 }}>
              <div style={{ fontSize: 12, color: V1.ink600, lineHeight: 1.5 }}>
                Otvori email i klikni link „<strong style={{ color: V1.ink900, fontWeight: 600 }}>Potvrdi nalog</strong>". Vrati se ovde kada to uradiš.
              </div>
            </div>
            <Tap1 onClick={recheck} disabled={checking} style={{
              marginTop: 16, width: '100%', height: 46, background: 'white', border: '1px solid ' + V1.ink200,
              borderRadius: 12, color: V1.ink900, fontSize: 14, fontWeight: 500,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            }}>
              {checking ? <><Ring size={16}/> Proveravam…</> : 'Već sam kliknuo · proveri ponovo'}
            </Tap1>
            <Tap1 style={{ marginTop: 8, width: '100%', textAlign: 'center', fontSize: 12.5, color: V1.ink500, padding: '8px 0' }}>
              Pošalji email ponovo
            </Tap1>
          </>
        ) : (
          <>
            <div style={{ width: 64, height: 64, borderRadius: 18, background: V1.successBg, color: V1.success, display: 'grid', placeItems: 'center', marginBottom: 20, marginTop: 24 }}><Chk1 size={28} sw={2.6}/></div>
            <div style={{ fontSize: 24, fontWeight: 600, letterSpacing: -0.5, color: V1.ink900, marginBottom: 6 }}>Email potvrđen</div>
            <div style={{ fontSize: 13.5, color: V1.ink500, lineHeight: 1.5 }}>{data.email}</div>
          </>
        )}
      </div>
      <BottomCTA label="Dalje" disabled={!data.emailVerified} onClick={next}/>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// STEP 5 — Consent
// ═════════════════════════════════════════════════════════════
function StepConsent({ data, setData, step, total, prev, next }) {
  const all = data.cGDPR && data.cPublic && data.cKodeks;
  const items = [
    { k: 'cGDPR',   t: 'Obrada ličnih podataka', s: 'Slažem se sa Vigilo politikom privatnosti i Zakonom o zaštiti podataka o ličnosti.', link: 'Politika privatnosti' },
    { k: 'cPublic', t: 'Javna lista posmatrača', s: 'Pristajem da se moje ime, prezime i tip posmatrača nalaze u javnoj listi posmatrača CRTE.', link: 'Pravila objavljivanja' },
    { k: 'cKodeks', t: 'Kodeks ponašanja',       s: 'Pročitao/la sam kodeks ponašanja CRTA posmatrača i prihvatam ga u potpunosti.',                  link: 'Kodeks ponašanja' },
  ];

  return (
    <div style={{ background: V1.paper, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: V1.font }}>
      <div style={{ paddingTop: 56 }} />
      <Progress step={step} total={total} onBack={prev}/>
      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 20px 16px' }}>
        <div style={{ fontSize: 24, fontWeight: 600, letterSpacing: -0.5, color: V1.ink900, marginBottom: 6 }}>Saglasnosti</div>
        <div style={{ fontSize: 13.5, color: V1.ink500, lineHeight: 1.5, marginBottom: 20 }}>
          Sve tri saglasnosti su obavezne — bez njih ne možeš biti posmatrač.
        </div>

        {items.map((it, i) => (
          <Tap1 key={it.k} onClick={() => setData({ ...data, [it.k]: !data[it.k] })} style={{
            display: 'flex', gap: 12, padding: '14px',
            background: 'white', border: '1px solid ' + (data[it.k] ? V1.ink950 : V1.ink200),
            borderRadius: 12, marginBottom: 10, textAlign: 'left',
            boxShadow: data[it.k] ? '0 0 0 1px ' + V1.ink950 : 'none',
            transition: 'border-color 80ms, box-shadow 80ms',
          }}>
            <div style={{
              flexShrink: 0, width: 22, height: 22, borderRadius: 6,
              background: data[it.k] ? V1.ink950 : 'white',
              border: '1.5px solid ' + (data[it.k] ? V1.ink950 : V1.ink300),
              display: 'grid', placeItems: 'center', marginTop: 1,
            }}>
              {data[it.k] && <Chk1 size={14} sw={3} style={{ color: 'white' }}/>}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: V1.ink900, marginBottom: 4 }}>{it.t}</div>
              <div style={{ fontSize: 12.5, color: V1.ink600, lineHeight: 1.5 }}>{it.s}</div>
              <span style={{ display: 'inline-block', marginTop: 6, fontSize: 11.5, color: V1.info, fontWeight: 500, textDecoration: 'underline' }}>{it.link}</span>
            </div>
          </Tap1>
        ))}
      </div>
      <BottomCTA label="Završi registraciju" disabled={!all} onClick={next}/>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// STEP 6 — Success
// ═════════════════════════════════════════════════════════════
function StepDone({ data, reset }) {
  return (
    <div style={{ background: V1.paper, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: V1.font }}>
      <div style={{ paddingTop: 80, padding: '80px 24px 16px', flex: 1, display: 'flex', flexDirection: 'column' }}>
        <div style={{
          width: 72, height: 72, borderRadius: 20, background: V1.successBg, color: V1.success,
          display: 'grid', placeItems: 'center', marginBottom: 24,
          boxShadow: '0 0 0 8px oklch(0.62 0.155 152 / 0.1)',
        }}><Chk1 size={32} sw={2.6}/></div>

        <div style={{ fontSize: 28, fontWeight: 600, letterSpacing: -0.6, color: V1.ink900, lineHeight: 1.1, marginBottom: 10 }}>
          Hvala, {data.ime || 'Jovana'}.
        </div>
        <div style={{ fontSize: 15, color: V1.ink600, lineHeight: 1.55, marginBottom: 24 }}>
          Tvoj zahtev je poslat HR koordinaciji. Dobićeš obaveštenje na <strong style={{ color: V1.ink900 }}>{data.email}</strong> i SMS na <strong style={{ color: V1.ink900 }}>+381 {data.telefon}</strong> kada budeš odobren/a.
        </div>

        <div style={{ background: 'white', border: '1px solid ' + V1.ink200, borderRadius: 14 }}>
          <div style={{ padding: '14px 16px', borderBottom: '1px solid ' + V1.ink150 }}>
            <div style={{ fontSize: 10.5, fontFamily: V1.mono, textTransform: 'uppercase', letterSpacing: 0.06, color: V1.ink400, marginBottom: 4 }}>Status prijave</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{ width: 8, height: 8, borderRadius: '50%', background: V1.warning, animation: 'm1pulse 1.6s ease-in-out infinite' }}/>
              <span style={{ fontSize: 14, fontWeight: 600, color: V1.ink900 }}>Čeka odobrenje koordinatora</span>
            </div>
            <div style={{ fontSize: 11.5, color: V1.ink500, marginTop: 4 }}>Obično 1–2 radna dana.</div>
          </div>
          <div style={{ padding: '14px 16px' }}>
            <div style={{ fontSize: 10.5, fontFamily: V1.mono, textTransform: 'uppercase', letterSpacing: 0.06, color: V1.ink400, marginBottom: 8 }}>U međuvremenu</div>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 0' }}>
              <div style={{ width: 28, height: 28, borderRadius: 8, background: V1.ink100, color: V1.ink700, display: 'grid', placeItems: 'center', flexShrink: 0 }}><Spark1 size={15}/></div>
              <div>
                <div style={{ fontSize: 13.5, fontWeight: 500, color: V1.ink900 }}>Pokreni obuku</div>
                <div style={{ fontSize: 11.5, color: V1.ink500, marginTop: 1 }}>8 modula · ~45 min · možeš krenuti odmah</div>
              </div>
            </div>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 0' }}>
              <div style={{ width: 28, height: 28, borderRadius: 8, background: V1.ink100, color: V1.ink700, display: 'grid', placeItems: 'center', flexShrink: 0 }}><Mail size={15}/></div>
              <div>
                <div style={{ fontSize: 13.5, fontWeight: 500, color: V1.ink900 }}>Proveri dobrodošlicu</div>
                <div style={{ fontSize: 11.5, color: V1.ink500, marginTop: 1 }}>Email od coordinator@crta.rs sa narednim koracima</div>
              </div>
            </div>
          </div>
        </div>

        <div style={{ flex: 1 }} />
      </div>
      <div style={{ padding: '14px 16px 36px' }}>
        <Tap1 style={{
          width: '100%', height: 54, background: V1.ink950, color: 'white',
          borderRadius: 14, fontFamily: V1.font, fontSize: 16, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>Pokreni obuku <ArrowR1 size={18} sw={2.4}/></Tap1>
        <Tap1 onClick={reset} style={{ marginTop: 8, width: '100%', textAlign: 'center', fontSize: 13, color: V1.ink600, padding: '8px 0' }}>
          Vidi pregled koraka
        </Tap1>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Flow
// ─────────────────────────────────────────────────────────────
function OnboardingFlow({ tweaks, initialData }) {
  const [step, setStep] = React.useState(tweaks.step ?? 0);
  const [data, setData] = React.useState(initialData);

  React.useEffect(() => { setStep(tweaks.step ?? 0); setData(initialData); }, [tweaks.step, tweaks.prefill]);

  const TOTAL = 5; // koraci u progress baru (welcome i done su van)
  const next  = () => setStep(s => Math.min(s + 1, 6));
  const prev  = () => setStep(s => Math.max(0, s - 1));
  const reset = () => setStep(0);

  if (step === 0) return <StepWelcome next={() => setStep(1)}/>;
  if (step === 1) return <StepBasic   data={data} setData={setData} step={0} total={TOTAL} prev={() => setStep(0)} next={() => setStep(2)}/>;
  if (step === 2) return <StepID      data={data} setData={setData} step={1} total={TOTAL} prev={() => setStep(1)} next={() => setStep(3)}/>;
  if (step === 3) return <StepPhone   data={data} setData={setData} step={2} total={TOTAL} prev={() => setStep(2)} next={() => setStep(4)}/>;
  if (step === 4) return <StepEmail   data={data} setData={setData} step={3} total={TOTAL} prev={() => setStep(3)} next={() => setStep(5)}/>;
  if (step === 5) return <StepConsent data={data} setData={setData} step={4} total={TOTAL} prev={() => setStep(4)} next={() => setStep(6)}/>;
  return <StepDone data={data} reset={reset}/>;
}

const m1styles = document.createElement('style');
m1styles.textContent = `@keyframes m1pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } }`;
document.head.appendChild(m1styles);

Object.assign(window, { OnboardingFlow });
