// Auth gate — sign in / sign up before rendering the app

function useSession() {
  const [session, setSession] = React.useState(undefined); // undefined = loading
  React.useEffect(() => {
    sb.auth.getSession().then(({ data }) => setSession(data.session || null));
    const { data: sub } = sb.auth.onAuthStateChange((_ev, s) => setSession(s));
    return () => sub.subscription.unsubscribe();
  }, []);
  return [session, setSession];
}

function AuthModal({ onClose }) {
  const [mode, setMode] = React.useState('signin'); // signin | signup
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [err, setErr] = React.useState(null);
  const [info, setInfo] = React.useState(null);
  const [busy, setBusy] = React.useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr(null); setInfo(null); setBusy(true);
    try {
      if (mode === 'signup') {
        const { data, error } = await sb.auth.signUp({ email, password });
        if (error) throw error;
        if (!data.session) setInfo('Check your email to confirm your account.');
        else onClose?.();
      } else {
        const { error } = await sb.auth.signInWithPassword({ email, password });
        if (error) throw error;
        onClose?.();
      }
    } catch (e2) {
      setErr(e2.message || 'Something went wrong');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-5" style={{ background: 'rgba(7,7,12,0.72)', backdropFilter: 'blur(6px)' }} onClick={onClose}>
      <div className="relative w-full max-w-[420px] glass rounded-2xl p-7" onClick={(e) => e.stopPropagation()}>
        <button onClick={onClose} className="absolute top-3 right-3 text-white/40 hover:text-white" aria-label="Close"><Icon name="x" size={14} /></button>
        <div className="flex items-center justify-center mb-6">
          <LogoMark size={28} />
        </div>
        <div className="text-center mb-5">
          <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-2">
            {mode === 'signup' ? 'Create account' : 'Welcome back'}
          </div>
          <h1 className="text-2xl font-semibold tracking-tight">
            {mode === 'signup' ? 'Join DavesShop' : 'Sign in to continue'}
          </h1>
          <p className="text-sm text-white/55 mt-1.5">
            {mode === 'signup'
              ? 'Create a free account to start ordering.'
              : 'Enter your credentials to access the shop.'}
          </p>
        </div>

        <form onSubmit={submit} className="space-y-3">
          <div>
            <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-1.5">Email</div>
            <div className="hairline rounded-lg px-3 py-2.5 flex items-center gap-2 accent-ring">
              <Icon name="user" size={14} />
              <input
                type="email"
                required
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="you@example.com"
                className="bg-transparent outline-none text-sm flex-1 min-w-0"
              />
            </div>
          </div>
          <div>
            <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-1.5">Password</div>
            <div className="hairline rounded-lg px-3 py-2.5 flex items-center gap-2 accent-ring">
              <Icon name="lock" size={14} />
              <input
                type="password"
                required
                minLength={6}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="••••••••"
                className="bg-transparent outline-none text-sm flex-1 min-w-0"
              />
            </div>
          </div>

          {err && (
            <div className="hairline rounded-lg p-3 text-xs flex gap-2" style={{ background: 'rgba(255,109,138,0.05)', borderColor: 'rgba(255,109,138,0.25)', color: 'var(--bad)' }}>
              <Icon name="info" size={14} /><span>{err}</span>
            </div>
          )}
          {info && (
            <div className="hairline rounded-lg p-3 text-xs flex gap-2" style={{ background: 'rgba(125,243,161,0.05)', borderColor: 'rgba(125,243,161,0.25)', color: 'var(--ok)' }}>
              <Icon name="check" size={14} /><span>{info}</span>
            </div>
          )}

          <button type="submit" disabled={busy} className="btn-primary w-full py-3 inline-flex items-center justify-center gap-2 disabled:opacity-60">
            {busy ? 'Working…' : (mode === 'signup' ? 'Create account' : 'Sign in')}
            {!busy && <Icon name="arrow" size={14} />}
          </button>
        </form>

        <div className="mt-5 text-center text-xs text-white/55">
          {mode === 'signup' ? 'Already have an account?' : "Don't have an account?"}{' '}
          <button
            onClick={() => { setMode(mode === 'signup' ? 'signin' : 'signup'); setErr(null); setInfo(null); }}
            className="font-medium" style={{ color: 'var(--accent)' }}
          >
            {mode === 'signup' ? 'Sign in' : 'Sign up'}
          </button>
        </div>

        <div className="mt-6 pt-5 border-t text-[11px] mono uppercase tracking-widest text-white/40 flex items-center justify-center gap-2" style={{ borderColor: 'var(--line)' }}>
          <Dot size={6} /> secured by supabase
        </div>
      </div>
    </div>
  );
}

async function signOut() {
  await sb.auth.signOut();
}

Object.assign(window, { useSession, AuthModal, signOut });
