// dashboard-people-workspace-phase-2.js — extracted verbatim from dashboard.js (pure move).

// ─── People Workspace (Phase 2) ──────────────────────────────────
// Tabs: Recommended (AI matches) — Requests (incoming) — Sent — Connections
// Mirrors the Telegram people-workspace surface, calling /api/people/* routes.

let peopleTab = "recommended";

async function renderPeople() {
  showLoading("Loading people…");

  const counts = await api("people-counts").catch((err) => ({ error: err.message }));
  if (counts?.error === "no_profile") {
    setContentNode(renderPeopleNoProfile(counts));
    return;
  }
  if (counts?.error) {
    showError(counts.error, renderPeople);
    return;
  }

  const tabs = el("div", { class: "tabs" }, [
    tabBtn(
      "recommended",
      `Recommended${counts.recommended ? ` (${fmtNum(counts.recommended)})` : ""}`,
      () => {
        peopleTab = "recommended";
        renderPeople();
      },
    ),
    tabBtn("requests", `Requests${counts.incoming ? ` (${counts.incoming})` : ""}`, () => {
      peopleTab = "requests";
      renderPeople();
    }),
    tabBtn("sent", `Sent${counts.sent ? ` (${counts.sent})` : ""}`, () => {
      peopleTab = "sent";
      renderPeople();
    }),
    tabBtn("connections", `Connections${counts.connected ? ` (${counts.connected})` : ""}`, () => {
      peopleTab = "connections";
      renderPeople();
    }),
  ]);

  setTimeout(() => {
    $$(".tab").forEach((t) =>
      t.classList.toggle("active", t.getAttribute("data-tab") === peopleTab),
    );
  }, 0);

  const content = el("div", {}, [
    el("div", { class: "page-header" }, [
      el("div", {}, [
        el("div", { class: "page-title" }, "People"),
        el(
          "div",
          { class: "page-subtitle" },
          "Registered Nexus members, AI-matched to your profile",
        ),
      ]),
      el("div", { style: "display: flex; gap: 8px;" }, [
        // Edit-my-profile shortcut — the matching engine ranks others against
        // YOUR profile, so an obvious "tune what others see about me" door
        // makes the loop tighter. Goes to the existing #profile editor.
        el(
          "button",
          {
            class: "btn btn-secondary",
            type: "button",
            title: "Edit your Nexus profile (drives how others match against you)",
            onclick: () => navigate("profile"),
          },
          "✎ Edit my profile",
        ),
        el(
          "button",
          { class: "btn btn-secondary", type: "button", onclick: renderPeople },
          "↻ Refresh",
        ),
      ]),
    ]),
    tabs,
    el("div", { id: "people-body" }, [el("div", { class: "loading" }, "Loading…")]),
  ]);
  setContentNode(content);

  // Lazy-load the active tab's body
  let body;
  if (peopleTab === "recommended") body = await renderPeopleRecommended();
  else if (peopleTab === "requests") body = await renderPeopleRequests();
  else if (peopleTab === "sent") body = await renderPeopleSent();
  else body = await renderPeopleConnections();

  const slot = $("#people-body");
  if (slot) {
    slot.innerHTML = "";
    slot.appendChild(body);
  }
}

function renderPeopleNoProfile(err) {
  return el("div", {}, [
    el("div", { class: "page-header" }, [
      el("div", {}, [el("div", { class: "page-title" }, "People")]),
    ]),
    el("div", { class: "empty-state" }, [
      el("div", { class: "empty-state-icon" }, "👋"),
      el("div", { class: "empty-state-title" }, "Tell the network who you are"),
      el(
        "div",
        { class: "empty-state-hint" },
        err?.message ||
          "Open Telegram and run /intro to register your profile, then come back here to discover matches.",
      ),
      el("div", { style: "display: flex; gap: 8px; justify-content: center; margin-top: 16px;" }, [
        el(
          "button",
          {
            class: "btn btn-primary",
            type: "button",
            onclick: () => openTgCommand("/intro"),
          },
          "Open /intro in Telegram",
        ),
        el(
          "button",
          {
            class: "btn btn-secondary",
            type: "button",
            onclick: () => navigate("home"),
          },
          "← Home",
        ),
      ]),
    ]),
  ]);
}

