// login.jsx — Flowboard sign-in. Email + password against /api/auth/login,
// with SSO buttons stubbed (the design includes them) and the workspace URL
// kept as a visual element. On success we store the JWT and reload so the
// bootstrap in index.html can fetch data and mount FlowboardApp.

function LoginApp({ variant = "default", onAuthed }) {
  const [email, setEmail]       = React.useState(variant === "demo" ? "aya.okafor@acme.co" : "");
  const [password, setPassword] = React.useState(variant === "demo" ? "password123" : "");
  const [workspace, setWorkspace] = React.useState(variant === "error" ? "acme-corp" : "acme");
  const [remember, setRemember] = React.useState(true);
  const [loading, setLoading]   = React.useState(null); // "google" | "microsoft" | "ws" | null
  const [errorMsg, setErrorMsg] = React.useState(variant === "error" ? "We couldn't find that workspace." : "");

  async function signIn() {
    if (!email.trim() || !password) {
      setErrorMsg("Enter your email and password to continue.");
      return;
    }
    setLoading("ws"); setErrorMsg("");
    try {
      const res = await api.auth.login(email.trim(), password);
      if (res && res.token) {
        if (typeof onAuthed === "function") onAuthed(res);
        else location.reload();
      }
    } catch (e) {
      setErrorMsg(
        e.status === 401 ? "Email or password is incorrect."
      : e.status === 0 || e.message === "Failed to fetch" ? "Cannot reach the server. Is it running?"
      :  e.message || "Sign-in failed."
      );
      setLoading(null);
    }
  }

  function ssoNotice(provider) {
    setLoading(provider);
    setTimeout(() => {
      setLoading(null);
      setErrorMsg("SSO is not wired up in this prototype — sign in with email below.");
    }, 700);
  }

  return (
    <div className="login-stage">
      <div className="login-grid"/>
      <div className="login-blob"/>

      <div className="login-card">
        <div className="login-brand">
          <div className="login-logo"><img src="tabsyst-icon.svg?v=1" alt="Tabsyst"/></div>
          <div className="login-wordmark">ZeroProject</div>
        </div>

        <div>
          <div className="login-title">Sign in to your workspace</div>
          <div className="login-sub">
            Continue with your work account or use your email and password.
          </div>
        </div>

        {errorMsg && (
          <div className="login-error">
            <div className="login-error-icon">!</div>
            <div className="login-error-body">
              <strong>{errorMsg}</strong>
              {variant === "error" && (
                <>
                  &nbsp;No workspace matches{" "}
                  <code style={{ fontFamily: "ui-monospace, monospace", background: "rgba(226,68,92,.1)", padding: "1px 4px", borderRadius: 3 }}>{workspace}</code>.
                </>
              )}
            </div>
          </div>
        )}

        {/* SSO */}
        <div className="login-sso">
          <button className="login-sso-btn" onClick={() => ssoNotice("google")} disabled={!!loading}>
            {loading === "google" ? <Spinner/> : <GoogleMark/>}
            <span>Continue with Google</span>
          </button>
          <button className="login-sso-btn" onClick={() => ssoNotice("microsoft")} disabled={!!loading}>
            {loading === "microsoft" ? <Spinner/> : <MicrosoftMark/>}
            <span>Continue with Microsoft</span>
          </button>
        </div>

        <div className="login-divider">or</div>

        {/* Email + password */}
        <div className="login-fields">
          <div className="login-field">
            <label className="login-label">Email</label>
            <div className="login-ws-input">
              <input type="email" placeholder="you@company.com" autoComplete="username"
                     value={email}
                     onChange={e => setEmail(e.target.value)}
                     onKeyDown={e => e.key === "Enter" && signIn()}/>
            </div>
          </div>

          <div className="login-field">
            <label className="login-label">Password</label>
            <div className="login-ws-input">
              <input type="password" placeholder="••••••••" autoComplete="current-password"
                     value={password}
                     onChange={e => setPassword(e.target.value)}
                     onKeyDown={e => e.key === "Enter" && signIn()}/>
            </div>
            <span className="login-hint">
              Seeded users sign in with <code style={{ fontFamily: "ui-monospace, monospace" }}>password123</code>
            </span>
          </div>

          <div className="login-field">
            <label className="login-label">Workspace URL</label>
            <div className="login-ws-input">
              <input type="text" placeholder="your-team" value={workspace}
                     onChange={e => setWorkspace(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ""))}/>
              <span className="login-ws-suffix">.flowboard.app</span>
            </div>
            <span className="login-hint">
              Single-workspace prototype — any value is accepted.
            </span>
          </div>

          <div className="login-row">
            <label className="login-checkbox">
              <input type="checkbox" checked={remember} onChange={e => setRemember(e.target.checked)}/>
              Remember me on this device
            </label>
          </div>

          <button className="login-submit" onClick={signIn}
                  disabled={!!loading || !email.trim() || !password}>
            {loading === "ws" ? <Spinner light/> : null}
            Continue
            {loading !== "ws" && <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>}
          </button>
        </div>

        <div className="login-foot">
          New to ZeroProject? <a href="#">Create a workspace</a>
        </div>
      </div>

      <div className="login-legal">
        © 2026 ZeroProject · <a href="#">Terms</a> · <a href="#">Privacy</a> · <a href="#">Security</a>
      </div>
    </div>
  );
}

// ── Brand marks ─────────────────────────────────────
function GoogleMark() {
  return (
    <svg width="18" height="18" viewBox="0 0 48 48" aria-hidden="true">
      <path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"/>
      <path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"/>
      <path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"/>
      <path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"/>
    </svg>
  );
}
function MicrosoftMark() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" aria-hidden="true">
      <rect x="1"  y="1"  width="10" height="10" fill="#F25022"/>
      <rect x="13" y="1"  width="10" height="10" fill="#7FBA00"/>
      <rect x="1"  y="13" width="10" height="10" fill="#00A4EF"/>
      <rect x="13" y="13" width="10" height="10" fill="#FFB900"/>
    </svg>
  );
}
function Spinner({ light }) {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" style={{ animation: "spin 0.9s linear infinite" }}>
      <circle cx="12" cy="12" r="9" fill="none"
              stroke={light ? "rgba(255,255,255,.35)" : "#e6e9ef"} strokeWidth="3"/>
      <path d="M21 12a9 9 0 0 0-9-9" fill="none"
            stroke={light ? "white" : "var(--brand)"} strokeWidth="3" strokeLinecap="round"/>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </svg>
  );
}

Object.assign(window, { LoginApp, GoogleMark, MicrosoftMark });
