/* ============================================================
   VENTUM STUDIO — auth gate.

   Wraps the main app. If no Supabase session exists, renders a
   sign-in screen (email + password). Once signed in, renders children.

   Closed-signup model:
     · Admin creates users in Supabase Dashboard → Authentication → Users
       and sets their initial password
     · Users sign in here with that email + password
     · Forgot-password sends a reset email via Supabase Auth

   detectSessionInUrl is still on in the client, so password-reset
   tokens in the URL hash are auto-detected and the user lands signed in.
   ============================================================ */
const { useState: aUseState, useEffect: aUseEffect } = React;

function VentumAuthGate({ children }) {
  const [session, setSession] = aUseState(null);
  const [checking, setChecking] = aUseState(true);
  const [email, setEmail] = aUseState(() => {
    try { return localStorage.getItem('ventum-last-email') || ''; } catch (_) { return ''; }
  });
  const [password, setPassword] = aUseState('');
  const [submitting, setSubmitting] = aUseState(false);
  const [error, setError] = aUseState(null);
  const [resetSent, setResetSent] = aUseState(false);
  const [resetting, setResetting] = aUseState(false);
  // True when the user clicked a password-reset email link and is now
  // mid-flow setting a new password. The PASSWORD_RECOVERY event from
  // Supabase fires synchronously when the SDK parses the URL hash on
  // init — supabase-client.js attaches a listener BEFORE React mounts
  // and sets window.__ventumRecoveryMode. We read that flag here and
  // also listen for the 'ventum-recovery' event in case it arrives
  // after mount (page navigation, multi-tab session change, etc.).
  const [recoveryMode, setRecoveryMode] = aUseState(() => !!window.__ventumRecoveryMode);
  const [newPassword, setNewPassword] = aUseState('');
  const [newPasswordConfirm, setNewPasswordConfirm] = aUseState('');
  const [updatingPassword, setUpdatingPassword] = aUseState(false);

  aUseEffect(() => {
    const sb = window.ventumSupabase;
    if (!sb) {
      setError('Supabase client failed to load. Check the network tab for blocked CDN scripts.');
      setChecking(false);
      return;
    }
    sb.auth.getSession().then(({ data }) => {
      setSession(data.session);
      setChecking(false);
    });
    const { data: sub } = sb.auth.onAuthStateChange((event, sess) => {
      setSession(sess);
      // Supabase fires PASSWORD_RECOVERY when the user lands here via a
      // password-reset email link. supabase-client.js catches the early
      // synchronous fire; this is the backup for any later occurrences.
      if (event === 'PASSWORD_RECOVERY') {
        setRecoveryMode(true);
      }
    });
    const onRecovery = () => setRecoveryMode(true);
    window.addEventListener('ventum-recovery', onRecovery);
    return () => {
      sub.subscription.unsubscribe();
      window.removeEventListener('ventum-recovery', onRecovery);
    };
  }, []);

  const submitNewPassword = async (e) => {
    e.preventDefault();
    setError(null);
    if (newPassword.length < 6) {
      setError('Password must be at least 6 characters.');
      return;
    }
    if (newPassword !== newPasswordConfirm) {
      setError('The two passwords don\'t match.');
      return;
    }
    setUpdatingPassword(true);
    try {
      const { error: e1 } = await window.ventumSupabase.auth.updateUser({ password: newPassword });
      if (e1) throw e1;
      try { window.__ventumRecoveryMode = false; } catch (_) {}
      setRecoveryMode(false);
      setNewPassword('');
      setNewPasswordConfirm('');
      // Session is now fully authenticated with the new password — fall
      // through to the app render. Show a quick toast on the way in.
      try { window.__toast && window.__toast('Password updated · signed in'); } catch (_) {}
    } catch (err) {
      console.error('updateUser failed', err);
      setError(err?.message || 'Failed to update password');
    } finally {
      setUpdatingPassword(false);
    }
  };

  const signIn = async (e) => {
    e.preventDefault();
    setError(null);
    if (!email.trim() || !password) return;
    setSubmitting(true);
    try {
      try { localStorage.setItem('ventum-last-email', email.trim()); } catch (_) {}
      const { error: e1 } = await window.ventumSupabase.auth.signInWithPassword({
        email: email.trim(),
        password
      });
      if (e1) throw e1;
      // onAuthStateChange will pick up the new session and re-render.
    } catch (err) {
      console.error('signIn failed', err);
      setError(translateAuthError(err.message));
    } finally {
      setSubmitting(false);
    }
  };

  const sendReset = async () => {
    if (!email.trim()) {
      setError('Enter your email above first so we know where to send the reset link.');
      return;
    }
    setError(null);
    setResetting(true);
    try {
      const redirectTo = window.location.origin + window.location.pathname;
      const { error: e1 } = await window.ventumSupabase.auth.resetPasswordForEmail(email.trim(), {
        redirectTo
      });
      if (e1) throw e1;
      setResetSent(true);
    } catch (err) {
      console.error('resetPasswordForEmail failed', err);
      setError(err.message || 'Failed to send reset email');
    } finally {
      setResetting(false);
    }
  };

  if (checking) {
    return (
      <div className="ventum-auth-mask">
        <div className="ventum-auth-card">
          <div className="mono ventum-auth-eyebrow">VENTUM STUDIO</div>
          <p className="ventum-auth-checking">Checking session…</p>
        </div>
      </div>
    );
  }

  // Password-recovery form: user clicked the reset email link and is now
  // in a temporary session. They must set a new password before the gate
  // lets them through to the app.
  if (recoveryMode) {
    return (
      <div className="ventum-auth-mask">
        <div className="ventum-auth-card">
          <img src="assets/Ventum-wordmark-black.png" alt="Ventum" className="ventum-auth-mark" />
          <div className="mono ventum-auth-eyebrow">STUDIO</div>
          <h1 className="ventum-auth-title">Set new password</h1>
          <p className="ventum-auth-lede">
            You signed in via a password-reset link. Pick a new password to finish.
          </p>
          <form onSubmit={submitNewPassword}>
            <label className="ventum-auth-label">
              <span>New password</span>
              <input
                type="password"
                placeholder="••••••••"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                required
                autoFocus
                autoComplete="new-password"
                minLength={6}
              />
            </label>
            <label className="ventum-auth-label">
              <span>Confirm new password</span>
              <input
                type="password"
                placeholder="••••••••"
                value={newPasswordConfirm}
                onChange={(e) => setNewPasswordConfirm(e.target.value)}
                required
                autoComplete="new-password"
                minLength={6}
              />
            </label>
            {error && <div className="ventum-auth-error">{error}</div>}
            <button type="submit" disabled={updatingPassword || !newPassword || !newPasswordConfirm} className="ventum-auth-primary">
              {updatingPassword ? 'Updating…' : <>Update password <span style={{ marginLeft: 4 }}>→</span></>}
            </button>
          </form>
          <div className="ventum-auth-footnote mono">
            6 characters minimum. After saving, you'll land in the studio signed in.
          </div>
        </div>
      </div>
    );
  }

  if (!session) {
    return (
      <div className="ventum-auth-mask">
        <div className="ventum-auth-card">
          <img src="assets/Ventum-wordmark-black.png" alt="Ventum" className="ventum-auth-mark" />
          <div className="mono ventum-auth-eyebrow">STUDIO</div>
          <h1 className="ventum-auth-title">Sign in</h1>

          {resetSent ? (
            <div className="ventum-auth-sent">
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', color: 'var(--teal)', textTransform: 'uppercase', marginBottom: 8 }}>Password reset sent</div>
              <p style={{ fontSize: 14, color: 'var(--ink-80)', lineHeight: 1.5, marginBottom: 14 }}>
                Check <strong>{email}</strong> for a reset link. Click it from this device to set a new password.
              </p>
              <button
                type="button"
                onClick={() => { setResetSent(false); setError(null); }}
                className="ventum-auth-secondary"
              >Back to sign in</button>
            </div>
          ) : (
            <form onSubmit={signIn}>
              <p className="ventum-auth-lede">
                Enter the email and password your admin shared with you.
              </p>
              <label className="ventum-auth-label">
                <span>Email</span>
                <input
                  type="email"
                  placeholder="you@company.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                  autoFocus
                  autoComplete="username"
                />
              </label>
              <label className="ventum-auth-label">
                <span>Password</span>
                <input
                  type="password"
                  placeholder="••••••••"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                  autoComplete="current-password"
                />
              </label>
              {error && <div className="ventum-auth-error">{error}</div>}
              <button type="submit" disabled={submitting || !email.trim() || !password} className="ventum-auth-primary">
                {submitting ? 'Signing in…' : <>Sign in <span style={{ marginLeft: 4 }}>→</span></>}
              </button>
              <button
                type="button"
                onClick={sendReset}
                disabled={resetting}
                className="ventum-auth-link"
              >{resetting ? 'Sending reset…' : 'Forgot password?'}</button>
            </form>
          )}

          <div className="ventum-auth-footnote mono">
            Restricted access. Accounts are created by your admin — sign-ups are disabled.
          </div>
        </div>
      </div>
    );
  }

  return children;
}

// Translate raw Supabase error messages into friendlier UI copy.
function translateAuthError(msg) {
  if (!msg) return 'Sign-in failed. Please try again.';
  const lower = msg.toLowerCase();
  if (lower.includes('invalid login credentials')) return 'Incorrect email or password.';
  if (lower.includes('email not confirmed')) return 'This email is not confirmed yet. Check your inbox for the confirmation link your admin sent.';
  if (lower.includes('rate limit')) return 'Too many attempts. Wait a minute and try again.';
  return msg;
}

window.VentumAuthGate = VentumAuthGate;
