/* ════════════════════════════════════════════════
   Halaman Pendaftaran Santri — form multi-langkah
   ════════════════════════════════════════════════ */
function RegisterPage({ navigate }) {
  const M = window.MQA || {};
  const [programs, setPrograms] = useState(M.programs || []);
  useEffect(() => {
    api.get('content.php?action=get_section&section=programs').then(r => {
      const arr = (r.ok && r.data && Array.isArray(r.data.items)) ? r.data.items : null;
      if (arr && arr.length) setPrograms(arr);
    }).catch(() => {});
  }, []);
  const [step, setStep] = useState(1);
  const [done, setDone] = useState(false);
  const [sending, setSending] = useState(false);
  const [form, setForm] = useState({
    name: '', usia: '', gender: 'Ikhwan',
    program: programs[0] ? programs[0].name : '', level: '',
    parent_name: '', phone: '', email: '', address: '', notes: '',
  });
  const upd = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const steps = ['Data Santri', 'Pilih Program', 'Kontak'];
  const canNext = step === 1 ? (form.name && form.usia) : step === 2 ? form.program : true;

  const selProgram = programs.find(p => p.name === form.program);
  const levels = selProgram ? (Array.isArray(selProgram.levels) ? selProgram.levels : []) : [];
  // Saat program dari dashboard termuat, pastikan pilihan default valid
  useEffect(() => {
    if (programs.length && !programs.some(p => p.name === form.program)) {
      setForm(f => ({ ...f, program: programs[0].name, level: '' }));
    }
  }, [programs]);

  const submit = async () => {
    if (!form.parent_name || !form.phone) return;
    setSending(true);
    try {
      await api.post('registrations.php?action=submit', form);
      setDone(true);
    } finally { setSending(false); }
  };

  if (done) {
    return (
      <div style={{ background: 'var(--bg)', minHeight: '80vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
        <div style={{ background: 'var(--surface)', borderRadius: 22, padding: '48px 40px', maxWidth: 440, textAlign: 'center', border: '1px solid var(--border-soft)', boxShadow: 'var(--shadow-warm-md)' }}>
          <div style={{ fontSize: 56, marginBottom: 16 }}>🎉</div>
          <div style={{ fontFamily: 'var(--font-d)', fontSize: 26, fontWeight: 900, color: 'var(--ink-deep)', marginBottom: 10 }}>Pendaftaran Terkirim!</div>
          <p style={{ color: 'var(--muted)', fontSize: 14.5, lineHeight: 1.6, marginBottom: 24 }}>Terima kasih telah mendaftarkan <strong style={{ color: 'var(--ink-deep)' }}>{form.name}</strong>. Tim kami akan menghubungi Anda via WhatsApp dalam 1×24 jam.</p>
          <button onClick={() => window.open('https://wa.me/628123456789?text=' + encodeURIComponent(`Assalamu'alaikum, saya baru mendaftarkan ${form.name} untuk program ${form.program}.`), '_blank')} style={{ width: '100%', padding: '13px', borderRadius: 12, border: 'none', background: '#25D366', color: '#fff', fontSize: 15, fontWeight: 800, cursor: 'pointer', fontFamily: 'inherit', marginBottom: 10 }}>💬 Hubungi via WhatsApp</button>
          <button onClick={() => navigate('home')} style={{ width: '100%', padding: '12px', borderRadius: 12, border: '1.5px solid var(--border)', background: 'var(--surface)', color: 'var(--ink-deep)', fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>Kembali ke Beranda</button>
        </div>
      </div>
    );
  }

  return (
    <div style={{ background: 'var(--bg)', minHeight: '70vh' }}>
      <PageBand pageKey="register" kicker="Penerimaan Santri Baru 2026" title="Formulir Pendaftaran" sub="Isi data berikut. Gratis, tanpa biaya pendaftaran." />
      <div className="container" style={{ maxWidth: 600, margin: '0 auto', padding: '30px 20px 70px' }}>
        {/* Stepper */}
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 28 }}>
          {steps.map((s, i) => {
            const n = i + 1, active = n === step, doneStep = n < step;
            return (
              <React.Fragment key={s}>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
                  <div style={{ width: 36, height: 36, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 14, background: active || doneStep ? 'var(--sage)' : 'var(--bg2)', color: active || doneStep ? '#fff' : 'var(--muted)' }}>{doneStep ? '✓' : n}</div>
                  <span style={{ fontSize: 11.5, fontWeight: 700, color: active ? 'var(--ink-deep)' : 'var(--muted)' }}>{s}</span>
                </div>
                {i < steps.length - 1 && <div style={{ flex: 1, height: 2, background: n < step ? 'var(--sage)' : 'var(--border)', margin: '0 8px', marginBottom: 18 }} />}
              </React.Fragment>
            );
          })}
        </div>

        <div style={{ background: 'var(--surface)', borderRadius: 18, padding: '28px 30px', border: '1px solid var(--border-soft)', boxShadow: 'var(--shadow-warm-sm, 0 4px 14px rgba(120,80,30,.06))' }}>
          {step === 1 && (
            <>
              <Field label="Nama Lengkap Santri *"><input value={form.name} onChange={e => upd('name', e.target.value)} placeholder="Nama santri" style={inp} /></Field>
              <Field label="Usia *"><input value={form.usia} onChange={e => upd('usia', e.target.value)} placeholder="contoh: 9 tahun / Dewasa" style={inp} /></Field>
              <Field label="Jenis Kelamin">
                <div style={{ display: 'flex', gap: 10 }}>
                  {['Ikhwan', 'Akhwat'].map(g => (
                    <button key={g} type="button" onClick={() => upd('gender', g)} style={{ flex: 1, padding: '11px', borderRadius: 10, border: `1.5px solid ${form.gender === g ? 'var(--sage)' : 'var(--border)'}`, background: form.gender === g ? 'rgba(31,107,71,.1)' : 'var(--surface)', color: form.gender === g ? 'var(--sage)' : 'var(--ink-deep)', fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>{g}</button>
                  ))}
                </div>
              </Field>
            </>
          )}
          {step === 2 && (
            <>
              <Field label="Pilih Program *">
                <div style={{ display: 'grid', gap: 10 }}>
                  {programs.map(p => (
                    <button key={p.id} type="button" onClick={() => { upd('program', p.name); upd('level', ''); }} style={{ textAlign: 'left', padding: '14px 16px', borderRadius: 12, border: `1.5px solid ${form.program === p.name ? 'var(--sage)' : 'var(--border)'}`, background: form.program === p.name ? 'rgba(31,107,71,.07)' : 'var(--surface)', cursor: 'pointer', fontFamily: 'inherit', display: 'flex', gap: 12, alignItems: 'center' }}>
                      <span style={{ fontSize: 26 }}>{p.icon || '📗'}</span>
                      <span><span style={{ display: 'block', fontWeight: 800, fontSize: 15, color: 'var(--ink-deep)' }}>{p.name}</span><span style={{ fontSize: 12.5, color: 'var(--muted)' }}>{p.schedule || ''}</span></span>
                    </button>
                  ))}
                </div>
              </Field>
              {levels.length > 0 && (
                <Field label="Level / Tingkat">
                  <select value={form.level} onChange={e => upd('level', e.target.value)} style={inp}>
                    <option value="">— Pilih level —</option>
                    {levels.map((l, i) => <option key={i} value={l}>{l}</option>)}
                  </select>
                </Field>
              )}
            </>
          )}
          {step === 3 && (
            <>
              <Field label="Nama Orang Tua / Wali *"><input value={form.parent_name} onChange={e => upd('parent_name', e.target.value)} placeholder="Nama wali" style={inp} /></Field>
              <Field label="Nomor WhatsApp *"><input value={form.phone} onChange={e => upd('phone', e.target.value.replace(/[^\d+]/g, ''))} placeholder="08xxxxxxxxxx" style={inp} /></Field>
              <Field label="Email (opsional)"><input type="email" value={form.email} onChange={e => upd('email', e.target.value)} placeholder="email@contoh.com" style={inp} /></Field>
              <Field label="Alamat (opsional)"><textarea value={form.address} onChange={e => upd('address', e.target.value)} rows="2" style={{ ...inp, resize: 'vertical' }} /></Field>
              <div style={{ background: 'var(--bg2)', borderRadius: 12, padding: '14px 16px', fontSize: 13, color: 'var(--ink)', lineHeight: 1.6 }}>
                <strong style={{ color: 'var(--ink-deep)' }}>Ringkasan:</strong> {form.name} ({form.usia}, {form.gender}) — {form.program}{form.level ? ` · ${form.level}` : ''}
              </div>
            </>
          )}

          <div style={{ display: 'flex', gap: 10, marginTop: 22 }}>
            {step > 1 && <button onClick={() => setStep(step - 1)} className="btn-hero-secondary" style={{ flex: '0 0 auto' }}>← Kembali</button>}
            {step < 3
              ? <button onClick={() => canNext && setStep(step + 1)} disabled={!canNext} className="btn-hero-primary" style={{ flex: 1, justifyContent: 'center', opacity: canNext ? 1 : .5 }}>Lanjut →</button>
              : <button onClick={submit} disabled={sending || !form.parent_name || !form.phone} className="btn-hero-primary" style={{ flex: 1, justifyContent: 'center', opacity: (sending || !form.parent_name || !form.phone) ? .5 : 1 }}>{sending ? 'Mengirim…' : 'Kirim Pendaftaran'}</button>}
          </div>
        </div>
      </div>
    </div>
  );
}

window.RegisterPage = RegisterPage;
