// Login form — mounted inside login.html

const LoginForm = () => {
  const [email,    setEmail]    = React.useState('');
  const [password, setPassword] = React.useState('');
  const [error,    setError]    = React.useState('');
  const [loading,  setLoading]  = React.useState(false);
  const [done,     setDone]     = React.useState(false);

  // Redirect already-authenticated users immediately
  React.useEffect(() => {
    db.auth.getSession().then(({ data: { session } }) => {
      if (session) goToDashboard(session);
    });
  }, []);

  const goToDashboard = (session) => {
    const dest = (typeof BLAN_ADMIN_URL !== 'undefined' && BLAN_ADMIN_URL)
      ? BLAN_ADMIN_URL.replace(/\/$/, '')
      : null;

    if (!dest) { setDone(true); return; }

    // Pass the auth tokens in the URL hash so the admin domain
    // can restore the session without requiring a second login.
    if (session?.access_token) {
      window.location.href =
        `${dest}#access_token=${session.access_token}` +
        `&refresh_token=${session.refresh_token}` +
        `&expires_in=${session.expires_in || 3600}` +
        `&token_type=bearer`;
    } else {
      window.location.href = dest;
    }
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!email.trim() || !password) return;

    setLoading(true);
    setError('');

    const { data, error } = await db.auth.signInWithPassword({
      email:    email.trim(),
      password,
    });

    if (error) {
      setError(
        error.message === 'Invalid login credentials'
          ? 'Incorrect email or password.'
          : error.message
      );
      setLoading(false);
      return;
    }

    goToDashboard(data.session);
  };

  if (done) {
    return (
      <div className="login-success-state">
        <div className="login-success-icon" aria-hidden="true">
          <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="20,6 9,17 4,12"/>
          </svg>
        </div>
        <p className="login-success-msg">You're signed in.</p>
        <p className="login-success-sub">
          Set <code>BLAN_ADMIN_URL</code> in <code>apps/web/config.js</code> to redirect automatically.
        </p>
      </div>
    );
  }

  return (
    <form className="login-form" onSubmit={submit} noValidate>
      {error && (
        <div className="login-error-msg" role="alert">
          <svg viewBox="0 0 16 16" width="14" height="14" fill="none" style={{ flexShrink: 0 }}>
            <circle cx="8" cy="8" r="7" stroke="currentColor" strokeWidth="1.3"/>
            <path d="M8 5v3.5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
            <circle cx="8" cy="11" r=".6" fill="currentColor"/>
          </svg>
          {error}
        </div>
      )}

      <div className="ag-field">
        <label htmlFor="lf-email">Email</label>
        <input
          id="lf-email"
          type="email"
          value={email}
          onChange={e => { setEmail(e.target.value); setError(''); }}
          placeholder="you@example.com"
          required
          autoFocus
          autoComplete="email"
        />
      </div>

      <div className="ag-field">
        <label htmlFor="lf-password">Password</label>
        <input
          id="lf-password"
          type="password"
          value={password}
          onChange={e => { setPassword(e.target.value); setError(''); }}
          placeholder="••••••••"
          required
          autoComplete="current-password"
        />
      </div>

      <button
        type="submit"
        className="ag-btn ag-btn--accent login-submit-btn"
        disabled={loading}
      >
        {loading ? 'Signing in…' : 'Sign in'}
      </button>
    </form>
  );
};

const loginRoot = document.getElementById('login-root');
if (loginRoot) {
  ReactDOM.createRoot(loginRoot).render(<LoginForm />);
}