function fmtSkillTags(items, limit = 4) {
  if (!Array.isArray(items) || items.length === 0) return null;
  const visible = items.slice(0, limit);
  const overflow = items.length - visible.length;
  return el("div", { class: "filter-pills", style: "margin-top: 6px;" }, [
    ...visible.map((s) => el("div", { class: "filter-pill" }, [String(s)])),
    overflow > 0
      ? el("div", { class: "filter-pill", style: "opacity: 0.6;" }, `+${overflow}`)
      : null,
  ]);
}

function renderPeopleCard(p, actions) {
  return el(
    "div",
    {
      class: "card",
      style: "padding: 14px; margin-bottom: 8px; cursor: pointer;",
      onclick: (ev) => {
        // Don't open detail if a button was clicked
        if (ev.target.closest("button")) return;
        openPeopleDetail(p.profileId);
      },
    },
    [
      el("div", { style: "display: flex; gap: 12px; align-items: flex-start;" }, [
        // Avatar bubble
        el(
          "div",
          {
            style:
              "width: 36px; height: 36px; border-radius: 50%; background: var(--accent-soft); color: var(--accent); font-weight: 700; display: flex; align-items: center; justify-content: center; flex-shrink: 0; font-size: 14px;",
          },
          (p.displayName || "?").slice(0, 2).toUpperCase(),
        ),
        // Body
        el("div", { style: "flex: 1; min-width: 0;" }, [
          el("div", { class: "primary-cell", style: "font-size: 14px;" }, [
            p.displayName || "—",
            p.username
              ? el("span", { class: "muted small", style: "margin-left: 8px;" }, `@${p.username}`)
              : null,
          ]),
          el(
            "div",
            { class: "muted", style: "font-size: 12px; margin-top: 2px;" },
            [p.role, p.company].filter(Boolean).join(" @ ") || p.sector || "—",
          ),
          p.bio
            ? el(
                "div",
                { class: "muted", style: "font-size: 12px; margin-top: 6px; line-height: 1.5;" },
                p.bio,
              )
            : null,
          fmtSkillTags(p.offers, 3),
          p.aiReason
            ? el(
                "div",
                { class: "muted", style: "font-size: 11px; margin-top: 6px; font-style: italic;" },
                `🧠 ${p.aiReason}`,
              )
            : null,
        ]),
        // Score + actions
        el(
          "div",
          {
            style:
              "flex-shrink: 0; display: flex; flex-direction: column; align-items: flex-end; gap: 6px;",
          },
          [
            p.score != null
              ? el(
                  "div",
                  { class: "muted small", style: "font-family: var(--font-mono);" },
                  `score ${Number(p.score).toFixed(1)}`,
                )
              : null,
            el("div", { style: "display: flex; gap: 4px;" }, actions),
          ],
        ),
      ]),
    ],
  );
}

async function renderPeopleRecommended() {
  const data = await api("people-recommended").catch((err) => ({ error: err.message }));
  if (data?.error) return el("div", { class: "muted" }, `Error: ${data.error}`);
  const profiles = data.profiles || [];
  if (!profiles.length) {
    return el("div", { class: "empty-state", style: "padding: 32px;" }, [
      el("div", { class: "empty-state-icon" }, "🎯"),
      el("div", { class: "empty-state-title" }, "Queue is empty"),
      el(
        "div",
        { class: "empty-state-hint" },
        [
          "The matcher couldn't find any candidates above the relevance threshold. ",
          data.rebuilt
            ? "We just rebuilt the queue and still found nothing — likely because no other registered profiles match your sector/role/skills, or you've already passed/connected with everyone."
            : "Try forcing a rebuild — first-time users sometimes need this once.",
        ].join(""),
      ),
      el("div", { style: "display: flex; gap: 8px; justify-content: center; margin-top: 16px;" }, [
        el(
          "button",
          {
            class: "btn btn-primary",
            type: "button",
            onclick: async (ev) => {
              await withProgress(ev.currentTarget, async () => {
                const r = await api("people-recommended", { queryString: "?refresh=1" });
                if (r?.error) toast(r.error, "err");
                else {
                  toast(r.rebuilt ? "Queue rebuilt" : "Refreshed", "ok");
                  renderPeople();
                }
              });
            },
          },
          "↻ Rebuild queue",
        ),
        el(
          "button",
          {
            class: "btn btn-secondary",
            type: "button",
            onclick: () => openTgCommand("/discover"),
          },
          "Open /discover in Telegram",
        ),
      ]),
    ]);
  }

  return el(
    "div",
    {},
    profiles.map((p) =>
      renderPeopleCard(p, [
        el(
          "button",
          {
            class: "btn btn-tiny btn-primary",
            type: "button",
            onclick: async (ev) => {
              await withProgress(ev.currentTarget, async () => {
                const r = await api("people-connect", {
                  profileId: p.profileId,
                  body: {
                    reason: "Connect from extension",
                    score: p.score,
                    matchType: p.matchType || "manual",
                  },
                });
                if (r?.error) toast(r.error, "err");
                else {
                  toast("Request sent", "ok");
                  renderPeople();
                }
              });
            },
          },
          "Connect",
        ),
        el(
          "button",
          {
            class: "btn btn-tiny btn-secondary",
            type: "button",
            onclick: async (ev) => {
              await withProgress(ev.currentTarget, async () => {
                const r = await api("people-pass", { profileId: p.profileId });
                if (r?.error) toast(r.error, "err");
                else renderPeople();
              });
            },
          },
          "Pass",
        ),
      ]),
    ),
  );
}

