// login.jsx — email/password auth screen + account chip.
const { useState: useStateAuth } = React;

function Login({ onSignedIn }) {
  const [email, setEmail] = useStateAuth('');
  const [pw, setPw] = useStateAuth('');
  const [err, setErr] = useStateAuth('');
  const [busy, setBusy] = useStateAuth(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr(''); setBusy(true);
    try {
      const { data, error } = await window.sb.auth.signInWithPassword({ email: email.trim(), password: pw });
      if (error) throw error;
      onSignedIn(data.session);
    } catch (ex) {
      setErr(ex.message || 'Could not sign in. Check your credentials.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="login-stage">
      <form className="login-card" onSubmit={submit}>
        <div className="login-brand">
          <div className="brand-mark" aria-hidden="true"><span></span><span></span><span></span></div>
          <span className="brand-name">WEBRIS</span>
        </div>
        <h1 className="login-title">Sign in to your dashboard</h1>
        <p className="login-sub">Use your WEBRIS account credentials.</p>

        <label className="login-field">
          <span>Email</span>
          <input type="email" autoComplete="email" required value={email}
            onChange={(e) => setEmail(e.target.value)} placeholder="you@firm.com" />
        </label>
        <label className="login-field">
          <span>Password</span>
          <input type="password" autoComplete="current-password" required value={pw}
            onChange={(e) => setPw(e.target.value)} placeholder="••••••••" />
        </label>

        {err && <div className="login-err">{err}</div>}

        <button type="submit" className="login-btn" disabled={busy}>
          {busy ? 'Signing in…' : 'Sign in'}
        </button>

        <p className="login-foot">Protected by Supabase Auth · row-level security</p>
      </form>
    </div>
  );
}

function AccountChip({ email, onSignOut }) {
  const [open, setOpen] = useStateAuth(false);
  return (
    <div className="acct" onMouseLeave={() => setOpen(false)}>
      <button className="acct-btn" onClick={() => setOpen((o) => !o)} title={email}>
        <span className="acct-avatar">{(email || '?')[0].toUpperCase()}</span>
        <span className="acct-email">{email}</span>
      </button>
      {open && (
        <div className="acct-menu">
          <div className="acct-menu-email">{email}</div>
          <button className="acct-signout" onClick={onSignOut}>Sign out</button>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Login, AccountChip });
