// Authentication — real backend auth via Supabase.
//
// Unlike the earlier demo gate, credentials are NEVER checked in the browser.
// signInWithPassword() sends them to Supabase Auth, which validates them
// server-side and returns a signed session (JWT) that the SDK persists. You
// manage exactly who can sign in from the Supabase dashboard — see
// SUPABASE-SETUP.md.
//
// Config lives in site/supabase-config.js (window.SUPABASE_CONFIG). The anon
// key there is public by design; security comes from Auth + Row Level Security.

// Single shared client. Null until you fill in site/supabase-config.js.
const _sb = (() => {
  try {
    const cfg = window.SUPABASE_CONFIG || {};
    if (!window.supabase || !cfg.url || !cfg.anonKey || cfg.url.indexOf('YOUR-PROJECT') !== -1) {
      return null;
    }
    return window.supabase.createClient(cfg.url, cfg.anonKey, {
      auth: { persistSession: true, autoRefreshToken: true, detectSessionInUrl: true },
    });
  } catch (e) {
    return null;
  }
})();

const useAuth = () => {
  const [session, setSession] = React.useState(null);
  const [ready, setReady] = React.useState(false);

  React.useEffect(() => {
    if (!_sb) { setReady(true); return; }
    let active = true;
    _sb.auth.getSession().then(({ data }) => {
      if (!active) return;
      setSession(data.session || null);
      setReady(true);
    });
    const { data: sub } = _sb.auth.onAuthStateChange((_event, s) => {
      setSession(s || null);
    });
    return () => { active = false; sub.subscription.unsubscribe(); };
  }, []);

  const signIn = React.useCallback(async (email, password) => {
    if (!_sb) return { error: 'Backend not configured yet — see SUPABASE-SETUP.md.' };
    const { error } = await _sb.auth.signInWithPassword({ email, password });
    return { error: error ? error.message : null };
  }, []);

  const signOut = React.useCallback(async () => {
    if (_sb) { try { await _sb.auth.signOut(); } catch (e) {} }
  }, []);

  return {
    session,
    user: session ? session.user : null,
    ready,
    signIn,
    signOut,
    configured: !!_sb,
  };
};