async function renderPeopleRequests() {
  const data = await api("people-requests").catch((err) => ({ error: err.message }));
  if (data?.error) return el("div", { class: "muted" }, `Error: ${data.error}`);
  const requests = data.requests || [];
  if (!requests.length) {
    return el("div", { class: "empty-state", style: "padding: 32px;" }, [
      el("div", { class: "empty-state-icon" }, "📥"),
      el("div", { class: "empty-state-title" }, "No incoming requests"),
      el(
        "div",
        { class: "empty-state-hint" },
        "When someone wants to connect, their request will show up here.",
      ),
    ]);
  }

  return el(
    "div",
    {},
    requests.map((r) => {
      const card = renderPeopleCard(r.sender, [
        el(
          "button",
          {
            class: "btn btn-tiny btn-primary",
            type: "button",
            onclick: async (ev) => {
              await withProgress(ev.currentTarget, async () => {
                const resp = await api("people-request-accept", { requestId: r.requestId });
                if (resp?.error) toast(resp.error, "err");
                else {
                  toast("Accepted", "ok");
                  renderPeople();
                }
              });
            },
          },
          "Accept",
        ),
        el(
          "button",
          {
            class: "btn btn-tiny btn-secondary",
            type: "button",
            onclick: async (ev) => {
              await withProgress(ev.currentTarget, async () => {
                const resp = await api("people-request-decline", { requestId: r.requestId });
                if (resp?.error) toast(resp.error, "err");
                else {
                  toast("Declined", "ok");
                  renderPeople();
                }
              });
            },
          },
          "Decline",
        ),
      ]);
      if (r.reason) {
        card.appendChild(
          el(
            "div",
            {
              class: "muted",
              style:
                "font-size: 12px; margin-top: 8px; padding-top: 8px; border-top: 1px solid var(--border); font-style: italic;",
            },
            `"${r.reason}"`,
          ),
        );
      }
      return card;
    }),
  );
}

async function renderPeopleSent() {
  const data = await api("people-sent").catch((err) => ({ error: err.message }));
  if (data?.error) return el("div", { class: "muted" }, `Error: ${data.error}`);
  const sent = data.sent || [];
  if (!sent.length) {
    return el("div", { class: "empty-state", style: "padding: 32px;" }, [
      el("div", { class: "empty-state-icon" }, "📤"),
      el("div", { class: "empty-state-title" }, "No sent requests"),
      el("div", { class: "empty-state-hint" }, "Connect from Recommended to start a request."),
    ]);
  }

  return el(
    "div",
    {},
    sent.map((r) => {
      const statusBadge =
        {
          pending: el("span", { class: "badge badge-yellow" }, "Pending"),
          accepted: el("span", { class: "badge badge-green" }, "Accepted"),
          declined: el("span", { class: "badge badge-gray" }, "Declined"),
        }[r.status] || el("span", { class: "badge badge-gray" }, r.status);

      return el(
        "div",
        {
          class: "card",
          style: "padding: 14px; margin-bottom: 8px; cursor: pointer;",
          onclick: () => openPeopleDetail(r.receiver.profileId),
        },
        [
          el("div", { style: "display: flex; align-items: center; gap: 12px;" }, [
            el("div", { style: "flex: 1;" }, [
              el("div", { class: "primary-cell" }, r.receiver.displayName || "—"),
              el(
                "div",
                { class: "muted", style: "font-size: 12px;" },
                [r.receiver.role, r.receiver.company].filter(Boolean).join(" @ ") ||
                  (r.receiver.username ? `@${r.receiver.username}` : "—"),
              ),
              el(
                "div",
                { class: "muted small", style: "margin-top: 4px;" },
                `Sent ${fmtDate(r.createdAt)}`,
              ),
            ]),
            statusBadge,
          ]),
        ],
      );
    }),
  );
}

