// PROFILE — account, saved items, design history. Opened from the sidebar
// logo menu ("Go to profile") or by clicking the user card.

function ProfilePage({ user, authReady, onOpenProject, onNavigate }) {
  const [projects, setProjects] = useState(null);
  const [busyId, setBusyId] = useState(null);
  const [tab, setTab] = useState("saved"); // saved | history | account
  const [signingOut, setSigningOut] = useState(false);

  // listProjects() requires sign-in, and Auth.init() resolves asynchronously
  // — fetching before that finishes would just throw and get stuck showing
  // "Nothing saved yet" forever. Wait for auth to actually resolve first.
  const refresh = () => {
    if (!authReady) return;
    if (!user) { setProjects([]); return; }
    API.listProjects()
      .then(({ projects }) => setProjects(projects))
      .catch(() => setProjects([]));
  };
  useEffect(refresh, [authReady, user?.id]);

  const fullName = user.user_metadata?.full_name || user.user_metadata?.name;
  const avatarUrl = user.user_metadata?.avatar_url || user.user_metadata?.picture || null;
  const displayName = fullName || user.email || "You";
  const initials = (fullName || user.email || "U").slice(0, 2).toUpperCase();
  const email = user.email;

  const handleDelete = async (p) => {
    if (!window.confirm(`Delete "${p.name}"? This can't be undone.`)) return;
    setBusyId(p.id);
    try {
      await API.deleteProject(p.id);
      refresh();
    } catch (e) {
      alert(`Delete failed: ${e.message}`);
    } finally {
      setBusyId(null);
    }
  };

  const fmtDate = (iso) => {
    if (!iso) return "—";
    const d = new Date(iso);
    if (isNaN(d)) return "—";
    return d.toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" }) +
      " · " + d.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });
  };

  const sourceLabel = (s) => (s === "generate" ? "AI generated" : s === "template" ? "From template" : "Manual");

  const savedCount = projects ? projects.length : 0;
  const lastActive = projects && projects.length ? fmtDate(projects[0].updatedAt) : "—";

  return (
    <div className="fade-in">
      {/* HEADER */}
      <div className="eyebrow">PROFILE</div>
      <div style={{ display: "flex", alignItems: "center", gap: 20, marginTop: 14, flexWrap: "wrap" }}>
        <div style={{
          width: 72, height: 72, borderRadius: 999, flexShrink: 0,
          display: "grid", placeItems: "center",
          fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 26, color: "#FFFFFF",
          background: "#070707",
          border: "3px solid transparent",
          backgroundImage: "linear-gradient(#070707, #070707), var(--holo-img)",
          backgroundOrigin: "padding-box, border-box",
          backgroundClip: "padding-box, border-box",
          backgroundSize: "auto, cover",
        }}>
          {avatarUrl ? (
            <img src={avatarUrl} alt="" style={{ width: "100%", height: "100%", borderRadius: 999, objectFit: "cover" }} />
          ) : initials}
        </div>
        <div style={{ flex: 1, minWidth: 200 }}>
          <h1 className="page-title" style={{ fontSize: 44, margin: 0 }}>{displayName}</h1>
          <div style={{ fontSize: 14, color: "var(--ink-3)", marginTop: 4 }}>
            {email || "Shared team workspace"} · Flexxi
          </div>
        </div>
        <div style={{ display: "flex", gap: 24 }}>
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 32, fontWeight: 700, letterSpacing: "-0.03em" }}>{savedCount}</div>
            <div style={{ fontSize: 12, color: "var(--ink-3)" }}>Saved designs</div>
          </div>
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 15, fontWeight: 600, marginTop: 10 }}>{lastActive}</div>
            <div style={{ fontSize: 12, color: "var(--ink-3)" }}>Last active</div>
          </div>
        </div>
      </div>

      {/* TABS */}
      <div className="gen-tab-row" style={{ marginTop: 36 }}>
        <button className={`gen-tab ${tab === "saved" ? "active" : ""}`} onClick={() => setTab("saved")}>
          <Icons.Grid size={13} style={{ marginRight: 6, verticalAlign: "-2px" }} /> Saved items
        </button>
        <button className={`gen-tab ${tab === "history" ? "active" : ""}`} onClick={() => setTab("history")}>
          <Icons.Layers size={13} style={{ marginRight: 6, verticalAlign: "-2px" }} /> Design history
        </button>
        <button className={`gen-tab ${tab === "account" ? "active" : ""}`} onClick={() => setTab("account")}>
          <Icons.Lock size={13} style={{ marginRight: 6, verticalAlign: "-2px" }} /> Account
        </button>
      </div>

      {/* SAVED ITEMS */}
      {tab === "saved" && (
        <div style={{ marginTop: 24 }}>
          {projects === null ? (
            <div style={{ color: "var(--ink-3)", fontSize: 14, padding: 40, textAlign: "center" }}>Loading…</div>
          ) : projects.length === 0 ? (
            <div className="card" style={{ padding: 48, textAlign: "center" }}>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 600 }}>Nothing saved yet.</div>
              <p style={{ color: "var(--ink-3)", fontSize: 14, margin: "8px 0 20px" }}>
                Open a template or generate a design, then hit Save — it'll show up here.
              </p>
              <button className="btn btn-primary" onClick={() => onNavigate("/templates")}>Browse templates</button>
            </div>
          ) : (
            <div className="grid-3">
              {projects.map((p) => (
                <div key={p.id} className="card hover-card" style={{ padding: 18, cursor: "pointer" }} onClick={() => onOpenProject(p.id)}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 10 }}>
                    <div style={{
                      width: 42, height: 42, borderRadius: 10, flexShrink: 0, display: "grid", placeItems: "center",
                      background: "#070707", color: "#FFFFFF",
                    }}>
                      <Icons.Grid size={18} />
                    </div>
                    <button
                      className="btn btn-sm btn-ghost"
                      style={{ padding: "5px 8px", flexShrink: 0 }}
                      title="Delete"
                      onClick={(e) => { e.stopPropagation(); handleDelete(p); }}
                      disabled={busyId === p.id}
                    >
                      {busyId === p.id ? <span className="spinner" /> : <Icons.Trash size={13} />}
                    </button>
                  </div>
                  <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 16, marginTop: 14, letterSpacing: "-0.01em", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {p.name}
                  </div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4 }}>
                    {p.category || "Design"} · {p.slideCount} slide{p.slideCount === 1 ? "" : "s"} · {sourceLabel(p.source)}
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 14 }}>
                    <span className="pill" style={{ fontSize: 10.5 }}>{fmtDate(p.updatedAt).split(" · ")[0]}</span>
                    <span style={{ fontSize: 12.5, color: "var(--ink-2)", display: "inline-flex", alignItems: "center", gap: 5 }}>
                      Open <Icons.ArrowRight size={13} />
                    </span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* DESIGN HISTORY */}
      {tab === "history" && (
        <div style={{ marginTop: 24 }}>
          {projects === null ? (
            <div style={{ color: "var(--ink-3)", fontSize: 14, padding: 40, textAlign: "center" }}>Loading…</div>
          ) : projects.length === 0 ? (
            <div className="card" style={{ padding: 40, textAlign: "center", color: "var(--ink-3)", fontSize: 14 }}>
              No design activity yet.
            </div>
          ) : (
            <div className="card" style={{ padding: 0, overflow: "hidden" }}>
              {[...projects]
                .sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
                .map((p, i, arr) => (
                  <div
                    key={p.id}
                    onClick={() => onOpenProject(p.id)}
                    style={{
                      display: "flex", alignItems: "center", gap: 16, padding: "16px 22px", cursor: "pointer",
                      borderBottom: i === arr.length - 1 ? "0" : "1px solid var(--line)",
                    }}
                    onMouseEnter={(e) => (e.currentTarget.style.background = "var(--bg-2)")}
                    onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}
                  >
                    <div style={{ width: 8, height: 8, borderRadius: 999, background: p.source === "generate" ? "var(--holo)" : "var(--ink)", flexShrink: 0 }} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 600, fontSize: 14.5, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.name}</div>
                      <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>
                        {sourceLabel(p.source)} · {p.category || "Design"}
                        {p.createdAt !== p.updatedAt ? " · edited" : " · created"}
                      </div>
                    </div>
                    <div style={{ fontSize: 12, color: "var(--ink-3)", flexShrink: 0 }}>{fmtDate(p.updatedAt)}</div>
                    <Icons.ArrowRight size={14} />
                  </div>
                ))}
            </div>
          )}
        </div>
      )}

      {/* ACCOUNT */}
      {tab === "account" && (
        <div style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 14, maxWidth: 640 }}>
          <div className="card" style={{ padding: 24 }}>
            <div className="inspector-label" style={{ marginBottom: 14 }}>Sign-in</div>
            <Row k="Name" v={fullName || "—"} />
            <Row k="Email" v={user.email || "—"} />
            <Row k="Method" v="Google (SSO)" />
            <Row k="AI generation" v="Enabled" last />
          </div>

          <div className="card" style={{ padding: 24 }}>
            <div className="inspector-label" style={{ marginBottom: 14 }}>Session</div>
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              <button
                className="btn btn-surface"
                disabled={signingOut}
                onClick={async () => {
                  setSigningOut(true);
                  try {
                    await Auth.signOut();
                  } catch (e) {
                    setSigningOut(false);
                  }
                }}
              >
                {signingOut ? <span className="spinner" style={{ width: 13, height: 13 }} /> : null} Sign out
              </button>
              <button
                className="btn btn-ghost"
                onClick={async () => {
                  try { await API.gateLock(); } catch (e) {}
                  window.location.reload();
                }}
              >
                <Icons.Lock size={13} /> Lock workspace
              </button>
            </div>
            <p style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 12, marginBottom: 0 }}>
              Locking the workspace signs this browser out of the shared password session.
            </p>
          </div>
        </div>
      )}
    </div>
  );
}

function Row({ k, v, last }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: 16, padding: "10px 0", borderBottom: last ? "0" : "1px solid var(--line)" }}>
      <span style={{ fontSize: 13, color: "var(--ink-3)", flexShrink: 0 }}>{k}</span>
      <span style={{ fontSize: 13.5, fontWeight: 500, textAlign: "right" }}>{v}</span>
    </div>
  );
}

window.ProfilePage = ProfilePage;