const LoginGate = ({ signIn, configured }) => {
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [error, setError] = React.useState('');
  const [shake, setShake] = React.useState(false);
  const [busy, setBusy] = React.useState(false);

  const fail = (msg) => { setError(msg); setShake(true); setTimeout(() => setShake(false), 420); };

  const submit = async (e) => {
    e.preventDefault();
    if (busy) return;
    const cleanEmail = email.trim().toLowerCase();
    const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(cleanEmail);
    if (!emailOk) { fail('Enter a valid email address.'); return; }
    if (!password) { fail('Enter your password.'); return; }

    setBusy(true);
    setError('');
    const { error } = await signIn(cleanEmail, password);
    setBusy(false);
    if (error) {
      // Supabase returns "Invalid login credentials" for a bad email/password.
      fail(/invalid login/i.test(error) ? "Those credentials weren't recognized." : error);
    }
    // On success, the auth state change re-renders the app into the site.
  };

  const inputStyle = {
    width: '100%',
    padding: '15px 16px',
    border: `1px solid ${tokens.inkLine}`,
    background: tokens.paper,
    fontSize: '15px',
    fontFamily: fontDisplay,
    letterSpacing: '-0.005em',
    color: tokens.ink,
  };

  const labelStyle = {
    fontFamily: fontMono, fontSize: '10px', letterSpacing: '0.18em',
    color: tokens.inkMute, textTransform: 'uppercase', marginBottom: '10px', display: 'block',
  };

  return (
    <div style={{
      minHeight: '100vh', background: tokens.bg, color: tokens.ink,
      display: 'grid', gridTemplateColumns: '1.1fr 1fr',
      fontFamily: fontDisplay,
    }}>
      {/* Left — brand panel */}
      <div style={{
        background: tokens.ink, color: tokens.bg,
        padding: 'clamp(40px, 6vw, 80px)',
        display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
        position: 'relative', overflow: 'hidden',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px', position: 'relative', zIndex: 2 }}>
          <span style={{ width: '22px', height: '22px', border: '1px solid rgba(244,241,234,0.5)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontFamily: fontMono, fontSize: '10px' }}>DU</span>
          <span style={{ fontWeight: 500, letterSpacing: '-0.02em', fontSize: '15px' }}>Daniel Urdaneta</span>
        </div>

        <div style={{ position: 'relative', zIndex: 2 }}>
          <div style={{ fontFamily: fontMono, fontSize: '11px', letterSpacing: '0.18em', color: 'rgba(244,241,234,0.55)', marginBottom: '24px', textTransform: 'uppercase' }}>
            Private · By invitation
          </div>
          <h1 style={{ fontSize: 'clamp(40px, 5vw, 64px)', lineHeight: 0.95, letterSpacing: '-0.045em', fontWeight: 400, margin: 0, marginBottom: '24px' }}>
            Private <span style={{ fontStyle: 'italic', fontWeight: 300, color: 'rgba(244,241,234,0.55)' }}>workspace.</span>
          </h1>
          <p style={{ fontSize: '16px', lineHeight: 1.55, color: 'rgba(244,241,234,0.7)', maxWidth: '420px', margin: 0 }}>
            Sign in with the email and password you were given.
          </p>
        </div>

        <div style={{ fontFamily: fontMono, fontSize: '10px', letterSpacing: '0.08em', color: 'rgba(244,241,234,0.45)', position: 'relative', zIndex: 2 }}>
          PRIVATE EQUITY · PUBLIC MARKETS · VENTURE
        </div>

        {/* subtle grid backdrop */}
        <div style={{
          position: 'absolute', inset: 0, pointerEvents: 'none', opacity: 0.5,
          backgroundImage: 'linear-gradient(rgba(244,241,234,0.04) 1px, transparent 1px), linear-gradient(90deg, rgba(244,241,234,0.04) 1px, transparent 1px)',
          backgroundSize: '64px 64px',
          maskImage: 'radial-gradient(ellipse at 30% 60%, black 20%, transparent 70%)',
        }}></div>
      </div>

      {/* Right — form */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 'clamp(32px, 5vw, 72px)' }}>
        <form onSubmit={submit} style={{
          width: '100%', maxWidth: '380px',
          animation: shake ? 'gate-shake 0.4s ease' : 'none',
        }}>
          <div style={{ fontFamily: fontMono, fontSize: '11px', letterSpacing: '0.18em', color: tokens.inkMute, marginBottom: '12px', textTransform: 'uppercase' }}>
            Sign in
          </div>
          <h2 style={{ fontSize: '34px', letterSpacing: '-0.035em', fontWeight: 400, margin: 0, marginBottom: '40px', lineHeight: 1.05 }}>
            Enter to continue.
          </h2>

          {!configured && (
            <div style={{ marginBottom: '28px', padding: '14px 16px', border: `1px solid ${tokens.inkLine}`, background: tokens.paper, fontFamily: fontMono, fontSize: '10px', lineHeight: 1.6, letterSpacing: '0.04em', color: tokens.inkMute }}>
              ⚠ BACKEND NOT CONFIGURED — add your Supabase URL and anon key to
              <span style={{ color: tokens.ink }}> site/supabase-config.js</span>. See SUPABASE-SETUP.md.
            </div>
          )}

          <div style={{ marginBottom: '24px' }}>
            <label style={labelStyle}>Email</label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="you@firm.com"
              autoComplete="email"
              style={inputStyle}
            />
          </div>

          <div style={{ marginBottom: '12px' }}>
            <label style={labelStyle}>Password</label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="••••••••"
              autoComplete="current-password"
              style={inputStyle}
            />
          </div>

          <div style={{ minHeight: '20px', marginBottom: '20px' }}>
            {error && (
              <div style={{ fontFamily: fontMono, fontSize: '11px', letterSpacing: '0.04em', color: tokens.red }}>
                ● {error}
              </div>
            )}
          </div>

          <button type="submit" disabled={busy} style={{
            width: '100%', padding: '15px 22px', background: tokens.ink, color: tokens.bg,
            border: 'none', cursor: busy ? 'default' : 'pointer', fontSize: '14px', letterSpacing: '0.01em',
            fontFamily: fontDisplay, fontWeight: 500, opacity: busy ? 0.6 : 1,
          }}>
            {busy ? 'Signing in…' : 'Enter →'}
          </button>

          <div style={{ marginTop: '28px', paddingTop: '20px', borderTop: `1px solid ${tokens.inkLine}`, display: 'flex', justifyContent: 'space-between', fontFamily: fontMono, fontSize: '10px', letterSpacing: '0.06em', color: tokens.inkMute }}>
            <span>REQUEST ACCESS</span>
            <a href="mailto:daniel@urdaneta.io" style={{ color: tokens.ink, borderBottom: `1px solid ${tokens.inkLine}`, paddingBottom: '2px' }}>daniel@urdaneta.io</a>
          </div>
        </form>
      </div>
    </div>
  );
};

window.useAuth = useAuth;
window.LoginGate = LoginGate;
// Expose the shared client so other modules (e.g. page-forme) can call Edge Functions.
window._supabaseClient = _sb;
