/* screens-company.jsx — Company 360 slide-over drawer (read-only v1).
   Open from anywhere:
     window.openCompany({ name, harveyId, pipeline })   // pipeline row optional context
   or dispatch CustomEvent "vault:open-company" with the same detail. */
(() => {
  const { useState, useEffect } = React;

  window.openCompany = function (detail) {
    window.dispatchEvent(new CustomEvent("vault:open-company", { detail: detail || {} }));
  };

  const norm = (s) => String(s || "").toLowerCase().replace(/[.,']/g, "").replace(/\s+/g, " ").trim();
  const money = (n) => (n == null || isNaN(n)) ? "—" : "$" + Number(n).toLocaleString();
  const mm = (n) => (n == null || isNaN(n)) ? "—" : "$" + Number(n).toLocaleString(undefined, { maximumFractionDigits: 2 }) + "M";

  function Section({ title, children }) {
    return (
      <div style={{ marginBottom: 18 }}>
        <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 0.4, color: "var(--muted, #6b7280)", marginBottom: 6 }}>{title}</div>
        {children}
      </div>
    );
  }

  function Row({ label, value }) {
    return (
      <div style={{ display: "flex", gap: 10, padding: "3px 0", fontSize: 13 }}>
        <div style={{ width: 108, flexShrink: 0, color: "var(--muted, #6b7280)" }}>{label}</div>
        <div style={{ color: "var(--ink, #111827)", minWidth: 0 }}>{value ?? "—"}</div>
      </div>
    );
  }

  function Card({ children }) {
    return <div style={{ border: "1px solid var(--line, #e5e7eb)", borderRadius: 10, padding: "10px 12px", marginBottom: 8, background: "#fff" }}>{children}</div>;
  }

  window.CompanyDrawer = function CompanyDrawer() {
    const [co, setCo] = useState(null); // { name, harveyId, pipeline }
    const [crs, setCrs] = useState(null); // null = loading, [] = none

    useEffect(() => {
      const onOpen = (e) => setCo(e.detail || {});
      const onKey = (e) => { if (e.key === "Escape") setCo(null); };
      window.addEventListener("vault:open-company", onOpen);
      window.addEventListener("keydown", onKey);
      return () => { window.removeEventListener("vault:open-company", onOpen); window.removeEventListener("keydown", onKey); };
    }, []);

    // Fetch CRs for this company whenever the drawer opens on a new target.
    useEffect(() => {
      if (!co) { setCrs(null); return; }
      const nm = String(co.name || (co.pipeline && co.pipeline.target) || "").replace(/"/g, "");
      const hid2 = co.harveyId != null && co.harveyId !== "" ? String(co.harveyId) : null;
      const parts = [];
      if (hid2) parts.push(`harvey_target_id.eq.${hid2}`);
      if (nm) parts.push(`target.ilike."${nm}"`);
      if (!parts.length || !window.VaultAPI || !window.VaultAPI.vaultFetch) { setCrs([]); return; }
      const q = parts.length > 1 ? `or=(${parts.join(",")})` : parts[0].replace(".eq.", "=eq.").replace(".ilike.", "=ilike.");
      let dead = false;
      window.VaultAPI.vaultFetch(`/crs?${encodeURI(q)}&order=due_date.asc.nullslast`, { method: "GET" })
        .then(rows => { if (!dead) setCrs(rows || []); })
        .catch(() => { if (!dead) setCrs([]); });
      return () => { dead = true; };
    }, [co && co.name, co && co.harveyId]);

    if (!co) return null;

    const name = co.name || (co.pipeline && co.pipeline.target) || "";
    const hid = co.harveyId != null && co.harveyId !== "" ? String(co.harveyId) : null;
    const n = norm(name);

    const offers = (window.HARVEY_OFFERS || []).filter(o =>
      (hid && String(o.targetId) === hid) || (n && norm(o.target) === n));
    const closed = (window.HARVEY_CLOSED || []).filter(c => n && norm(c.name) === n);
    const pl = co.pipeline || null;
    const harveyUrl = hid && window.VaultHarvey ? window.VaultHarvey.companyUrl(hid) : null;
    const nameOf = (id) => ((window.VAULT_FIRM && window.VAULT_FIRM.PEOPLE_BY_ID && window.VAULT_FIRM.PEOPLE_BY_ID[id]) || {}).name || id || "—";

    return (
      <div>
        <div onClick={() => setCo(null)}
          style={{ position: "fixed", inset: 0, background: "rgba(17,24,39,0.32)", zIndex: 900 }} />
        <div style={{
          position: "fixed", top: 0, right: 0, bottom: 0, width: "min(430px, 94vw)", zIndex: 901,
          background: "var(--panel, #f8fafc)", borderLeft: "1px solid var(--line, #e5e7eb)",
          boxShadow: "-12px 0 32px rgba(17,24,39,0.14)", overflowY: "auto", padding: "18px 18px 28px",
        }}>
          <div style={{ display: "flex", alignItems: "flex-start", gap: 10, marginBottom: 4 }}>
            <div style={{ minWidth: 0, flex: 1 }}>
              <div style={{ fontSize: 17, fontWeight: 700, color: "var(--ink, #111827)", lineHeight: 1.25 }}>{name}</div>
              <div style={{ display: "flex", gap: 8, marginTop: 6, flexWrap: "wrap", alignItems: "center" }}>
                {pl && pl.status != null && (
                  <span style={{ fontSize: 11, fontWeight: 600, padding: "2px 8px", borderRadius: 999, background: "#eaf2f8", color: "var(--accent, #196EA7)" }}>
                    Status {pl.status}
                  </span>
                )}
                {harveyUrl && (
                  <a href={harveyUrl} target="_blank" rel="noopener noreferrer"
                    style={{ fontSize: 12, fontWeight: 600, color: "var(--accent, #196EA7)", textDecoration: "none" }}>
                    Open in Harvey ↗
                  </a>
                )}
              </div>
            </div>
            <button onClick={() => setCo(null)} aria-label="Close"
              style={{ border: "none", background: "transparent", fontSize: 20, lineHeight: 1, cursor: "pointer", color: "var(--muted, #6b7280)", padding: 4 }}>×</button>
          </div>

          <div style={{ height: 1, background: "var(--line, #e5e7eb)", margin: "12px 0 16px" }} />

          {pl && (
            <Section title="PIPELINE">
              <Card>
                <Row label="Buyer" value={pl.buyer} />
                <Row label="Module" value={pl.module} />
                <Row label="EBITDA / Sales" value={(pl.ebitda != null ? "$" + pl.ebitda + "M" : "—") + "  /  " + (pl.sales != null ? "$" + pl.sales + "M" : "—")} />
                <Row label="Next action" value={pl.nextAction || "—"} />
                <Row label="Deal team" value={[pl.dm1Name, pl.dm2Name].filter(Boolean).join(" · ") || "—"} />
              </Card>
            </Section>
          )}

          <Section title={"OFFERS (" + offers.length + ")"}>
            {offers.length === 0 && <div style={{ fontSize: 13, color: "var(--muted, #6b7280)" }}>No offers on record.</div>}
            {offers.map((o, i) => (
              <Card key={i}>
                <Row label="Stage" value={o.stage} />
                <Row label="Offer date" value={o.offerDate} />
                <Row label="Amount" value={o.amount} />
                <Row label="Buyer" value={o.buyer} />
                <Row label="Project" value={o.project} />
                <Row label="Team" value={[o.dm, o.aa].filter(Boolean).map(nameOf).join(" · ")} />
              </Card>
            ))}
          </Section>

          <Section title={"CLOSED DEALS (" + closed.length + ")"}>
            {closed.length === 0 && <div style={{ fontSize: 13, color: "var(--muted, #6b7280)" }}>No closed deals on record.</div>}
            {closed.map((c, i) => (
              <Card key={i}>
                <Row label="Closed" value={c.closeDate} />
                <Row label="Buyer" value={c.buyer} />
                <Row label="TEV / Fee" value={mm(c.tev) + "  /  " + money(c.fee)} />
                <Row label="Type" value={c.type} />
                <Row label="Deal team" value={[c.dm1, c.dm2, c.dm3].filter(Boolean).map(nameOf).join(" · ")} />
              </Card>
            ))}
          </Section>

          <Section title={<span><window.AcroLabel text="CRs"/>{crs == null ? "" : " (" + crs.length + ")"}</span>}>
            {crs == null && <div style={{ fontSize: 13, color: "var(--muted, #6b7280)" }}>Loading…</div>}
            {crs != null && crs.length === 0 && <div style={{ fontSize: 13, color: "var(--muted, #6b7280)" }}>No CRs on record.</div>}
            {(crs || []).map((c, i) => (
              <Card key={c.id || i}>
                <Row label="Status" value={
                  <span style={{ fontSize: 11, fontWeight: 600, padding: "2px 8px", borderRadius: 999,
                    background: c.completed_at ? "#e8f5ec" : "#fdf3e2",
                    color: c.completed_at ? "#1a7f3c" : "#9a6b12" }}>
                    {c.completed_at ? "Completed" : (c.status || "open")}
                  </span>
                } />
                <Row label="Due" value={c.due_date || "—"} />
                <Row label="Owner" value={nameOf(c.owner_id)} />
                {c.note ? <Row label="Note" value={c.note} /> : null}
              </Card>
            ))}
          </Section>
        </div>
      </div>
    );
  };
})();