// SetupWizard.jsx — İlk açılış: yönetici hesabı oluştur
const { useState: useStateSW, useEffect: useEffectSW } = React;

function SetupWizard({ onComplete }) {
  const [step, setStep] = useStateSW(1);
  const [name, setName] = useStateSW('');
  const [phoneDigits, setPhoneDigits] = useStateSW('');
  const [pin, setPin] = useStateSW('');
  const [error, setError] = useStateSW(null);
  const [submitting, setSubmitting] = useStateSW(false);

  const phoneOk = phoneDigits.length === 10;

  const goStep1Next = () => {
    setError(null);
    if (!name.trim()) { setError('Ad gerekli'); return; }
    if (!phoneOk) { setError('Geçerli bir telefon gir (10 hane)'); return; }
    setStep(2);
  };

  // Step 2 onSubmit: save the chosen pin and advance to confirm
  const handleSetPin = async (entered) => {
    setPin(entered);
    setError(null);
    setStep(3);
    return true;
  };

  // Step 3 onSubmit: must match step 2 pin, then create admin
  const submitFinal = async (confirmedPin) => {
    if (confirmedPin !== pin) {
      setError('PIN\'ler eşleşmiyor');
      return false;
    }
    setError(null);
    setSubmitting(true);
    try {
      await Store.setupAdmin(name.trim(), '+90' + phoneDigits, pin);
      onComplete();
      return true;
    } catch (e) {
      setError(e.message || 'Kurulum başarısız');
      setSubmitting(false);
      return false;
    }
  };

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 300, background: 'var(--bg)',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      paddingTop: 'max(20px, env(safe-area-inset-top, 20px))',
      paddingBottom: 'max(20px, env(safe-area-inset-bottom, 20px))',
      paddingLeft: 24, paddingRight: 24,
    }}>
      <div style={{ width: '100%', maxWidth: 400, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 18 }}>
        <div style={{ width: 56, height: 56, background: 'var(--accent)', borderRadius: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 28 }}>☕</div>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontWeight: 800, fontSize: 22, letterSpacing: '-0.02em' }}>adisyon</div>
          <div style={{ fontSize: 12, color: 'var(--text-3)', fontWeight: 500, letterSpacing: '0.06em', textTransform: 'uppercase' }}>ilk kurulum</div>
        </div>

        <div style={{ width: '100%', background: 'white', borderRadius: 18, boxShadow: 'var(--shadow-lg)', padding: 24 }}>
          {/* Step indicator */}
          <div style={{ display: 'flex', gap: 6, justifyContent: 'center', marginBottom: 20 }}>
            {[1, 2, 3].map((n) => (
              <div key={n} style={{
                width: n === step ? 24 : 8, height: 8, borderRadius: 4,
                background: n <= step ? 'var(--accent)' : 'var(--border)',
                transition: 'all 0.2s',
              }} />
            ))}
          </div>

          {step === 1 && (
            <>
              <div style={{ fontWeight: 700, fontSize: 18, marginBottom: 4 }}>Yönetici Hesabı</div>
              <div style={{ color: 'var(--text-2)', fontSize: 13, marginBottom: 18 }}>
                Adını ve telefonunu gir. Daha sonra giriş yaparken kullanacaksın.
              </div>

              <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: 'var(--text-2)', marginBottom: 6 }}>Ad Soyad</label>
              <input className="input" value={name} onChange={(e) => { setName(e.target.value); setError(null); }}
                placeholder="Örn. Ali Yılmaz" autoFocus
                style={{ marginBottom: 14, fontSize: 16, padding: '12px 14px' }} />

              <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: 'var(--text-2)', marginBottom: 6 }}>Telefon</label>
              <div style={{ display: 'flex', alignItems: 'stretch', border: '2px solid var(--border)', borderRadius: 12, overflow: 'hidden', marginBottom: 16 }}>
                <div style={{ display: 'flex', alignItems: 'center', padding: '0 12px', background: 'var(--bg)', fontSize: 16, fontWeight: 600, color: 'var(--text-2)' }}>+90</div>
                <input type="tel" inputMode="numeric" autoComplete="tel-national"
                  placeholder="5XX XXX XX XX"
                  value={window.formatPhoneInput(phoneDigits)}
                  onChange={(e) => { const d = e.target.value.replace(/\D/g, '').slice(0, 10); setPhoneDigits(d); setError(null); }}
                  style={{ flex: 1, padding: '14px 14px', border: 'none', outline: 'none', fontFamily: 'inherit', fontSize: 17, fontWeight: 600, letterSpacing: '0.04em' }} />
              </div>

              {error && <div style={{ color: 'var(--red)', fontSize: 13, marginBottom: 12, fontWeight: 600 }}>{error}</div>}

              <button className="btn btn-primary" style={{ width: '100%', padding: '14px 0', fontSize: 15 }}
                disabled={!name.trim() || !phoneOk}
                onClick={goStep1Next}>
                Devam Et →
              </button>
            </>
          )}

          {step === 2 && (
            <>
              <div style={{ fontWeight: 700, fontSize: 18, marginBottom: 4 }}>PIN Belirle</div>
              <div style={{ color: 'var(--text-2)', fontSize: 13, marginBottom: 18 }}>
                Giriş yaparken kullanacağın 6 haneli PIN'i belirle.
              </div>

              <window.PinInput length={6} onSubmit={handleSetPin} error={error} autoFocus />

              <button className="btn btn-ghost" style={{ width: '100%', marginTop: 14 }}
                onClick={() => { setStep(1); setError(null); }}>← Geri</button>
            </>
          )}

          {step === 3 && (
            <>
              <div style={{ fontWeight: 700, fontSize: 18, marginBottom: 4 }}>PIN'i Onayla</div>
              <div style={{ color: 'var(--text-2)', fontSize: 13, marginBottom: 18 }}>
                Aynı PIN'i tekrar gir.
              </div>

              <window.PinInput length={6} onSubmit={submitFinal} error={error} disabled={submitting} autoFocus />

              {submitting && <div style={{ marginTop: 12, textAlign: 'center', color: 'var(--text-2)', fontSize: 13 }}>Kuruluyor…</div>}

              <button className="btn btn-ghost" style={{ width: '100%', marginTop: 14 }} disabled={submitting}
                onClick={() => { setStep(2); setPin(''); setError(null); }}>← PIN'i değiştir</button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SetupWizard });
