/* global React */

// t08 — login screen. Renders before the main app when no JWT is held.
// On successful POST /api/auth/login the parent stores { token, user }
// in memory (NOT localStorage) and the main app mounts. Visual language
// matches the existing dark forest / cream palette: dark background image,
// glass card, cream/leaf accents. No new design tokens introduced.

function LoginPage({ onLoggedIn, defaultEmail = "" }) {
  const [email, setEmail] = React.useState(defaultEmail);
  const [password, setPassword] = React.useState("");
  // v01n — Stay-logged-in toggle. When checked, /api/auth/login issues
  // a 7-day JWT instead of the default 24h. The choice is also
  // remembered locally so the checkbox is pre-ticked on next visit.
  const [remember, setRemember] = React.useState(() => {
    try { return localStorage.getItem("filmtracker.remember") === "1"; } catch (e) { return false; }
  });
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);
  const emailRef = React.useRef(null);
  // v01a — request-access modal toggle. Shown via a small link below
  // the login form; posts to /api/auth/request-access which emails
  // saltercreekltd@gmail.com via emailService. No self-service signup.
  const [showRequest, setShowRequest] = React.useState(false);

  React.useEffect(() => {
    if (emailRef.current && !defaultEmail) emailRef.current.focus();
  }, [defaultEmail]);

  const submit = (e) => {
    e.preventDefault();
    if (submitting) return;
    setError(null);
    setSubmitting(true);
    fetch("/api/auth/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email: email.trim(), password, remember }),
    })
      .then(async r => {
        const body = await r.json().catch(() => ({}));
        if (!r.ok) throw new Error(body.error || `HTTP ${r.status}`);
        return body;
      })
      .then(({ token, user }) => {
        if (!token || !user) throw new Error("Malformed login response.");
        // v01n — remember the user's preference so the checkbox is
        // pre-ticked next time. The token itself is persisted by the
        // App-level handleLoggedIn handler.
        try { localStorage.setItem("filmtracker.remember", remember ? "1" : "0"); } catch (e) {}
        onLoggedIn && onLoggedIn(token, user, { remember });
      })
      .catch(err => {
        setError(err.message || "Login failed.");
        setSubmitting(false);
      });
  };

  return (
    <div className="login-shell">
      <div className="login-backdrop" aria-hidden="true"/>
      <main className="login-card glass">
        <div className="login-brand">
          <div className="login-eyebrow">FILM TRACKER</div>
          <h1 className="login-title">Sign in</h1>
          <div className="login-sub">Production tracker for film &amp; VFX projects</div>
        </div>

        <form className="login-form" onSubmit={submit} autoComplete="on">
          <label className="login-field">
            <span className="login-label">Email</span>
            <input
              ref={emailRef}
              className="login-input"
              type="email"
              autoComplete="email"
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="you@example.com"
            />
          </label>
          <label className="login-field">
            <span className="login-label">Password</span>
            <input
              className="login-input"
              type="password"
              autoComplete="current-password"
              required
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="••••••••"
            />
          </label>

          {error && <div className="login-error" role="alert">{error}</div>}

          {/* v01n — stay-logged-in toggle. Sends `remember: true` to
              /api/auth/login which issues a 7-day token (vs 24h
              default). */}
          <label className="login-remember">
            <input
              type="checkbox"
              checked={remember}
              onChange={(e) => setRemember(e.target.checked)}
              disabled={submitting}
            />
            <span>Stay logged in for 7 days</span>
          </label>

          <button className="login-submit" type="submit" disabled={submitting || !email || !password}>
            {submitting ? "Signing in…" : "Sign in"}
          </button>
        </form>

        <div className="login-foot">
          Need an account?{" "}
          <button
            type="button"
            className="login-request-link"
            onClick={() => setShowRequest(true)}
          >
            Request access
          </button>
        </div>
      </main>
      {showRequest && <RequestAccessModal onClose={() => setShowRequest(false)}/>}
    </div>
  );
}

// v01a — Request-access modal. Captured outside <main className="login-card">
// so the form sits above the glass card on its own backdrop. POSTs to
// /api/auth/request-access (which is in AUTH_EXEMPT_PATHS, so no token
// required). The endpoint always returns ok=true to avoid leaking SMTP
// state, so the success message is the same whether email actually got
// dispatched or just logged.
function RequestAccessModal({ onClose }) {
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [message, setMessage] = React.useState("");
  const [submitting, setSubmitting] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const [sent, setSent] = React.useState(false);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [onClose]);

  const submit = (e) => {
    e.preventDefault();
    if (submitting) return;
    setErr(null);
    if (!name.trim() || !email.trim()) {
      setErr("Name and email are required.");
      return;
    }
    setSubmitting(true);
    fetch("/api/auth/request-access", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name: name.trim(), email: email.trim(), message: message.trim() }),
    })
      .then(async r => {
        const body = await r.json().catch(() => ({}));
        if (!r.ok) throw new Error(body.error || `HTTP ${r.status}`);
        return body;
      })
      .then(() => setSent(true))
      .catch(e2 => setErr(e2.message || "Could not send request."))
      .finally(() => setSubmitting(false));
  };

  const stop = (e) => e.stopPropagation();
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal-card glass auth-modal-card" style={{ maxWidth: 460 }} onClick={stop} role="dialog" aria-modal="true">
        <button className="modal-close-btn" aria-label="Close" onClick={onClose}>
          <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
        </button>
        <div className="auth-modal-head">
          <div className="auth-modal-eyebrow">REQUEST ACCESS</div>
          <div className="auth-modal-title">Ask for an account</div>
          <div className="auth-modal-sub">We will send your details to the project admin. There is no self-service signup yet — they will add you manually.</div>
        </div>
        {sent ? (
          <div className="auth-modal-body">
            <div className="auth-msg auth-msg--ok">Request sent. The admin will be in touch shortly.</div>
            <button type="button" className="auth-submit" onClick={onClose}>Done</button>
          </div>
        ) : (
          <form className="auth-modal-body auth-form" onSubmit={submit} autoComplete="off">
            <label className="auth-field">
              <span className="auth-field-label">Your name</span>
              <input className="auth-input" type="text" required
                value={name} onChange={(e) => setName(e.target.value)} disabled={submitting}/>
            </label>
            <label className="auth-field">
              <span className="auth-field-label">Email</span>
              <input className="auth-input" type="email" required
                value={email} onChange={(e) => setEmail(e.target.value)} disabled={submitting}/>
            </label>
            <label className="auth-field">
              <span className="auth-field-label">Message (optional)</span>
              <textarea className="auth-input auth-textarea" rows={4}
                placeholder="Tell us a little about why you would like access…"
                value={message} onChange={(e) => setMessage(e.target.value)} disabled={submitting}/>
            </label>
            {err && <div className="auth-msg auth-msg--err" role="alert">{err}</div>}
            <button className="auth-submit" type="submit" disabled={submitting || !name || !email}>
              {submitting ? "Sending…" : "Send request"}
            </button>
          </form>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { LoginPage, RequestAccessModal });
