/* Channels — connect / disconnect REAL social accounts via the platform API
   (@leap/social-integration). Live-only: offline the prototype simulates
   channels. Scoped to the active client's org (its own workspace). */
(function () {
  const S = window.CroprStore;
  const API = window.LeapAPI;

  const META = {
    x: { label: "X", color: "#0f1419", ini: "X" }, facebook: { color: "#1877F2", ini: "FB" },
    instagram: { color: "#E4405F", ini: "IG" }, linkedin: { color: "#0A66C2", ini: "LI" },
    linkedin_page: { color: "#0A66C2", ini: "LP" }, youtube: { color: "#FF0000", ini: "YT" },
    tiktok: { color: "#111", ini: "TT" }, pinterest: { color: "#E60023", ini: "PIN" },
    telegram: { color: "#26A5E4", ini: "TG" },
  };
  const ini = (p) => (META[p] && META[p].ini) || p.slice(0, 2).toUpperCase();
  const inp = { flex: "1 1 220px", fontFamily: "inherit", fontSize: 13, padding: "8px 10px", borderRadius: 10, border: "1px solid var(--border-strong)", color: "var(--fg1)", background: "var(--surface)", boxSizing: "border-box" };

  function orgId() {
    try { const c = S.getActiveClient && S.getActiveClient(); if (c && c._orgId) return c._orgId; } catch (e) {}
    return (window.LeapGate && window.LeapGate.orgId && window.LeapGate.orgId()) || null;
  }

  function Channels({ onToast }) {
    const live = !!(API && API.configured());
    const [platforms, setPlatforms] = React.useState([]);
    const [conns, setConns] = React.useState([]);
    const [loading, setLoading] = React.useState(live);
    const [tg, setTg] = React.useState({ botToken: "", chatId: "" });
    const [busy, setBusy] = React.useState(null);
    const org = orgId();
    const toast = (m, k) => onToast && onToast(m, k || "ok");
    const errText = (e) => { try { return JSON.parse(e.body).message || e.message; } catch (x) { return e.body || e.message; } };

    async function refresh() {
      if (!live || !org) { setLoading(false); return; }
      // Fetch independently: the platform catalog is static, so a failing connections
      // read (e.g. a brand-new workspace) must NOT blank out the list of channels you
      // can connect. Each is best-effort.
      try { setPlatforms((await API.social.platforms(org)) || []); }
      catch (e) { toast("Couldn't load channels: " + errText(e), "error"); }
      try { setConns((await API.social.connections(org)) || []); }
      catch (e) { setConns([]); /* no connections yet / workspace warming up — non-fatal */ }
      setLoading(false);
    }

    React.useEffect(() => {
      try {
        const q = new URLSearchParams(window.location.search);
        if (q.get("connected")) {
          toast("Connected " + q.get("connected") + " (" + (q.get("accounts") || 0) + " account)", "ok");
          const u = new URL(window.location.href); u.search = ""; window.history.replaceState({}, "", u.toString());
        }
      } catch (e) {}
      refresh();
    }, []);

    const connected = (p) => conns.filter((c) => c.platform === p);

    async function connect(p) {
      setBusy(p);
      try { await API.social.startConnect(org, p, window.location.origin + window.location.pathname); }
      catch (e) { toast("Connect failed: " + errText(e), "error"); setBusy(null); }
    }
    async function connectTelegram() {
      if (!tg.botToken || !tg.chatId) return;
      setBusy("telegram");
      try { await API.social.connectTelegram(org, { botToken: tg.botToken, chatId: tg.chatId, accountName: "Telegram channel" }); setTg({ botToken: "", chatId: "" }); toast("Telegram connected"); await refresh(); }
      catch (e) { toast("Telegram connect failed: " + errText(e), "error"); }
      setBusy(null);
    }
    async function disconnect(c) {
      setBusy(c.id);
      try { await API.social.disconnect(org, c.id); toast("Disconnected " + c.platform); await refresh(); }
      catch (e) { toast("Disconnect failed: " + errText(e), "error"); }
      setBusy(null);
    }
    // Shareable client connect-link — the agency-friendly path: whoever holds the
    // client's social logins opens it and authorises with their OWN browser session,
    // so X's "sticky account" problem never traps you on the wrong account.
    const [link, setLink] = React.useState(null);
    const clientName = (function () { try { const c = window.CroprStore.getActiveClient && window.CroprStore.getActiveClient(); return c && c.name ? c.name : "this client"; } catch (e) { return "this client"; } })();
    async function makeLink() {
      setBusy("link");
      try {
        const r = await API.social.connectLink(org, clientName, 24);
        setLink(r);
        try { await navigator.clipboard.writeText(r.url); toast("Connect link copied to clipboard"); }
        catch (e) { toast("Connect link created — copy it below"); }
      } catch (e) { toast("Couldn't create link: " + errText(e), "error"); }
      setBusy(null);
    }

    if (!live) return <div style={{ padding: 20, color: "var(--fg3)", border: "1px solid var(--border)", borderRadius: 12 }}>Connecting real social accounts needs live mode (a configured Leap API). In the offline demo, channels are simulated.</div>;
    if (loading) return <div style={{ padding: 20, color: "var(--fg3)" }}>Loading channels…</div>;

    return (
      <div style={{ maxWidth: 720 }}>
        <div style={{ fontSize: 13, color: "var(--fg3)", marginBottom: 14 }}>Connect the accounts Leap publishes to. OAuth opens the network's consent screen; Telegram uses a bot token. Accounts connect to the active client's workspace.</div>

        {/* Share a connect link — let whoever holds the client's logins connect their
            own accounts, from their own browser (no Leap login, no account collisions). */}
        <div style={{ border: "1px solid var(--accent)", background: "var(--accent-weak)", borderRadius: 14, padding: "14px 16px", marginBottom: 18 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <Icon name="link" size={18} color="var(--accent)" />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 700 }}>Send {clientName} a connect link</div>
              <div style={{ fontSize: 12, color: "var(--fg2)", marginTop: 2, lineHeight: 1.45 }}>They open it in their own browser (already logged into their accounts) and authorise — the accounts land in this client's workspace. No Leap login needed.</div>
            </div>
            <Button size="sm" variant="primary" icon="link" disabled={busy === "link"} onClick={makeLink}>{busy === "link" ? "Creating…" : (link ? "New link" : "Get connect link")}</Button>
          </div>
          {link && (
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 12 }}>
              <input readOnly value={link.url} onFocus={(e) => e.target.select()} style={{ flex: 1, fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--fg1)", background: "var(--surface)", border: "1px solid var(--border-strong)", borderRadius: 9, padding: "8px 10px", outline: "none" }} />
              <Button size="sm" variant="secondary" icon="copy" onClick={() => { try { navigator.clipboard.writeText(link.url); toast("Copied"); } catch (e) {} }}>Copy</Button>
            </div>
          )}
          {link && <div style={{ fontSize: 11, color: "var(--fg4)", marginTop: 6 }}>Expires {new Date(link.expiresAt).toLocaleString("en-GB", { day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit" })} · anyone with the link can connect an account to {clientName}.</div>}
        </div>

        {platforms.map((p) => {
          const meta = META[p.platform] || {};
          const list = connected(p.platform);
          return (
            <div key={p.platform} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", border: "1px solid var(--border)", borderRadius: 12, marginBottom: 10, background: "var(--surface)" }}>
              <Avatar color={meta.color || "#666"} initials={ini(p.platform)} size={30} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600 }}>{p.label}</div>
                {list.length
                  ? <div style={{ fontSize: 12, color: "var(--fg2)" }}>{list.map((c) => c.accountName + " · " + c.status).join(", ")}</div>
                  : <div style={{ fontSize: 12, color: "var(--fg4)" }}>Not connected</div>}
              </div>
              {list.map((c) => <Button key={c.id} size="sm" variant="secondary" icon="x" disabled={busy === c.id} onClick={() => disconnect(c)}>Disconnect</Button>)}
              {p.platform !== "telegram" && <Button size="sm" variant="primary" icon="plus" disabled={busy === p.platform} onClick={() => connect(p.platform)}>{list.length ? "Add" : "Connect"}</Button>}
            </div>
          );
        })}
        <div style={{ padding: "12px 14px", border: "1px dashed var(--border-strong)", borderRadius: 12, marginTop: 4 }}>
          <div style={{ fontWeight: 600, marginBottom: 8, display: "flex", alignItems: "center", gap: 8 }}><Avatar color="#26A5E4" initials="TG" size={22} />Telegram — connect with a bot token</div>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
            <input placeholder="Bot token (from @BotFather)" value={tg.botToken} onChange={(e) => setTg({ ...tg, botToken: e.target.value })} style={inp} />
            <input placeholder="Channel @username or chat id" value={tg.chatId} onChange={(e) => setTg({ ...tg, chatId: e.target.value })} style={inp} />
            <Button size="sm" variant="primary" icon="check" disabled={!tg.botToken || !tg.chatId || busy === "telegram"} onClick={connectTelegram}>Connect</Button>
          </div>
        </div>
      </div>
    );
  }
  window.Channels = Channels;
})();
