/* Cloud Sync Keys: mint, list, revoke. Requires a SWA-authenticated user. */

function KeysPage({ go }) {
  const [me, setMe] = React.useState(undefined);  // undefined = loading, null = not signed in, object = signed in
  const [keys, setKeys] = React.useState(null);
  const [error, setError] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [justMinted, setJustMinted] = React.useState(null);
  const [label, setLabel] = React.useState("");

  // Fetch /api/whoami once on mount. Null => kick off Google login.
  React.useEffect(() => {
    fetch("/api/whoami")
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => setMe(data || null))
      .catch(() => setMe(null));
  }, []);

  React.useEffect(() => {
    if (!me) return;
    refreshKeys();
  }, [me]);

  async function refreshKeys() {
    setError("");
    try {
      const r = await fetch("/api/keys");
      if (!r.ok) throw new Error(`whoops, /api/keys returned ${r.status}`);
      const data = await r.json();
      setKeys(data.keys || []);
    } catch (e) {
      setError(e.message);
    }
  }

  async function mint() {
    setBusy(true);
    setError("");
    try {
      const r = await fetch("/api/keys", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ label: label.trim() || "Untitled key" }),
      });
      const data = await r.json();
      if (!r.ok) throw new Error(data.error || `whoops, /api/keys returned ${r.status}`);
      setJustMinted(data);
      setLabel("");
      await refreshKeys();
    } catch (e) {
      setError(e.message);
    } finally {
      setBusy(false);
    }
  }

  async function revoke(id, lab) {
    if (!confirm(`Revoke "${lab}"? Any device using this key will stop syncing.`)) return;
    setBusy(true);
    setError("");
    try {
      const r = await fetch(`/api/keys/${id}`, { method: "DELETE" });
      if (!r.ok && r.status !== 404) throw new Error(`whoops, returned ${r.status}`);
      await refreshKeys();
    } catch (e) {
      setError(e.message);
    } finally {
      setBusy(false);
    }
  }

  // ---------- Render states ----------

  if (me === undefined) {
    return (
      <div className="page" data-screen-label="07 Keys (loading)">
        <section className="section" style={{ paddingTop: 64 }}>
          <div className="container">
            <p className="lead">Loading...</p>
          </div>
        </section>
      </div>
    );
  }

  if (me === null) {
    return (
      <div className="page" data-screen-label="07 Keys (not signed in)">
        <section className="section" style={{ paddingTop: 64 }}>
          <div className="container" style={{ maxWidth: 640 }}>
            <div className="eyebrow" style={{ marginBottom: 16 }}>Cloud Sync</div>
            <h1 style={{ marginBottom: 18 }}>Sign in to manage your sync keys.</h1>
            <p className="lead" style={{ marginBottom: 28 }}>
              You need a Google account to create the keys that let MCS desktop upload your stash to the cloud.
            </p>
            <a className="btn btn-primary"
               href="/.auth/login/google?post_login_redirect_uri=/%23keys"
               style={{ display: "inline-block", padding: "12px 24px",
                        background: "var(--accent)", color: "white",
                        textDecoration: "none", borderRadius: "var(--radius)",
                        fontWeight: 600 }}>
              Sign in with Google
            </a>
          </div>
        </section>
      </div>
    );
  }

  return (
    <div className="page" data-screen-label="07 Keys">
      <section className="section" style={{ paddingTop: 64 }}>
        <div className="container" style={{ maxWidth: 760 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 32 }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 16 }}>Cloud Sync</div>
              <h1 style={{ marginBottom: 12 }}>Your sync keys.</h1>
              <p className="kicker">Signed in as {me.userDetails}</p>
            </div>
            <a href="/.auth/logout?post_logout_redirect_uri=/" style={{ fontSize: 13 }}>Sign out</a>
          </div>

          {error && (
            <div className="card bordered" style={{ padding: 16, marginBottom: 24,
                  background: "rgba(216,84,58,.08)", borderColor: "var(--accent)" }}>
              <strong>Something went sideways:</strong> {error}
            </div>
          )}

          {justMinted && (
            <div className="card bordered" style={{ padding: 20, marginBottom: 24,
                  background: "var(--accent-soft)", borderColor: "var(--accent)" }}>
              <div className="kicker" style={{ marginBottom: 8 }}>New key minted</div>
              <p style={{ marginBottom: 12 }}>
                <strong>Copy this now.</strong> It will not be shown again. Paste it into
                MCS desktop under Settings &rarr; Cloud Sync.
              </p>
              <code style={{ display: "block", padding: 12, background: "var(--paper)",
                              border: "1px solid var(--line-soft)", borderRadius: 8,
                              fontFamily: "var(--mono-font)", fontSize: 14,
                              wordBreak: "break-all", marginBottom: 12 }}>
                {justMinted.key}
              </code>
              <button onClick={() => { navigator.clipboard.writeText(justMinted.key); }}
                      style={{ padding: "8px 16px", marginRight: 8 }}>
                Copy to clipboard
              </button>
              <button onClick={() => setJustMinted(null)}
                      style={{ padding: "8px 16px" }}>
                I've copied it, dismiss
              </button>
            </div>
          )}

          <div className="card bordered" style={{ padding: 20, marginBottom: 32 }}>
            <div className="kicker" style={{ marginBottom: 8 }}>Create new key</div>
            <div style={{ display: "flex", gap: 8 }}>
              <input type="text" placeholder="Label (e.g. Josh's PC)"
                     value={label} onChange={(e) => setLabel(e.target.value)}
                     style={{ flex: 1, padding: "10px 12px",
                              border: "1px solid var(--line-soft)",
                              borderRadius: 8, fontSize: 14,
                              background: "var(--paper-3)" }}/>
              <button onClick={mint} disabled={busy}
                      style={{ padding: "10px 24px", background: "var(--accent)",
                               color: "white", border: 0, borderRadius: 8,
                               fontWeight: 600, cursor: busy ? "wait" : "pointer" }}>
                {busy ? "..." : "Mint key"}
              </button>
            </div>
          </div>

          <h2 style={{ marginBottom: 16, fontSize: 20 }}>Existing keys</h2>
          {keys === null ? (
            <p>Loading...</p>
          ) : keys.length === 0 ? (
            <p className="kicker">No keys yet. Mint one above to start syncing from MCS desktop.</p>
          ) : (
            <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
              {keys.map((k) => (
                <li key={k.id} className="card bordered"
                    style={{ padding: 16, marginBottom: 12,
                             opacity: k.active ? 1 : 0.55 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <div>
                      <div style={{ fontWeight: 600, marginBottom: 4 }}>{k.label}</div>
                      <div className="kicker">
                        <code style={{ fontFamily: "var(--mono-font)" }}>{k.prefix}...</code>
                        {" · created "}{new Date(k.createdAt).toLocaleDateString()}
                        {k.lastUsedAt && ` · last used ${new Date(k.lastUsedAt).toLocaleDateString()}`}
                        {!k.active && " · REVOKED"}
                      </div>
                    </div>
                    {k.active && (
                      <button onClick={() => revoke(k.id, k.label)} disabled={busy}
                              style={{ padding: "6px 14px", background: "transparent",
                                       color: "var(--accent-deep)", border: "1px solid var(--accent)",
                                       borderRadius: 6, fontSize: 13,
                                       cursor: busy ? "wait" : "pointer" }}>
                        Revoke
                      </button>
                    )}
                  </div>
                </li>
              ))}
            </ul>
          )}
        </div>
      </section>
    </div>
  );
}

// Expose for the PAGES map in index.html. Same pattern as login.jsx, home.jsx, etc.
Object.assign(window, { KeysPage });
