// Vanday — Settings → Connections
//
// Shows each social platform with connection status. Today the "Connect"
// button opens Upload-Post's dashboard in a new tab (their hosted OAuth
// flow). When Upload-Post documents an embedded connect URL, we replace
// the href with that and the page is otherwise unchanged.

const CONNECTION_PLATFORMS = [
  { id: "instagram", name: "Instagram", color: "oklch(0.62 0.18 18)",  blurb: "Post images + reels to your business or creator account." },
  { id: "facebook",  name: "Facebook",  color: "oklch(0.48 0.13 250)", blurb: "Post to a Facebook Page you manage (not personal profile)." },
  { id: "linkedin",  name: "LinkedIn",  color: "oklch(0.42 0.13 240)", blurb: "Post to your personal LinkedIn or a Company Page." },
  { id: "pinterest", name: "Pinterest", color: "oklch(0.55 0.18 18)",  blurb: "Pin to a board on your connected Pinterest account." },
  { id: "x",         name: "X",         color: "oklch(0.2 0.005 80)",  blurb: "Post tweets to your X account." },
];

function ConnectionsSection() {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [openingConnect, setOpeningConnect] = React.useState(false);

  const authHeaders = async () => {
    try {
      const t = window.Clerk?.session ? await window.Clerk.session.getToken() : null;
      return t ? { Authorization: `Bearer ${t}` } : {};
    } catch { return {}; }
  };

  const load = React.useCallback(async () => {
    setLoading(true); setError(null);
    try {
      const r = await fetch("/api/social/connections", { headers: await authHeaders() });
      const body = await r.json();
      if (!r.ok) { setError(body.error || `Server returned ${r.status}`); return; }
      setData(body);
    } catch (err) {
      setError("Couldn't reach the server.");
    } finally { setLoading(false); }
  }, []);

  React.useEffect(() => { load(); }, [load]);

  // Auto-refresh status when the user comes back from the Upload-Post OAuth
  // flow. The Upload-Post hosted page redirects to our `redirect_url` which
  // we set to .../?back_from=connect. If we see that in the URL, refresh
  // and clean the URL.
  React.useEffect(() => {
    const p = new URLSearchParams(window.location.search);
    if (p.get("back_from") === "connect") {
      load();
      p.delete("back_from");
      const qs = p.toString();
      window.history.replaceState({}, "", window.location.pathname + (qs ? "?" + qs : "") + window.location.hash);
    }
  }, [load]);

  // Open the Upload-Post hosted "connect" page for one or all platforms.
  // We get a 48-hour short-lived URL from our /api/social/connect-link
  // endpoint then open it in a new tab.
  const openConnectFlow = React.useCallback(async (platforms) => {
    setOpeningConnect(true);
    try {
      const redirectUrl = `${window.location.origin}/?back_from=connect#settings/connections`;
      const r = await fetch("/api/social/connect-link", {
        method: "POST",
        headers: { "Content-Type": "application/json", ...(await authHeaders()) },
        body: JSON.stringify({ platforms, redirectUrl }),
      });
      const body = await r.json();
      if (!r.ok || !body.accessUrl) {
        window.alert("Couldn't generate the connect link: " + (body.error || `HTTP ${r.status}`));
        return;
      }
      window.open(body.accessUrl, "_blank", "noopener,noreferrer");
    } catch (err) {
      window.alert("Couldn't reach the server. Try again in a moment.");
    } finally {
      setOpeningConnect(false);
    }
  }, []);

  return (
    <>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 4 }}>
        <div>
          <h1 className="settings-h1">Connections</h1>
          <p className="settings-sub">
            Connect your social accounts so Vanday can publish on your behalf.
            We use <a href="https://www.upload-post.com" target="_blank" rel="noreferrer" style={{ color: "var(--brand)" }}>Upload-Post</a> under the hood — that's where the OAuth handoff happens.
          </p>
        </div>
        <button className="btn" onClick={load} disabled={loading}>
          {loading ? "Refreshing…" : "Refresh status"}
        </button>
      </div>

      {error && (
        <div style={{
          marginTop: 16, padding: 12,
          background: "oklch(0.96 0.04 24)",
          border: "1px solid oklch(0.85 0.08 24)",
          borderRadius: 8, fontSize: 13, color: "oklch(0.42 0.16 24)",
        }}>
          {error}
        </div>
      )}

      <div style={{ marginTop: 18, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 12, overflow: "hidden" }}>
        {CONNECTION_PLATFORMS.map((p, idx) => {
          const status = data?.platforms?.[p.id]?.status || "unknown";
          const detail = data?.platforms?.[p.id]?.detail;
          return (
            <div
              key={p.id}
              style={{
                display: "flex", alignItems: "center", gap: 14,
                padding: "16px 18px",
                borderTop: idx === 0 ? "none" : "1px solid var(--border)",
              }}
            >
              <div
                aria-hidden
                style={{
                  width: 36, height: 36, borderRadius: 8,
                  background: p.color, color: "white",
                  display: "grid", placeItems: "center",
                  fontWeight: 700, fontSize: 13, flexShrink: 0,
                }}
              >{p.name[0]}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600, fontSize: 14 }}>{p.name}</div>
                <div style={{ fontSize: 12.5, color: "var(--text-muted)", marginTop: 2 }}>
                  {p.blurb}
                </div>
              </div>
              <StatusPill status={status} detail={detail} />
              <button
                className="btn"
                onClick={() => openConnectFlow([p.id])}
                disabled={openingConnect}
                title={status === "connected"
                  ? `Manage your ${p.name} connection in a new tab`
                  : `Connect ${p.name} (opens an authorisation page in a new tab)`}
                style={{ cursor: openingConnect ? "wait" : "pointer" }}
              >
                <IcExternal size={13} /> {status === "connected" ? "Manage" : "Connect"}
              </button>
            </div>
          );
        })}
      </div>

      {/* Quick "Connect all" shortcut */}
      <div style={{ marginTop: 14, display: "flex", justifyContent: "flex-end" }}>
        <button
          className="btn primary"
          onClick={() => openConnectFlow(CONNECTION_PLATFORMS.map((p) => p.id))}
          disabled={openingConnect}
          style={{ cursor: openingConnect ? "wait" : "pointer" }}
        >
          <IcExternal size={13} /> {openingConnect ? "Opening…" : "Connect all accounts"}
        </button>
      </div>

      <div style={{
        marginTop: 16, padding: 12,
        background: "var(--surface-sunken)",
        border: "1px solid var(--border)",
        borderRadius: 10, fontSize: 12.5, color: "var(--text-muted)",
      }}>
        <strong style={{ color: "var(--text)" }}>How connecting works today:</strong>{" "}
        Click <em>Connect</em> for any platform — it opens our Upload-Post dashboard in a new tab.
        Sign in there, click <em>Connect</em> for that platform, and authorize Vanday on the
        platform itself (Meta / LinkedIn / etc.). When you come back here and hit <em>Refresh status</em>,
        the platform will show as connected. An in-app connect flow is on the roadmap.
        {data?.sharedWithBeta && (
          <>
            <br /><br />
            <strong style={{ color: "var(--text)" }}>Beta note:</strong>{" "}
            All beta workspaces currently share one Upload-Post profile, so connecting a platform
            here connects it for the whole beta. Once embedded OAuth ships, each workspace will
            get its own isolated profile.
          </>
        )}
      </div>
    </>
  );
}

function StatusPill({ status, detail }) {
  let label, bg, fg;
  if (status === "connected") {
    label = detail ? `Connected · ${detail}` : "Connected";
    bg = "oklch(0.93 0.07 155)"; fg = "oklch(0.32 0.13 155)";
  } else if (status === "not_connected") {
    label = "Not connected";
    bg = "var(--surface-sunken)"; fg = "var(--text-muted)";
  } else {
    label = "Status unknown";
    bg = "var(--surface-sunken)"; fg = "var(--text-faint)";
  }
  return (
    <span style={{
      padding: "4px 10px", borderRadius: 999,
      fontSize: 11.5, fontWeight: 600,
      background: bg, color: fg, flexShrink: 0,
    }}>{label}</span>
  );
}

window.ConnectionsSection = ConnectionsSection;
