/* =====================================================================
   Brodemy · Auth Modal (Giriş / Kayıt)
   Modal modu — herhangi bir sayfadan tetiklenebilir
   Mobile'da full-screen, desktop'ta centered
   ===================================================================== */

function AuthModal({ open, mode, onClose, onModeChange }) {
  const [showPw, setShowPw] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [success, setSuccess] = React.useState(false);

  React.useEffect(() => {
    if (!open) return;
    setError(null);
    setSuccess(false);
    setLoading(false);
    const onEsc = (e) => e.key === 'Escape' && onClose();
    document.addEventListener('keydown', onEsc);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onEsc);
      document.body.style.overflow = '';
    };
  }, [open, onClose]);

  if (!open) return null;

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    try {
      const fd = new FormData(e.target);
      const email = fd.get('email') || e.target.querySelector('input[type="email"]')?.value;
      const password = fd.get('password') || e.target.querySelector('input[type="password"]')?.value;
      if (!email || !password) {
        setError({ field: 'email', message: 'E-posta ve şifre zorunlu.' });
        setLoading(false);
        return;
      }
      if (typeof window === 'undefined' || !window.BrodemyAPI) {
        setError({ field: 'password', message: 'API helper yüklenemedi (refresh dene).' });
        setLoading(false);
        return;
      }
      if (mode === 'login') {
        const r = await window.BrodemyAPI.login(email, password);
        if (!r.ok) {
          setError({ field: 'password', message: r.data?.error || 'E-posta veya şifre hatalı.' });
        } else {
          // Başarılı — sayfa state'i yenile
          setSuccess(true);
          setTimeout(() => {
            if (typeof window !== 'undefined') window.location.reload();
          }, 400);
        }
      } else {
        const firstName = fd.get('firstName') || e.target.querySelector('input[name="firstName"]')?.value || '';
        const lastName  = fd.get('lastName')  || e.target.querySelector('input[name="lastName"]')?.value  || '';
        const r = await window.BrodemyAPI.register({ firstName, lastName, email, password });
        if (!r.ok) {
          setError({ field: 'email', message: r.data?.error || 'Kayıt sırasında bir hata oluştu.' });
        } else {
          setSuccess(true);
        }
      }
    } catch (err) {
      setError({ field: 'password', message: err.message || 'Bir hata oluştu.' });
    } finally {
      setLoading(false);
    }
  };

  const isRegister = mode === 'register';

  return (
    <div
      className="fixed inset-0 z-[60] flex items-end md:items-center justify-center md:p-4"
      style={{ animation: 'scrim-in 200ms ease-out' }}
      onClick={onClose}
    >
      <div className="absolute inset-0 bg-ink/70 backdrop-blur-sm"></div>

      <div
        className="relative w-full md:max-w-[440px] bg-paper md:rounded-[20px] rounded-t-[20px] shadow-[0_24px_80px_rgba(0,0,0,0.5)] overflow-hidden flex flex-col max-h-[100dvh] md:max-h-[calc(100dvh-32px)]"
        style={{ animation: 'modal-in 280ms cubic-bezier(0.16, 1, 0.3, 1)' }}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between p-5 md:p-6 border-b border-rule flex-shrink-0">
          <Logo size="sm" />
          <button onClick={onClose} className="w-9 h-9 grid place-items-center rounded-md hover:bg-mist text-fg-2">
            <Icon name="x" size={20} />
          </button>
        </div>

        {/* Mobile drag handle */}
        <div className="md:hidden mx-auto mt-2 mb-1 w-10 h-1 rounded-full bg-slate-300"></div>

        {/* Tabs */}
        {!success && (
          <div className="px-5 md:px-6 pt-4 md:pt-5">
            <div className="grid grid-cols-2 gap-1 p-1 bg-mist rounded-[10px]">
              <button onClick={() => onModeChange('login')}
                      className={`py-2.5 rounded-[7px] text-[13px] font-semibold transition-all ${!isRegister ? 'bg-white text-ink shadow-[var(--shadow-card)]' : 'text-fg-2'}`}>
                Giriş
              </button>
              <button onClick={() => onModeChange('register')}
                      className={`py-2.5 rounded-[7px] text-[13px] font-semibold transition-all ${isRegister ? 'bg-white text-ink shadow-[var(--shadow-card)]' : 'text-fg-2'}`}>
                Kayıt Ol
              </button>
            </div>
          </div>
        )}

        {/* Content */}
        <div className="px-5 md:px-6 py-5 md:py-6 overflow-y-auto flex-1">

          {success && isRegister ? <RegisterSuccess /> : isRegister ? (
            <RegisterForm onSubmit={handleSubmit} loading={loading} error={error} />
          ) : (
            <LoginForm onSubmit={handleSubmit} loading={loading} error={error} showPw={showPw} setShowPw={setShowPw} />
          )}

          {!success && (
            <>
              <div className="flex items-center gap-3 my-5">
                <div className="flex-1 h-px bg-rule"></div>
                <span className="text-[11px] text-fg-3 font-mono uppercase tracking-[0.08em]">veya</span>
                <div className="flex-1 h-px bg-rule"></div>
              </div>

              <button className="w-full py-3 px-4 border border-rule-strong rounded-[10px] flex items-center justify-center gap-3 hover:bg-mist transition-colors">
                <svg width="18" height="18" viewBox="0 0 18 18"><path d="M17.64 9.20c0-.637-.057-1.251-.164-1.84H9v3.481h4.844c-.209 1.125-.843 2.078-1.796 2.716v2.258h2.908c1.702-1.567 2.684-3.874 2.684-6.615z" fill="#4285F4"/><path d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332C2.438 15.983 5.482 18 9 18z" fill="#34A853"/><path d="M3.964 10.71c-.18-.54-.282-1.117-.282-1.71s.102-1.17.282-1.71V4.958H.957C.347 6.173 0 7.548 0 9s.348 2.827.957 4.042l3.007-2.332z" fill="#FBBC05"/><path d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0 5.482 0 2.438 2.017.957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z" fill="#EA4335"/></svg>
                <span className="text-[14px] font-semibold text-ink">Google ile devam et</span>
              </button>

              <div className="text-center mt-6 text-[13px] text-fg-2">
                {isRegister ? (
                  <>Hesabın var mı? <button onClick={() => onModeChange('login')} className="text-brand-600 font-semibold hover:text-accent-500">Giriş yap</button></>
                ) : (
                  <>Hesabın yok mu? <button onClick={() => onModeChange('register')} className="text-brand-600 font-semibold hover:text-accent-500">Hemen oluştur</button></>
                )}
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function LoginForm({ onSubmit, loading, error, showPw, setShowPw }) {
  return (
    <form onSubmit={onSubmit} className="space-y-4">
      <div>
        <div className="font-display font-bold text-[26px] tracking-[-0.03em] text-ink leading-[1] mb-1">Hoş geldin, devam edelim.</div>
        <p className="text-[14px] text-fg-2">Hesabına giriş yap, eğitimlerine kaldığın yerden devam et.</p>
      </div>

      <div className="space-y-1.5">
        <label className="text-[13px] font-semibold text-ink">E-posta</label>
        <input type="email" name="email" required placeholder="ad@email.com"
               className="w-full px-3.5 py-3 bg-white border border-rule-strong rounded-[10px] text-[14px] focus:outline-none focus:border-brand-500 focus:ring-[3px] focus:ring-brand-500/15 transition-all" />
      </div>

      <div className="space-y-1.5">
        <div className="flex justify-between items-center">
          <label className="text-[13px] font-semibold text-ink">Şifre</label>
          <a href="#" className="text-[12px] text-brand-600 font-medium hover:text-accent-500">Şifremi unuttum</a>
        </div>
        <div className={`flex items-center bg-white border rounded-[10px] transition-all ${error ? 'border-red-700 ring-[3px] ring-red-700/10' : 'border-rule-strong focus-within:border-brand-500 focus-within:ring-[3px] focus-within:ring-brand-500/15'}`}>
          <input type={showPw ? 'text' : 'password'} name="password" required placeholder="Şifreniz"
                 className="flex-1 px-3.5 py-3 bg-transparent border-none outline-none text-[14px]" />
          <button type="button" onClick={() => setShowPw(!showPw)} className="px-3 text-fg-3 hover:text-ink">
            <Icon name={showPw ? 'eyeOff' : 'eye'} size={16} />
          </button>
        </div>
        {error && (
          <div className="flex items-start gap-1.5 text-[12px] text-red-700 mt-2">
            <Icon name="alert" size={14} className="flex-shrink-0 mt-0.5" />
            <span>{error.message}</span>
          </div>
        )}
      </div>

      <div className="flex items-center gap-2 pt-1">
        <input type="checkbox" id="remember" defaultChecked className="sr-only" />
        <label htmlFor="remember" className="flex items-center gap-2 cursor-pointer">
          <span className="w-[18px] h-[18px] rounded-[5px] border-[1.5px] border-rule-strong bg-brand-500 border-brand-500 grid place-items-center">
            <Icon name="check" size={11} strokeWidth={3} className="text-white" />
          </span>
          <span className="text-[13px] text-fg-2">Beni hatırla</span>
        </label>
      </div>

      <Button variant="primary" size="lg" className="w-full mt-2" type="submit" disabled={loading}>
        {loading ? 'Doğrulanıyor…' : 'Giriş Yap'}
      </Button>
    </form>
  );
}

function RegisterForm({ onSubmit, loading, error }) {
  const [pw, setPw] = React.useState('');
  const [kvkk, setKvkk] = React.useState(false);
  const strong = pw.length >= 8;

  return (
    <form onSubmit={onSubmit} className="space-y-4">
      <div>
        <div className="font-display font-bold text-[26px] tracking-[-0.03em] text-ink leading-[1] mb-1">Hesap oluştur, hemen başla.</div>
        <p className="text-[14px] text-fg-2">30 saniyede hesabını oluştur, ücretsiz önizleme dersleri seni bekliyor.</p>
      </div>

      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-1.5">
          <label className="text-[13px] font-semibold text-ink">Ad <span className="text-red-700">*</span></label>
          <input type="text" name="firstName" required placeholder="Hatice"
                 className="w-full px-3.5 py-3 bg-white border border-rule-strong rounded-[10px] text-[14px] focus:outline-none focus:border-brand-500 focus:ring-[3px] focus:ring-brand-500/15 transition-all" />
        </div>
        <div className="space-y-1.5">
          <label className="text-[13px] font-semibold text-ink">Soyad <span className="text-red-700">*</span></label>
          <input type="text" name="lastName" required placeholder="Gümüş"
                 className="w-full px-3.5 py-3 bg-white border border-rule-strong rounded-[10px] text-[14px] focus:outline-none focus:border-brand-500 focus:ring-[3px] focus:ring-brand-500/15 transition-all" />
        </div>
      </div>

      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-1.5">
          <label className="text-[13px] font-semibold text-ink">E-posta <span className="text-red-700">*</span></label>
          <input type="email" name="email" required placeholder="ad@email.com"
                 className="w-full px-3.5 py-3 bg-white border border-rule-strong rounded-[10px] text-[14px] focus:outline-none focus:border-brand-500 focus:ring-[3px] focus:ring-brand-500/15 transition-all" />
        </div>
        <div className="space-y-1.5">
          <label className="text-[13px] font-semibold text-ink">Telefon</label>
          <div className="flex items-center bg-white border border-rule-strong rounded-[10px] focus-within:border-brand-500 focus-within:ring-[3px] focus-within:ring-brand-500/15 transition-all">
            <span className="pl-3 text-[14px] text-fg-3 font-medium">+90</span>
            <input type="tel" name="phone" placeholder="555 000 00 00"
                   className="flex-1 pl-2 pr-3.5 py-3 bg-transparent border-none outline-none text-[14px]" />
          </div>
        </div>
      </div>

      <div className="space-y-1.5">
        <label className="text-[13px] font-semibold text-ink">Şifre <span className="text-red-700">*</span></label>
        <input type="password" name="password" required value={pw} onChange={(e) => setPw(e.target.value)} placeholder="Min. 8 karakter"
               className="w-full px-3.5 py-3 bg-white border border-rule-strong rounded-[10px] text-[14px] focus:outline-none focus:border-brand-500 focus:ring-[3px] focus:ring-brand-500/15 transition-all" />
        <div className="flex gap-1 pt-1">
          <div className={`flex-1 h-1 rounded-full ${pw.length >= 1 ? 'bg-red-500' : 'bg-slate-200'}`}></div>
          <div className={`flex-1 h-1 rounded-full ${pw.length >= 6 ? 'bg-accent-400' : 'bg-slate-200'}`}></div>
          <div className={`flex-1 h-1 rounded-full ${strong ? 'bg-green-600' : 'bg-slate-200'}`}></div>
        </div>
        {pw.length > 0 && (
          <div className="text-[11px] text-fg-3">
            {strong ? <span className="text-green-700 font-semibold">✓ Güçlü şifre</span> : `${8 - pw.length} karakter daha gerekli`}
          </div>
        )}
      </div>

      <label className="flex items-start gap-2.5 pt-1 cursor-pointer">
        <input type="checkbox" required checked={kvkk} onChange={() => setKvkk(!kvkk)} className="sr-only" />
        <span className={`w-[18px] h-[18px] rounded-[5px] border-[1.5px] flex-shrink-0 mt-0.5 grid place-items-center transition-all ${kvkk ? 'bg-brand-500 border-brand-500' : 'bg-white border-rule-strong'}`}>
          {kvkk && <Icon name="check" size={11} strokeWidth={3} className="text-white" />}
        </span>
        <span className="text-[12px] text-fg-2 leading-[1.5]">
          <a href="/brodemy-kvkk" target="_blank" className="text-brand-600 font-semibold">KVKK Aydınlatma Metni</a>'ni ve <a href="/brodemy-kullanim-kosullari" target="_blank" className="text-brand-600 font-semibold">Kullanım Koşulları</a>'nı okudum, kabul ediyorum.
        </span>
      </label>

      <Button variant="primary" size="lg" className="w-full mt-2" type="submit" disabled={loading || !kvkk || !strong}>
        {loading ? 'Hesap oluşturuluyor…' : 'Hesabımı Oluştur'}
      </Button>
    </form>
  );
}

function RegisterSuccess() {
  return (
    <div className="text-center py-4">
      <div className="w-16 h-16 mx-auto mb-5 rounded-full bg-green-100 grid place-items-center">
        <Icon name="check" size={28} strokeWidth={3} className="text-green-700" />
      </div>
      <h3 className="font-display font-bold text-[26px] tracking-[-0.03em] text-ink mb-2 leading-[1]">Hesabın oluşturuldu!</h3>
      <p className="text-[14px] text-fg-2 leading-[1.55] mb-6">
        E-posta adresine doğrulama linki gönderdik. Şimdi seçtiğin kursa kayıt için <strong className="text-ink">PayTR ile ödeme</strong> ekranına yönlendireceğiz…
      </p>
      <div className="flex items-center justify-center gap-2 text-[13px] text-brand-600 font-semibold mb-6">
        <div className="w-4 h-4 border-2 border-brand-500/30 border-t-brand-500 rounded-full animate-spin"></div>
        Yönlendiriliyor…
      </div>
      <Button variant="outline" size="md">Dashboard'a Git</Button>
    </div>
  );
}

Object.assign(window, { AuthModal });
