// login.jsx — login icon button + provider popup
// Order: Google, Apple, GitHub, Magic link, Email
// Backend wiring (real OAuth) lands later — buttons currently route to
// /auth/<provider> on click and the inline forms POST to /api/auth/email,
// /api/auth/magic. UI-only for now if endpoints 404.

function LoginIcon({ accent, onOpen }) {
  return (
    <button
      onClick={onOpen}
      aria-label="Giriş yap"
      style={{
        width: 44, height: 44, borderRadius: 10,
        border: '2px solid var(--ink)', background: 'var(--paper)',
        color: 'var(--ink)', cursor: 'pointer',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: '3px 3px 0 var(--ink)',
        transition: 'transform .12s, box-shadow .12s, background .15s',
      }}
      onMouseEnter={(e) => { e.currentTarget.style.background = accent; }}
      onMouseLeave={(e) => { e.currentTarget.style.background = 'var(--paper)'; }}
      onMouseDown={(e) => { e.currentTarget.style.transform = 'translate(3px, 3px)'; e.currentTarget.style.boxShadow = '0 0 0 var(--ink)'; }}
      onMouseUp={(e) => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = '3px 3px 0 var(--ink)'; }}>
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/>
        <polyline points="10 17 15 12 10 7"/>
        <line x1="15" y1="12" x2="3" y2="12"/>
      </svg>
    </button>
  );
}

// Provider SVG icons — monochrome by default, brand-colored on hover via parent.
const Icons = {
  google: () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
      <path fill="#4285F4" d="M22.5 12.27c0-.79-.07-1.54-.2-2.27H12v4.51h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.22-4.74 3.22-8.32z"/>
      <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.99.66-2.25 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84A11 11 0 0 0 12 23z"/>
      <path fill="#FBBC04" d="M5.84 14.1A6.6 6.6 0 0 1 5.5 12c0-.73.13-1.44.34-2.1V7.06H2.18A11 11 0 0 0 1 12c0 1.77.43 3.45 1.18 4.94l3.66-2.84z"/>
      <path fill="#EA4335" d="M12 5.38c1.62 0 3.07.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1A11 11 0 0 0 2.18 7.06l3.66 2.84C6.71 7.31 9.14 5.38 12 5.38z"/>
    </svg>
  ),
  apple: () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
      <path d="M17.05 12.04c-.03-2.85 2.32-4.22 2.43-4.29-1.32-1.93-3.39-2.2-4.12-2.22-1.76-.18-3.43 1.03-4.32 1.03-.9 0-2.27-1.01-3.74-.98-1.92.03-3.7 1.12-4.69 2.83-2 3.47-.51 8.6 1.44 11.42.95 1.38 2.08 2.92 3.55 2.86 1.42-.06 1.96-.92 3.68-.92s2.2.92 3.71.89c1.53-.03 2.5-1.4 3.43-2.78 1.08-1.6 1.53-3.16 1.55-3.24-.03-.01-2.97-1.14-3-4.6zm-2.87-8.45c.78-.95 1.31-2.27 1.16-3.59-1.12.05-2.49.75-3.3 1.7-.72.83-1.36 2.19-1.19 3.49 1.25.1 2.54-.64 3.33-1.6z"/>
    </svg>
  ),
  github: () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
      <path d="M12 0C5.37 0 0 5.37 0 12c0 5.3 3.44 9.8 8.21 11.39.6.11.82-.26.82-.58v-2.04c-3.34.73-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.08-.73.08-.73 1.2.09 1.84 1.24 1.84 1.24 1.07 1.83 2.8 1.3 3.48.99.11-.77.42-1.3.76-1.6-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.39 1.24-3.23-.13-.31-.54-1.53.12-3.19 0 0 1-.32 3.3 1.23.96-.27 1.98-.4 3-.4s2.04.13 3 .4c2.3-1.55 3.3-1.23 3.3-1.23.66 1.66.25 2.88.12 3.19.77.84 1.24 1.92 1.24 3.23 0 4.61-2.8 5.62-5.48 5.92.43.37.81 1.1.81 2.22v3.29c0 .32.22.7.83.58A12 12 0 0 0 24 12c0-6.63-5.37-12-12-12z"/>
    </svg>
  ),
  magic: () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polygon fill="currentColor" points="13 2 4 14 12 14 11 22 20 10 12 10 13 2"/>
    </svg>
  ),
  email: () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M4 4h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"/>
      <polyline points="22 6 12 13 2 6"/>
    </svg>
  ),
};

