/* =========================================================================
   Live ICP Tracker — External partner view (Partner Portal)
   Faithful port of the Malachyte Partner Portal design.
   Partners never see ICP scores, spend, owners, or win-plan internals.
   Exports: ExternalView
   ========================================================================= */
const { useState: useStateE, useEffect: useEffectE, useMemo: useMemoE } = React;

/* ---- live-data helpers -------------------------------------------------- */
// Relative timestamp from an epoch-ms value.
function extTimeAgo(ts) {
  if (!ts) return "";
  const s = Math.floor((Date.now() - ts) / 1000);
  if (s < 60) return "just now";
  const m = Math.floor(s / 60); if (m < 60) return m + (m === 1 ? " min ago" : " mins ago");
  const h = Math.floor(m / 60); if (h < 24) return h + (h === 1 ? " hour ago" : " hours ago");
  const d = Math.floor(h / 24); if (d < 7) return d + (d === 1 ? " day ago" : " days ago");
  const w = Math.floor(d / 7); return w + (w === 1 ? " week ago" : " weeks ago");
}

// Build a lookup of account-id -> { name, domain } from the loaded ICP data.
function extAccountIndex() {
  const idx = {};
  const accts = (window.ICP && window.ICP.ACCOUNTS) || [];
  accts.forEach(a => { if (a && a.id != null) idx[String(a.id)] = a; });
  return idx;
}

const EXT_PALETTE = ["#038362", "#4B4E87", "#D89251", "#A7A0EB", "#C14545"];
function extColor(s) {
  let h = 5381;
  for (let i = 0; i < s.length; i++) h = ((h << 5) + h) + s.charCodeAt(i);
  return EXT_PALETTE[Math.abs(h) % EXT_PALETTE.length];
}

// Company logo (from the account card in Supabase/ICP data) with a colored
// letter tile as fallback when the logo is missing or fails to load.
function CompanyLogo({ name, logo, size, radius }) {
  const [failed, setFailed] = useStateE(false);
  const color = extColor(name || "?");
  const tile = {
    width: size, height: size, borderRadius: radius, flexShrink: 0,
    display: "grid", placeItems: "center", letterSpacing: "-0.01em",
    fontSize: Math.round(size * 0.4), fontWeight: 700,
    background: color + "1A", color,
  };
  if (logo && !failed) {
    return (
      <img
        src={logo}
        alt={name + " logo"}
        onError={() => setFailed(true)}
        style={{ width: size, height: size, borderRadius: radius, objectFit: "contain", flexShrink: 0, background: "#fff", border: "1px solid #EFEAE1" }}
      />
    );
  }
  return <div style={tile}>{(name || "?")[0]}</div>;
}

