// Supabase auth helpers + modal (requires js/supabase-client.js)

function useSupabaseAuth() {
  const [session, setSession] = React.useState(null);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    const sb = window.NotloomSupabase;
    if (!sb.ready) {
      setLoading(false);
      return undefined;
    }

    sb.getSession().then(({ data }) => {
      setSession(data.session ?? null);
      setLoading(false);
    });

    const { data: sub } = sb.onAuthStateChange((_event, nextSession) => {
      setSession(nextSession);
      setLoading(false);
    });

    return () => sub.subscription.unsubscribe();
  }, []);

  return {
    session,
    user: session?.user ?? null,
    loading,
    ready: window.NotloomSupabase?.ready ?? false,
    signInWithGoogle: () => window.NotloomSupabase.signInWithGoogle(),
    signInWithEmail: (email) => window.NotloomSupabase.signInWithEmail(email),
    signOut: () => window.NotloomSupabase.signOut()
  };
}

const AuthModal = ({ open, onClose, auth }) => {
  const [email, setEmail] = React.useState('');
  const [status, setStatus] = React.useState('');
  const [busy, setBusy] = React.useState(false);

  if (!open) return null;

  const run = async (fn) => {
    setBusy(true);
    setStatus('');
    const { error } = await fn();
    setBusy(false);
    if (error) {
      setStatus(error.message);
      return;
    }
    setStatus('Check your email for the sign-in link, or finish in the popup.');
  };

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 10000,
        background: 'rgba(28,28,28,.35)', backdropFilter: 'blur(6px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24
      }}>
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: '100%', maxWidth: 420, background: '#FFFFFF',
          border: '1px solid #E0DAE8', borderRadius: 18, padding: '28px 28px 24px',
          boxShadow: '0 24px 60px rgba(60,30,80,.18)'
        }}>
        <h2 style={{ margin: 0, fontSize: 22, fontWeight: 600, color: '#1c1c1c' }}>Sign in to Notloom</h2>
        <p style={{ margin: '8px 0 20px', fontSize: 14, lineHeight: 1.5, color: '#6b6377' }}>
          Use Google or a magic link sent to your email.
        </p>

        {!auth.ready && (
          <p style={{ margin: '0 0 16px', fontSize: 13, color: '#C4407A', lineHeight: 1.45 }}>
            Add your Supabase anon key in <code>config.js</code> (see <code>config.example.js</code>).
          </p>
        )}

        <button
          disabled={busy || !auth.ready}
          onClick={() => run(auth.signInWithGoogle)}
          style={{
            width: '100%', padding: '12px 16px', borderRadius: 10, border: '1px solid #E0DAE8',
            background: '#FFFFFF', cursor: busy ? 'wait' : 'pointer',
            fontFamily: 'inherit', fontSize: 14, fontWeight: 600, color: '#1c1c1c', marginBottom: 10
          }}>
          Continue with Google
        </button>

        <div style={{ display: 'flex', gap: 8, marginBottom: 10 }}>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="you@company.com"
            style={{
              flex: 1, padding: '11px 12px', borderRadius: 10, border: '1px solid #E0DAE8',
              fontFamily: 'inherit', fontSize: 14, outline: 'none'
            }}
          />
          <button
            disabled={busy || !auth.ready || !email.includes('@')}
            onClick={() => run(() => auth.signInWithEmail(email.trim()))}
            style={{
              padding: '11px 14px', borderRadius: 10, border: 'none', cursor: busy ? 'wait' : 'pointer',
              fontFamily: 'inherit', fontSize: 14, fontWeight: 600, color: '#1c1c1c',
              background: 'linear-gradient(120deg,#C8B6FF 0%,#F5B8D0 50%,#C8B6FF 100%)'
            }}>
            Email link
          </button>
        </div>

        {status && (
          <p style={{ margin: 0, fontSize: 13, color: '#4a4356', lineHeight: 1.45 }}>{status}</p>
        )}

        <button
          onClick={onClose}
          style={{
            marginTop: 16, background: 'transparent', border: 'none', cursor: 'pointer',
            fontFamily: 'inherit', fontSize: 13, color: '#9089A0'
          }}>
          Close
        </button>
      </div>
    </div>
  );
};