function ProviderButton({ icon, label, sub, onClick, accent, primary = false }) {
  return (
    <button
      onClick={onClick}
      style={{
        display: 'flex', alignItems: 'center', gap: 14,
        width: '100%', padding: '14px 16px',
        border: '2px solid var(--ink)', borderRadius: 10,
        background: primary ? accent : 'var(--paper)',
        color: 'var(--ink)', cursor: 'pointer', textAlign: 'left',
        fontFamily: 'var(--sans)', fontSize: 14, fontWeight: 500,
        boxShadow: '3px 3px 0 var(--ink)',
        transition: 'transform .12s, box-shadow .12s, background .15s',
        minHeight: 56,
      }}
      onMouseDown={(e) => { e.currentTarget.style.transform = 'translate(3px,3px)'; e.currentTarget.style.boxShadow = '0 0 0 var(--ink)'; }}
      onMouseUp={(e) => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = '3px 3px 0 var(--ink)'; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = '3px 3px 0 var(--ink)'; }}>
      <span style={{ display: 'inline-flex', width: 36, height: 36, borderRadius: 8, alignItems: 'center', justifyContent: 'center', background: primary ? 'var(--ink)' : 'var(--paper-2)', color: primary ? accent : 'var(--ink)', flexShrink: 0 }}>
        {icon}
      </span>
      <span style={{ flex: 1 }}>
        <span style={{ display: 'block' }}>{label}</span>
        {sub && <span style={{ display: 'block', fontSize: 11, color: 'var(--ink-2)', marginTop: 2, fontFamily: 'var(--mono)' }}>{sub}</span>}
      </span>
      <span style={{ opacity: .4 }}>→</span>
    </button>
  );
}