async function renderPeopleConnections() {
  const data = await api("people-connections").catch((err) => ({ error: err.message }));
  if (data?.error) return el("div", { class: "muted" }, `Error: ${data.error}`);
  const connections = data.connections || [];
  if (!connections.length) {
    return el("div", { class: "empty-state", style: "padding: 32px;" }, [
      el("div", { class: "empty-state-icon" }, "🤝"),
      el("div", { class: "empty-state-title" }, "No accepted connections yet"),
      el(
        "div",
        { class: "empty-state-hint" },
        "Once a request is accepted (by you or them), the connection lands here.",
      ),
    ]);
  }

  return el(
    "div",
    {},
    connections.map((c) =>
      el(
        "div",
        {
          class: "card",
          style: "padding: 14px; margin-bottom: 8px; cursor: pointer;",
          onclick: () => openPeopleDetail(c.other.profileId),
        },
        [
          el("div", { style: "display: flex; align-items: center; gap: 12px;" }, [
            el(
              "div",
              {
                style:
                  "width: 32px; height: 32px; border-radius: 50%; background: var(--accent-soft); color: var(--accent); display: flex; align-items: center; justify-content: center; font-weight: 700; flex-shrink: 0;",
              },
              (c.other.displayName || "?").slice(0, 2).toUpperCase(),
            ),
            el("div", { style: "flex: 1;" }, [
              el("div", { class: "primary-cell" }, c.other.displayName || "—"),
              el(
                "div",
                { class: "muted", style: "font-size: 12px;" },
                [c.other.role, c.other.company].filter(Boolean).join(" @ ") ||
                  (c.other.username ? `@${c.other.username}` : "—"),
              ),
            ]),
            el("div", { class: "muted small" }, `connected ${fmtDate(c.acceptedAt)}`),
            c.other.username
              ? el(
                  "button",
                  {
                    class: "btn btn-tiny btn-secondary",
                    type: "button",
                    onclick: (ev) => {
                      ev.stopPropagation();
                      chrome.tabs.create({ url: `https://t.me/${c.other.username}` });
                    },
                  },
                  "💬 Chat",
                )
              : null,
          ]),
        ],
      ),
    ),
  );
}