function ExternalView() {
  const [tab, setTab] = useStateE("intros");
  const [warmths, setWarmths] = useStateE({});
  const [claimed, setClaimed] = useStateE({});
  const [expanded, setExpanded] = useStateE({});
  const [drafts, setDrafts] = useStateE({});
  const [replies, setReplies] = useStateE({});
  const [companyWarmths, setCompanyWarmths] = useStateE({}); // "listId::company" -> "hot"|"warm"|"cold"
  const [companyNotes, setCompanyNotes] = useStateE({});     // "listId::company" -> note text

  /* ---- live data from Supabase (via /api/referrals) ---- */
  const [referrals, setReferrals] = useStateE([]);
  const [listMembers, setListMembers] = useStateE({}); // listId -> [accountId]
  const [loaded, setLoaded] = useStateE(false);

  useEffectE(() => {
    let live = true;
    Promise.all([
      fetch("/api/referrals").then(r => r.json()).catch(() => ({ referrals: [] })),
      fetch("/api/saved-lists").then(r => r.json()).catch(() => ({ lists: [] })),
    ]).then(([ref, sl]) => {
      if (!live) return;
      setReferrals(ref.referrals || []);
      const map = {};
      (sl.lists || []).forEach(l => { map[l.id] = l.accountIds || []; });
      setListMembers(map);
      setLoaded(true);
    }).catch(e => { console.log("[v0] external load failed:", e && e.message); if (live) setLoaded(true); });
    return () => { live = false; };
  }, []);

  // Split + shape referrals into the intro/list card models.
  const acctIdx = useMemoE(() => extAccountIndex(), [loaded]);
  const acctName = a => (a && (a.brand || a.name)) || null;
  const introItems = useMemoE(() => referrals
    .filter(r => r.kind === "account")
    .map(r => {
      const acct = r.accountId != null ? acctIdx[String(r.accountId)] : null;
      const company = r.accountName || acctName(acct) || "Account";
      return {
        id: r.id,
        company,
        domain: (acct && acct.domain) || "",
        logo: (acct && acct.logo) || "",
        postedAt: extTimeAgo(r.createdAt),
        reason: r.description || "We're actively targeting this account — a warm intro is the fastest path in.",
        initialReplies: [],
      };
    }), [referrals, acctIdx]);

  const listItems = useMemoE(() => referrals
    .filter(r => r.kind === "list")
    .map(r => {
      const ids = listMembers[r.listId] || [];
      const companies = ids
        .map(id => { const a = acctIdx[String(id)]; return a ? { name: acctName(a), logo: a.logo || "" } : null; })
        .filter(c => c && c.name);
      const count = companies.length || r.accountCount || 0;
      return {
        id: r.id,
        title: r.listName || "Saved list",
        postedAt: extTimeAgo(r.createdAt),
        description: r.description || "A curated list of target accounts we'd love warm intros to.",
        companies,
        accountCount: count,
        initialReplies: [],
      };
    }), [referrals, listMembers, acctIdx]);

  const introCount = introItems.length;
  const listCount = listItems.length;

  const getReplies = (id, initial) => (replies[id] !== undefined ? replies[id] : initial);
  const toggleThread = id => setExpanded(s => ({ ...s, [id]: !s[id] }));
  const setDraft = (id, v) => setDrafts(s => ({ ...s, [id]: v }));
  const submitReply = (id, initial) => {
    const txt = (drafts[id] || "").trim();
    if (!txt) return;
    const nr = { id: Date.now(), author: "Sarah Chen", initials: "SC", time: "just now", text: txt, claimed: false };
    setReplies(s => {
      const base = s[id] !== undefined ? s[id] : initial;
      return { ...s, [id]: [...base, nr] };
    });
    setDrafts(s => ({ ...s, [id]: "" }));
    setExpanded(s => ({ ...s, [id]: true }));
  };

  const avatarStyle = (author, sz = 30, fs = 11) => ({
    width: sz, height: sz, borderRadius: "50%", background: extColor(author), color: "#fff",
    display: "grid", placeItems: "center", fontSize: fs, fontWeight: 600, flexShrink: 0, letterSpacing: "0.02em",
  });

  /* ---- warmth selector styles ---- */
  const baseBtn = { display: "inline-flex", alignItems: "center", gap: 7, borderRadius: 9999, fontFamily: "'Manrope', sans-serif", fontWeight: 500, cursor: "pointer", border: "1px solid", transition: "all 140ms", fontSize: 13, padding: "7px 16px", letterSpacing: "-0.005em" };
  const defBtn = { ...baseBtn, background: "transparent", color: "#8A9399", borderColor: "#E6E2DB" };
  const selHot = { ...baseBtn, background: "#D84040", color: "#fff", borderColor: "#D84040" };
  const selWarm = { ...baseBtn, background: "#038362", color: "#fff", borderColor: "#038362" };
  const selNo = { ...baseBtn, background: "#606B70", color: "#fff", borderColor: "#606B70" };
  const selCold = { ...baseBtn, background: "#4B6A8A", color: "#fff", borderColor: "#4B6A8A" };
  const dot = (clr, sel) => ({ display: "inline-block", width: 7, height: 7, borderRadius: "50%", background: sel ? "#fff" : clr, flexShrink: 0, border: sel ? "none" : "1.5px solid " + clr });

  const setWarmth = (id, level) => setWarmths(s => ({ ...s, [id]: s[id] === level ? null : level }));
  const claim = id => { setClaimed(s => ({ ...s, [id]: true })); setExpanded(s => ({ ...s, [id]: true })); };

  // Per-company warmth + optional note inside a list posting.
  const cwKey = (listId, company) => listId + "::" + company;
  const setCompanyWarmth = (listId, company, level) =>
    setCompanyWarmths(s => { const k = cwKey(listId, company); return { ...s, [k]: s[k] === level ? null : level }; });
  const setCompanyNote = (listId, company, val) =>
    setCompanyNotes(s => ({ ...s, [cwKey(listId, company)]: val }));

  const tabStyle = active => ({
    background: active ? "#038362" : "transparent",
    border: "1px solid", borderColor: active ? "#038362" : "rgba(250,253,249,0.18)",
    color: active ? "#fff" : "rgba(250,253,249,0.6)",
    fontFamily: "'Manrope', sans-serif", fontSize: 13, fontWeight: active ? 500 : 400,
    padding: "7px 16px", borderRadius: 9999, cursor: "pointer", transition: "all 140ms",
  });

  const card = { background: "#FFFFFF", border: "1px solid #E6E2DB", borderRadius: 16, overflow: "hidden", boxShadow: "0 1px 3px rgba(6,23,31,0.04)" };

  return (
    <div style={{ fontFamily: "'Manrope', sans-serif", background: "#FAF6F0", color: "#06171F", minHeight: "100vh", WebkitFontSmoothing: "antialiased" }}>
      {/* ── Top navbar ── */}
      <div style={{ position: "sticky", top: 0, zIndex: 100, background: "#FDFBF7", borderBottom: "1px solid #F0EBE6", padding: "0 32px", height: 56, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <img src="assets/malachyte-logo-gradient.png" style={{ height: 20, width: "auto", display: "block" }} alt="Malachyte" onError={e => { e.target.style.display = "none"; }} />
          <div style={{ width: 1, height: 18, background: "#E6E2DB" }}></div>
          <span style={{ fontSize: 12, fontWeight: 500, color: "#8A9399", letterSpacing: "0.01em" }}>Partner Portal</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 9, background: "rgba(3,131,98,0.06)", border: "1px solid rgba(3,131,98,0.12)", borderRadius: 9999, padding: "6px 14px 6px 8px" }}>
          <img src="assets/malachyte-symbol-gradient.png" alt="Malachyte" style={{ width: 28, height: 28, borderRadius: "50%", objectFit: "cover", flexShrink: 0, background: "#FAFDF9" }} />
          <div>
            <div style={{ fontSize: 12, fontWeight: 500, color: "#06171F", lineHeight: 1.2 }}>Malachyte Team Account</div>
            <div style={{ fontSize: 11, color: "#8A9399", lineHeight: 1.2 }}>GTM · external</div>
          </div>
        </div>
      </div>

      {/* ── Hero band ── */}
      <div style={{ background: "#06171F", position: "relative", overflow: "hidden", padding: "44px 32px 40px" }}>
        <div style={{ position: "absolute", right: -30, top: -80, width: 180, height: 340, borderRadius: "50%", background: "linear-gradient(135deg, #DAFED0 0%, #89C0A5 45%, #038362 100%)", transform: "rotate(-10deg)", opacity: 0.75, pointerEvents: "none" }}></div>
        <div style={{ position: "absolute", right: -100, top: -20, width: 210, height: 380, borderRadius: "50%", background: "linear-gradient(135deg, #DAFED0 0%, #C7BCE8 55%, #A7A0EB 100%)", transform: "rotate(-10deg)", opacity: 0.38, pointerEvents: "none" }}></div>
        <div style={{ position: "absolute", right: 140, top: -50, width: 120, height: 220, borderRadius: "50%", background: "linear-gradient(135deg, #DAFED0, #89C0A5)", transform: "rotate(-10deg)", opacity: 0.18, pointerEvents: "none" }}></div>
        <div style={{ position: "relative", zIndex: 1, maxWidth: 760, margin: "0 auto" }}>
          <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: "rgba(250,253,249,0.5)", marginBottom: 14 }}>Your partner brief</div>
          <h1 style={{ fontSize: 32, fontWeight: 500, color: "#FAFDF9", letterSpacing: "-0.02em", lineHeight: 1.15, margin: "0 0 10px", maxWidth: 480 }}>Help us open doors.</h1>
          <p style={{ fontSize: 14, color: "rgba(250,253,249,0.6)", lineHeight: 1.6, margin: "0 0 20px", maxWidth: 420 }}>Below are accounts we're actively targeting. If you have a connection — however loose — let us know. Your intro is the fastest path in.</p>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <div style={{ width: 6, height: 6, borderRadius: "50%", background: "#ADEF9B" }}></div>
            <span style={{ fontSize: 12, color: "rgba(250,253,249,0.55)" }}>Updated {new Date().toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })} · {introCount} intro {introCount === 1 ? "request" : "requests"} · {listCount} list {listCount === 1 ? "posting" : "postings"}</span>
          </div>
        </div>
      </div>

      {/* ── Tab bar ── */}
      <div style={{ background: "#0C1C24", borderBottom: "1px solid rgba(255,255,255,0.05)" }}>
        <div style={{ maxWidth: 760, margin: "0 auto", padding: "0 32px", display: "flex", gap: 4, alignItems: "center", height: 52 }}>
          <button onClick={() => setTab("intros")} style={tabStyle(tab === "intros")}>
            Intro requests
            <span style={{ display: "inline-block", background: "rgba(3,131,98,0.35)", color: "#ADEF9B", fontSize: 10, fontWeight: 600, padding: "1px 7px", borderRadius: 9999, marginLeft: 6, verticalAlign: "middle" }}>{introCount}</span>
          </button>
          <button onClick={() => setTab("lists")} style={tabStyle(tab === "lists")}>
            List postings
            <span style={{ display: "inline-block", background: "rgba(250,253,249,0.08)", color: "rgba(250,253,249,0.4)", fontSize: 10, fontWeight: 600, padding: "1px 7px", borderRadius: 9999, marginLeft: 6, verticalAlign: "middle" }}>{listCount}</span>
          </button>
        </div>
      </div>

      {/* ── Main content ── */}
      <div style={{ maxWidth: 760, margin: "0 auto", padding: "28px 32px 80px" }}>

        {/* ─ Intro requests tab ─ */}
        {tab === "intros" && (
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {!loaded ? (
              <div style={{ ...card, padding: "28px 20px", textAlign: "center", fontSize: 13, color: "#8A9399" }}>Loading intro requests…</div>
            ) : introItems.length === 0 ? (
              <div style={{ ...card, padding: "32px 20px", textAlign: "center" }}>
                <div style={{ fontSize: 15, fontWeight: 500, color: "#06171F", marginBottom: 4 }}>No open intro requests</div>
                <div style={{ fontSize: 13, color: "#8A9399", lineHeight: 1.6 }}>When the team requests an intro to a target account, it&apos;ll show up here.</div>
              </div>
            ) : introItems.map(item => {
              const color = extColor(item.company);
              const warmth = warmths[item.id] || null;
              const isClaimed = claimed[item.id] || false;
              const canClaim = (warmth === "hot" || warmth === "warm") && !isClaimed;
              const threadReplies = getReplies(item.id, item.initialReplies);
              const isExpanded = expanded[item.id] || false;
              const replyAvatars = threadReplies.slice(0, 3);
              return (
                <div key={item.id} style={card}>
                  {/* Company header */}
                  <div style={{ padding: "18px 20px 14px", display: "flex", gap: 14, alignItems: "flex-start" }}>
                    <CompanyLogo name={item.company} logo={item.logo} size={46} radius={13} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 16, fontWeight: 500, color: "#06171F", letterSpacing: "-0.015em" }}>{item.company}</div>
                      {item.domain && <div style={{ fontSize: 12, color: "#8A9399", marginTop: 3 }}>{item.domain}</div>}
                    </div>
                    <div style={{ display: "flex", alignItems: "center", gap: 8, flexShrink: 0 }}>
                      {isClaimed && <span style={{ fontSize: 11, padding: "4px 10px", background: "rgba(3,131,98,0.1)", color: "#038362", borderRadius: 9999, fontWeight: 500, whiteSpace: "nowrap" }}>✓ Claimed</span>}
                      <span style={{ fontSize: 11, color: "#C4BFB8" }}>{item.postedAt}</span>
                    </div>
                  </div>

                  {/* Why we want this intro */}
                  <div style={{ margin: "0 20px 16px", padding: "12px 14px", background: "rgba(218,254,208,0.28)", borderRadius: 10, borderLeft: "3px solid rgba(3,131,98,0.3)" }}>
                    <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: "0.08em", textTransform: "uppercase", color: "#038362", marginBottom: 5 }}>Why we want this intro</div>
                    <div style={{ fontSize: 13, color: "#2D5843", lineHeight: 1.65, textWrap: "pretty" }}>{item.reason}</div>
                  </div>

                  {/* Warmth selector */}
                  <div style={{ padding: "0 20px 14px" }}>
                    <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase", color: "#8A9399", marginBottom: 10 }}>Your connection</div>
                    <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                      <button onClick={() => setWarmth(item.id, "hot")} style={warmth === "hot" ? selHot : defBtn}>
                        <span style={dot("#D84040", warmth === "hot")}></span>
                        Hot — I can intro now
                      </button>
                      <button onClick={() => setWarmth(item.id, "warm")} style={warmth === "warm" ? selWarm : defBtn}>
                        <span style={dot("#038362", warmth === "warm")}></span>
                        Warm — I know someone
                      </button>
                      <button onClick={() => setWarmth(item.id, "no")} style={warmth === "no" ? selNo : defBtn}>No connection</button>
                    </div>
                  </div>

                  {/* Claim CTA */}
                  {canClaim && (
                    <div style={{ padding: "0 20px 16px", animation: "slideIn 160ms ease forwards" }}>
                      <button onClick={() => claim(item.id)} style={{ width: "100%", padding: "11px 20px", background: "#038362", color: "#fff", border: "none", borderRadius: 9999, fontSize: 14, fontWeight: 500, cursor: "pointer", letterSpacing: "-0.008em", transition: "background 120ms" }}>Claim this intro →</button>
                    </div>
                  )}

                  {/* Thread row */}
                  <div style={{ borderTop: "1px solid #F0ECEC" }}>
                    <button onClick={() => toggleThread(item.id)} style={{ width: "100%", padding: "11px 20px", background: "#FAFDF9", border: "none", display: "flex", alignItems: "center", gap: 7, cursor: "pointer", textAlign: "left", transition: "background 120ms" }}>
                      {threadReplies.length > 0 && (
                        <>
                          <div style={{ display: "flex", marginRight: 4 }}>
                            {replyAvatars.map((av, i) => (
                              <div key={av.id} style={{ width: 20, height: 20, borderRadius: "50%", background: extColor(av.author), color: "#fff", display: "grid", placeItems: "center", fontSize: 8, fontWeight: 600, border: "2px solid #FAFDF9", marginLeft: i > 0 ? -6 : 0, zIndex: 3 - i, position: "relative" }}>{av.initials}</div>
                            ))}
                          </div>
                          <span style={{ fontSize: 12, fontWeight: 500, color: "#606B70" }}>{threadReplies.length} {threadReplies.length === 1 ? "reply" : "replies"}</span>
                          <span style={{ color: "#D4CFC5", fontSize: 12 }}>·</span>
                        </>
                      )}
                      <span style={{ fontSize: 12, fontWeight: 500, color: "#038362" }}>+ Reply</span>
                      <span style={{ marginLeft: "auto", fontSize: 11, color: "#C4BFB8" }}>{isExpanded ? "▲" : "▼"}</span>
                    </button>
                  </div>

                  {/* Thread content */}
                  {isExpanded && (
                    <div style={{ background: "#FAFDF9", borderTop: "1px solid #F0ECEC", padding: "16px 20px", display: "flex", flexDirection: "column", gap: 14, animation: "slideIn 180ms ease forwards" }}>
                      {threadReplies.map(reply => (
                        <div key={reply.id} style={{ display: "flex", gap: 12 }}>
                          <div style={avatarStyle(reply.author)}>{reply.initials}</div>
                          <div style={{ flex: 1, background: "#fff", border: "1px solid #EFEAE1", borderRadius: 12, padding: "12px 14px" }}>
                            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6, flexWrap: "wrap" }}>
                              <span style={{ fontSize: 13, fontWeight: 500, color: "#06171F" }}>{reply.author}</span>
                              <span style={{ fontSize: 11, color: "#C4BFB8" }}>{reply.time}</span>
                              {reply.claimed && <span style={{ fontSize: 10, padding: "2px 8px", borderRadius: 9999, background: "rgba(3,131,98,0.1)", color: "#038362", fontWeight: 500 }}>✓ Claimed intro</span>}
                            </div>
                            <div style={{ fontSize: 13, color: "#606B70", lineHeight: 1.6 }}>{reply.text}</div>
                          </div>
                        </div>
                      ))}
                      {/* Reply compose */}
                      <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
                        <div style={{ width: 30, height: 30, borderRadius: "50%", background: "#038362", color: "#FAFDF9", display: "grid", placeItems: "center", fontSize: 11, fontWeight: 600, flexShrink: 0, marginTop: 2 }}>SC</div>
                        <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 8 }}>
                          <textarea value={drafts[item.id] || ""} onChange={e => setDraft(item.id, e.target.value)} placeholder="Who do you know? Any context helps..." rows={2} style={{ width: "100%", padding: "10px 14px", fontSize: 13, border: "1px solid #E6E2DB", borderRadius: 12, outline: "none", resize: "none", background: "#fff", color: "#06171F", lineHeight: 1.55, fontFamily: "'Manrope', sans-serif" }} />
                          <div style={{ display: "flex", justifyContent: "flex-end" }}>
                            <button onClick={() => submitReply(item.id, item.initialReplies)} style={{ padding: "7px 18px", background: "#038362", color: "#fff", border: "none", borderRadius: 9999, fontSize: 13, fontWeight: 500, cursor: "pointer" }}>Send reply</button>
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}

        {/* ─ List postings tab ─ */}
        {tab === "lists" && (
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <p style={{ fontSize: 13, color: "#8A9399", lineHeight: 1.6, margin: "0 0 4px", textWrap: "pretty" }}>Curated lists of target accounts. Expand a list and mark how warm your connection is to each company — add a note if you can help with an intro.</p>
            {!loaded ? (
              <div style={{ ...card, padding: "28px 20px", textAlign: "center", fontSize: 13, color: "#8A9399" }}>Loading list postings…</div>
            ) : listItems.length === 0 ? (
              <div style={{ ...card, padding: "32px 20px", textAlign: "center" }}>
                <div style={{ fontSize: 15, fontWeight: 500, color: "#06171F", marginBottom: 4 }}>No list postings yet</div>
                <div style={{ fontSize: 13, color: "#8A9399", lineHeight: 1.6 }}>When the team posts a saved target list to referrals, it&apos;ll appear here.</div>
              </div>
            ) : listItems.map(list => {
              const threadReplies = getReplies(list.id, list.initialReplies);
              const isExpanded = expanded[list.id] || false;
              const companyCount = list.companies.length || list.accountCount;
              return (
                <div key={list.id} style={card}>
                  {/* List header */}
                  <div style={{ padding: "18px 20px 14px" }}>
                    <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12 }}>
                      <div>
                        <div style={{ fontSize: 16, fontWeight: 500, color: "#06171F", letterSpacing: "-0.015em" }}>{list.title}</div>
                        <div style={{ fontSize: 12, color: "#8A9399", marginTop: 3 }}>Posted {list.postedAt} · {companyCount} {companyCount === 1 ? "company" : "companies"}</div>
                      </div>
                      <div style={{ background: "rgba(3,131,98,0.08)", color: "#038362", fontSize: 11, fontWeight: 600, padding: "4px 10px", borderRadius: 9999, whiteSpace: "nowrap", flexShrink: 0, border: "1px solid rgba(3,131,98,0.12)" }}>{companyCount} {companyCount === 1 ? "company" : "companies"}</div>
                    </div>
                    <p style={{ fontSize: 13, color: "#606B70", lineHeight: 1.6, margin: "12px 0 0", textWrap: "pretty" }}>{list.description}</p>
                  </div>

                  {/* Full company list — warmth + optional note per company */}
                  {list.companies.length > 0 ? (
                    <div style={{ padding: "0 20px 16px", display: "flex", flexDirection: "column", gap: 10 }}>
                      <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase", color: "#8A9399" }}>Companies in this list</div>
                      {list.companies.map((co, i) => {
                        const coName = co.name;
                        const k = cwKey(list.id, coName);
                        const cw = companyWarmths[k] || null;
                        const note = companyNotes[k] || "";
                        const noteOpen = cw === "hot" || cw === "warm";
                        return (
                          <div key={coName + i} style={{ border: "1px solid #EFEAE1", borderRadius: 12, padding: "12px 14px", background: "#FCFBF8" }}>
                            <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
                              <CompanyLogo name={coName} logo={co.logo} size={30} radius={8} />
                              <div style={{ fontSize: 14, fontWeight: 500, color: "#06171F", flex: 1, minWidth: 0 }}>{coName}</div>
                            </div>
                            <div style={{ display: "flex", gap: 7, flexWrap: "wrap", marginTop: 11 }}>
                              <button onClick={() => setCompanyWarmth(list.id, coName, "hot")} style={cw === "hot" ? selHot : defBtn}>
                                <span style={dot("#D84040", cw === "hot")}></span>Hot
                              </button>
                              <button onClick={() => setCompanyWarmth(list.id, coName, "warm")} style={cw === "warm" ? selWarm : defBtn}>
                                <span style={dot("#038362", cw === "warm")}></span>Warm
                              </button>
                              <button onClick={() => setCompanyWarmth(list.id, coName, "cold")} style={cw === "cold" ? selCold : defBtn}>
                                <span style={dot("#4B6A8A", cw === "cold")}></span>Cold
                              </button>
                            </div>
                            {noteOpen && (
                              <textarea
                                value={note}
                                onChange={e => setCompanyNote(list.id, coName, e.target.value)}
                                placeholder="Add context (optional) — who you know, how you'd intro…"
                                rows={2}
                                style={{ width: "100%", marginTop: 10, padding: "9px 12px", fontSize: 13, border: "1px solid #E6E2DB", borderRadius: 10, outline: "none", resize: "none", background: "#fff", color: "#06171F", lineHeight: 1.55, fontFamily: "'Manrope', sans-serif", animation: "slideIn 160ms ease forwards" }}
                              />
                            )}
                          </div>
                        );
                      })}
                    </div>
                  ) : (
                    <div style={{ padding: "0 20px 16px", fontSize: 12, color: "#A8A199" }}>Company details for this list aren&apos;t available.</div>
                  )}

                  {/* Thread row */}
                  <div style={{ borderTop: "1px solid #F0ECEC" }}>
                    <button onClick={() => toggleThread(list.id)} style={{ width: "100%", padding: "11px 20px", background: "#FAFDF9", border: "none", display: "flex", alignItems: "center", gap: 7, cursor: "pointer", textAlign: "left" }}>
                      {threadReplies.length > 0 && (
                        <>
                          <span style={{ fontSize: 12, fontWeight: 500, color: "#606B70" }}>{threadReplies.length} {threadReplies.length === 1 ? "reply" : "replies"}</span>
                          <span style={{ color: "#D4CFC5", fontSize: 12 }}>·</span>
                        </>
                      )}
                      <span style={{ fontSize: 12, fontWeight: 500, color: "#038362" }}>+ Comment</span>
                      <span style={{ marginLeft: "auto", fontSize: 11, color: "#C4BFB8" }}>{isExpanded ? "▲" : "▼"}</span>
                    </button>
                  </div>

                  {/* Thread content */}
                  {isExpanded && (
                    <div style={{ background: "#FAFDF9", borderTop: "1px solid #F0ECEC", padding: "16px 20px", display: "flex", flexDirection: "column", gap: 14, animation: "slideIn 180ms ease forwards" }}>
                      {threadReplies.map(reply => (
                        <div key={reply.id} style={{ display: "flex", gap: 12 }}>
                          <div style={avatarStyle(reply.author)}>{reply.initials}</div>
                          <div style={{ flex: 1, background: "#fff", border: "1px solid #EFEAE1", borderRadius: 12, padding: "12px 14px" }}>
                            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
                              <span style={{ fontSize: 13, fontWeight: 500, color: "#06171F" }}>{reply.author}</span>
                              <span style={{ fontSize: 11, color: "#C4BFB8" }}>{reply.time}</span>
                            </div>
                            <div style={{ fontSize: 13, color: "#606B70", lineHeight: 1.6 }}>{reply.text}</div>
                          </div>
                        </div>
                      ))}
                      <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
                        <div style={{ width: 30, height: 30, borderRadius: "50%", background: "#038362", color: "#FAFDF9", display: "grid", placeItems: "center", fontSize: 11, fontWeight: 600, flexShrink: 0, marginTop: 2 }}>SC</div>
                        <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 8 }}>
                          <textarea value={drafts[list.id] || ""} onChange={e => setDraft(list.id, e.target.value)} placeholder="Leave a note for the team..." rows={2} style={{ width: "100%", padding: "10px 14px", fontSize: 13, border: "1px solid #E6E2DB", borderRadius: 12, outline: "none", resize: "none", background: "#fff", color: "#06171F", lineHeight: 1.55, fontFamily: "'Manrope', sans-serif" }} />
                          <div style={{ display: "flex", justifyContent: "flex-end" }}>
                            <button onClick={() => submitReply(list.id, list.initialReplies)} style={{ padding: "7px 18px", background: "#038362", color: "#fff", border: "none", borderRadius: 9999, fontSize: 13, fontWeight: 500, cursor: "pointer" }}>Send reply</button>
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* ── Footer ── */}
      <div style={{ borderTop: "1px solid #F0EBE6", background: "#FDFBF7", padding: "20px 32px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <img src="assets/malachyte-logo-gradient.png" style={{ height: 16, width: "auto", opacity: 0.5 }} alt="Malachyte" onError={e => { e.target.style.display = "none"; }} />
        <span style={{ fontSize: 11, color: "#C4BFB8" }}>Questions? Reply to your partner contact.</span>
      </div>
    </div>
  );
}

Object.assign(window, { ExternalView });