function LoginModal({ accent, onClose }) {
  const { t } = useT();
  const [mode, setMode] = React.useState('list'); // 'list' | 'email' | 'magic'
  const [email, setEmail] = React.useState('');
  const [submitted, setSubmitted] = React.useState(false);

  React.useEffect(() => {
    function onKey(e) { if (e.key === 'Escape') onClose(); }
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [onClose]);

  function open(provider) {
    // Real wiring later. For now route to /auth/<provider> which returns 302
    // when implemented, or a placeholder page in the meantime.
    if (provider === 'google' || provider === 'apple' || provider === 'github') {
      window.location.href = '/auth/' + provider + '?ref=' + encodeURIComponent(location.href);
      return;
    }
    setMode(provider);
  }

  async function submitEmailForm(e) {
    e.preventDefault();
    const endpoint = mode === 'magic' ? '/api/auth/magic' : '/api/auth/email';
    try {
      await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email }) });
    } catch (err) {}
    setSubmitted(true);
  }

  return (
    <div role="dialog" aria-modal="true" aria-labelledby="ruu-login-title"
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 100,
        background: 'rgba(20,22,18,.5)', backdropFilter: 'blur(4px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 16, animation: 'ruu-fade-up .2s ease-out',
      }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: 'var(--paper)', color: 'var(--ink)',
        border: '2px solid var(--ink)', borderRadius: 16,
        boxShadow: '6px 6px 0 var(--ink)',
        width: '100%', maxWidth: 420, padding: '24px 24px 20px',
        fontFamily: 'var(--sans)',
      }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
          <div>
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 4 }}>
              {t('login.kicker')}
            </div>
            <h2 id="ruu-login-title" className="serif" style={{ fontSize: 26, lineHeight: 1.05, letterSpacing: '-0.02em', margin: 0 }}>
              {mode === 'list' && t('login.title')}
              {mode === 'email' && t('login.email.title')}
              {mode === 'magic' && t('login.magic.title')}
            </h2>
          </div>
          <button onClick={onClose} aria-label={t('login.close')} style={{
            width: 36, height: 36, borderRadius: 8, border: '2px solid var(--ink)',
            background: 'var(--paper)', cursor: 'pointer', flexShrink: 0,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
              <line x1="18" y1="6" x2="6" y2="18"/>
              <line x1="6" y1="6" x2="18" y2="18"/>
            </svg>
          </button>
        </div>

        {/* Body */}
        {mode === 'list' && (
          <div style={{ display: 'grid', gap: 10 }}>
            <ProviderButton accent={accent} icon={<Icons.google />} label={t('login.google.label')} sub={t('login.google.sub')} onClick={() => open('google')} primary />
            <ProviderButton accent={accent} icon={<Icons.apple />}  label={t('login.apple.label')}  sub={t('login.apple.sub')}  onClick={() => open('apple')} />
            <ProviderButton accent={accent} icon={<Icons.github />} label={t('login.github.label')} sub={t('login.github.sub')} onClick={() => open('github')} />
            <div style={{ borderTop: '1px dashed var(--rule)', margin: '4px 0' }}/>
            <ProviderButton accent={accent} icon={<Icons.magic />}  label={t('login.magic.label')}  sub={t('login.magic.sub')}  onClick={() => open('magic')} />
            <ProviderButton accent={accent} icon={<Icons.email />}  label={t('login.email.label')}  sub={t('login.email.sub')}  onClick={() => open('email')} />
          </div>
        )}

        {(mode === 'email' || mode === 'magic') && !submitted && (
          <form onSubmit={submitEmailForm} style={{ display: 'grid', gap: 12 }}>
            <p style={{ fontSize: 14, lineHeight: 1.5, color: 'var(--ink-2)', margin: 0 }}>
              {mode === 'magic' ? t('login.magic.body') : t('login.email.body')}
            </p>
            <input
              type="email" required autoFocus value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder={t('login.email.placeholder')}
              style={{
                padding: '14px 14px', border: '2px solid var(--ink)', borderRadius: 10,
                fontFamily: 'var(--mono)', fontSize: 14, background: 'var(--paper)',
                color: 'var(--ink)', outline: 'none',
              }}/>
            <div style={{ display: 'flex', gap: 8 }}>
              <button type="button" onClick={() => setMode('list')} style={{
                padding: '12px 16px', border: '2px solid var(--ink)', borderRadius: 10,
                background: 'var(--paper)', cursor: 'pointer', fontSize: 13,
              }}>← {t('login.back')}</button>
              <button type="submit" style={{
                flex: 1, padding: '12px 16px', border: '2px solid var(--ink)', borderRadius: 10,
                background: accent, cursor: 'pointer', fontSize: 13, fontWeight: 600,
                boxShadow: '3px 3px 0 var(--ink)',
              }}>{mode === 'magic' ? t('login.magic.cta') : t('login.email.cta')} →</button>
            </div>
          </form>
        )}

        {(mode === 'email' || mode === 'magic') && submitted && (
          <div style={{ padding: '12px 0', display: 'grid', gap: 10 }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, fontSize: 14, color: 'var(--ink)' }}>
              <span style={{ width: 24, height: 24, borderRadius: '50%', background: accent, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>✓</span>
              <strong>{t('login.sent.title')}</strong>
            </div>
            <p style={{ fontSize: 13, color: 'var(--ink-2)', margin: 0, lineHeight: 1.5 }}>
              {mode === 'magic' ? t('login.magic.sent') : t('login.email.sent')}
            </p>
            <button onClick={onClose} style={{
              marginTop: 8, padding: '12px 16px', border: '2px solid var(--ink)', borderRadius: 10,
              background: 'var(--ink)', color: accent, cursor: 'pointer', fontSize: 13,
            }}>{t('login.close')}</button>
          </div>
        )}

        {/* Footer */}
        <div style={{ marginTop: 18, paddingTop: 14, borderTop: '1px dashed var(--rule)', fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--mono)', textAlign: 'center' }}>
          {t('login.footer')}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LoginIcon, LoginModal });