async function openPeopleDetail(profileId) {
  openDrawer("Profile", el("div", { class: "loading" }, "Loading…"));
  const data = await api("people-detail", { profileId }).catch((err) => ({ error: err.message }));
  if (data?.error) {
    openDrawer("Profile", el("div", { class: "muted" }, `Error: ${data.error}`));
    return;
  }
  const p = data.profile || {};
  const rel = data.relationship;
  const communities = data.communities || [];

  const body = el("div", { class: "drawer-body" }, [
    el("div", { style: "display: flex; gap: 12px; align-items: center; margin-bottom: 16px;" }, [
      el(
        "div",
        {
          style:
            "width: 48px; height: 48px; border-radius: 50%; background: var(--accent-soft); color: var(--accent); display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 18px;",
        },
        (p.displayName || "?").slice(0, 2).toUpperCase(),
      ),
      el("div", {}, [
        el("div", { style: "font-size: 16px; font-weight: 600;" }, p.displayName || "—"),
        p.username ? el("div", { class: "muted small" }, `@${p.username}`) : null,
      ]),
    ]),

    p.bio
      ? el("div", { class: "card", style: "margin-bottom: 12px;" }, [
          el("div", { class: "card-title" }, "Bio"),
          el("div", { class: "muted", style: "font-size: 13px; line-height: 1.6;" }, p.bio),
        ])
      : null,

    el("div", { class: "card", style: "margin-bottom: 12px;" }, [
      el("div", { class: "card-title" }, "Profile"),
      ...[
        ["Role", p.role],
        ["Company", p.company],
        ["Sector", p.sector],
      ]
        .filter(([, v]) => v)
        .map(([k, v]) =>
          el("div", { class: "field-row" }, [
            el("span", { class: "field-label" }, k),
            el("span", { class: "field-value" }, v),
          ]),
        ),
      p.linkedinUrl
        ? el("div", { class: "field-row" }, [
            el("span", { class: "field-label" }, "LinkedIn"),
            el("a", { class: "field-value", href: p.linkedinUrl, target: "_blank" }, "open ↗"),
          ])
        : null,
      p.twitterHandle
        ? el("div", { class: "field-row" }, [
            el("span", { class: "field-label" }, "X / Twitter"),
            el(
              "a",
              {
                class: "field-value",
                href: `https://x.com/${p.twitterHandle.replace(/^@/, "")}`,
                target: "_blank",
              },
              `@${p.twitterHandle}`,
            ),
          ])
        : null,
    ]),

    (p.offers || []).length
      ? el("div", { class: "card", style: "margin-bottom: 12px;" }, [
          el("div", { class: "card-title" }, "Offers"),
          el(
            "div",
            { class: "filter-pills" },
            p.offers.map((s) => el("div", { class: "filter-pill" }, [s])),
          ),
        ])
      : null,

    (p.needs || []).length
      ? el("div", { class: "card", style: "margin-bottom: 12px;" }, [
          el("div", { class: "card-title" }, "Needs"),
          el(
            "div",
            { class: "filter-pills" },
            p.needs.map((s) => el("div", { class: "filter-pill" }, [s])),
          ),
        ])
      : null,

    (p.skills || []).length
      ? el("div", { class: "card", style: "margin-bottom: 12px;" }, [
          el("div", { class: "card-title" }, "Skills"),
          el(
            "div",
            { class: "filter-pills" },
            p.skills.map((s) => el("div", { class: "filter-pill" }, [s])),
          ),
        ])
      : null,

    communities.length
      ? el("div", { class: "card", style: "margin-bottom: 12px;" }, [
          el("div", { class: "card-title" }, `Communities (${communities.length})`),
          el(
            "div",
            {},
            communities.map((c) =>
              el(
                "div",
                { class: "muted", style: "font-size: 12px; padding: 4px 0;" },
                c.name || (c.handle ? `@${c.handle}` : `community ${c.id}`),
              ),
            ),
          ),
        ])
      : null,

    // Action bar
    el("div", { style: "display: flex; gap: 8px; flex-wrap: wrap; margin-top: 16px;" }, [
      rel && rel.status === "pending" && rel.sentByMe
        ? el("span", { class: "badge badge-yellow" }, "Request pending")
        : rel && rel.status === "accepted"
          ? el("span", { class: "badge badge-green" }, "Connected")
          : rel && rel.status === "pending" && !rel.sentByMe
            ? el(
                "button",
                {
                  class: "btn btn-tiny btn-primary",
                  type: "button",
                  onclick: async () => {
                    const r = await api("people-request-accept", { requestId: rel.requestId });
                    if (r?.error) toast(r.error, "err");
                    else {
                      toast("Accepted", "ok");
                      closeDrawer();
                      renderPeople();
                    }
                  },
                },
                "Accept request",
              )
            : el(
                "button",
                {
                  class: "btn btn-tiny btn-primary",
                  type: "button",
                  onclick: async () => {
                    const r = await api("people-connect", {
                      profileId: p.profileId,
                      body: { reason: "Connect from extension" },
                    });
                    if (r?.error) toast(r.error, "err");
                    else {
                      toast("Request sent", "ok");
                      closeDrawer();
                      renderPeople();
                    }
                  },
                },
                "Connect",
              ),
      el(
        "button",
        {
          class: "btn btn-tiny btn-secondary",
          type: "button",
          onclick: async () => {
            const action = data.bookmarked ? "people-bookmark-remove" : "people-bookmark-add";
            const r = await api(action, { profileId: p.profileId });
            if (r?.error) toast(r.error, "err");
            else {
              toast(data.bookmarked ? "Unbookmarked" : "Bookmarked", "ok");
              openPeopleDetail(profileId);
            }
          },
        },
        data.bookmarked ? "★ Bookmarked" : "☆ Bookmark",
      ),
      el(
        "button",
        {
          class: "btn btn-tiny btn-danger",
          type: "button",
          onclick: async () => {
            if (!confirm("Block this user? They won't be able to message you.")) return;
            const r = await api("people-block", { profileId: p.profileId });
            if (r?.error) toast(r.error, "err");
            else {
              toast("Blocked", "ok");
              closeDrawer();
              renderPeople();
            }
          },
        },
        "Block",
      ),
    ]),
  ]);
  openDrawer(p.displayName || "Profile", body);
}
