/* MatchPlan.ai — Briefs library: view all, search, multi-select, export CSV, delete. */

function csvCell(v) {
  var s = String(v == null ? "" : v);
  if (/[",\n]/.test(s)) s = '"' + s.replace(/"/g, '""') + '"';
  return s;
}
function briefsToCSV(preps) {
  var head = ["Company", "Website", "Stage", "Match", "Status", "Contacts", "Key insight", "Created"];
  var rows = preps.map(function (p) {
    var people = (p.contacts || []).filter(function (c) { return c.name; }).map(function (c) { return c.name + (c.title ? " (" + c.title + ")" : ""); }).join("; ");
    return [p.prospect, p.url || "", p.stage, (p.confidence || ""), p.done ? "Done" : "Ready",
      people, p.insight || "", new Date(p.createdAt).toLocaleDateString()];
  });
  return [head].concat(rows).map(function (r) { return r.map(csvCell).join(","); }).join("\n");
}
function downloadCSV(name, text) {
  try {
    var blob = new Blob([text], { type: "text/csv;charset=utf-8;" });
    var url = URL.createObjectURL(blob);
    var a = document.createElement("a");
    a.href = url; a.download = name; document.body.appendChild(a); a.click();
    document.body.removeChild(a); setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
  } catch (e) {}
}

function PeopleStack({ contacts }) {
  const named = (contacts || []).filter(c => c.name);
  if (named.length === 0) return <span style={{ color: "var(--fg-3)", fontSize: "var(--fs-body-3)" }}>Company only</span>;
  const shown = named.slice(0, 3);
  return (
    <span className="mp-people-mini" title={named.map(c => c.name).join(", ")}>
      {shown.map((c, i) => <Avatar key={i} name={c.name} color={["blue", "purple", "green", "gold"][i % 4]} size={26} />)}
      {named.length > 3 && <span className="mp-av-soft" style={{ width: 26, height: 26, fontSize: 10, display: "inline-flex", alignItems: "center", justifyContent: "center", borderRadius: 999, fontWeight: 900, background: "var(--accent-soft)", color: "var(--accent)" }}>+{named.length - 3}</span>}
    </span>
  );
}

function ConfirmDelete({ count, onCancel, onConfirm }) {
  return (
    <div className="mp-modal-scrim" onClick={onCancel}>
      <div className="mp-modal" onClick={e => e.stopPropagation()}>
        <span className="mp-modal__icon"><Icon name="Trash2" size={22} /></span>
        <h3 className="text-heading-3" style={{ margin: 0 }}>Delete {count === 1 ? "this brief" : count + " briefs"}?</h3>
        <p style={{ margin: "10px 0 0", color: "var(--fg-2)", fontSize: "var(--fs-body-1)", lineHeight: 1.55 }}>
          This permanently removes {count === 1 ? "it" : "them"} and any post-call analysis. This can't be undone. Your monthly brief count isn't refunded.
        </p>
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 22 }}>
          <Button variant="secondary" onClick={onCancel}>Cancel</Button>
          <Button variant="danger" icon="Trash2" onClick={onConfirm}>Delete {count === 1 ? "" : count}</Button>
        </div>
      </div>
    </div>
  );
}

function BriefsPage({ path }) {
  const toast = useToast();
  const [, force] = React.useReducer(x => x + 1, 0);
  const [q, setQ] = React.useState("");
  const [sel, setSel] = React.useState(() => new Set());
  const [confirm, setConfirm] = React.useState(null); // {ids}
  const all = MP.get().preps;
  // pitchiq#511 — the list could not be read (a #399 platform outage): the slot replaces the toolbar and the table (spec L20),
  // the page header stays (L19). Never the empty state below, which would say "No briefs yet" about a list nobody could read.
  // The slot lives in pages-dash.jsx and the flag in store.js; both are guarded (like app.jsx's `refusalNow`) because a browser
  // can run this file against an older cached copy of either (pitchiq#443) — then the list path below draws, as before.
  const OutageSlot = window.BriefsOutageSlot;
  const briefsOutage = typeof OutageSlot === "function" && typeof MP.briefsOutage === "function" && MP.briefsOutage();

  const filtered = all.filter(p => {
    if (!q.trim()) return true;
    const hay = (p.prospect + " " + (p.url || "") + " " + (p.insight || "") + " " + (p.contacts || []).map(c => c.name + " " + c.title).join(" ")).toLowerCase();
    return hay.includes(q.trim().toLowerCase());
  });

  const allVisibleSelected = filtered.length > 0 && filtered.every(p => sel.has(p.id));
  const toggle = (id) => setSel(s => { const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n; });
  const toggleAll = () => setSel(s => {
    if (allVisibleSelected) { const n = new Set(s); filtered.forEach(p => n.delete(p.id)); return n; }
    const n = new Set(s); filtered.forEach(p => n.add(p.id)); return n;
  });
  const clearSel = () => setSel(new Set());

  const selectedPreps = all.filter(p => sel.has(p.id));
  const exportSel = (preps, label) => {
    if (!preps.length) return;
    downloadCSV("pre-sales-agent-briefs.csv", briefsToCSV(preps));
    toast.success("Exported " + preps.length + " brief" + (preps.length > 1 ? "s" : "") + " to CSV.");
  };
  const doDelete = async (ids) => {
    // The local UI updates stay BEFORE the await, so the list reflects the
    // local write immediately; only the success CLAIM waits for the server.
    const saved = MP.deletePreps(ids);
    setSel(s => { const n = new Set(s); ids.forEach(i => n.delete(i)); return n; });
    setConfirm(null); force();
    try {
      await saved;
      toast.success("Deleted " + ids.length + " brief" + (ids.length > 1 ? "s" : "") + ".");
    } catch (e) {
      // #87: this used to toast success unconditionally. If the DELETE failed
      // the briefs are still on the server and reappear on the next load, so
      // claiming success is a lie the user acts on.
      toast.error("Couldn't delete " + (ids.length > 1 ? "those briefs" : "that brief") + ". Try again.");
    }
  };

  return (
    <Shell path={path}>
      <PageHeader title="Briefs"
        subtitle="Every Game Day Brief you've generated. Search, export, or clean up."
        actions={<>
          <Button variant="secondary" size="sm" icon="Download" disabled={!filtered.length}
            onClick={() => exportSel(filtered)}>Export all</Button>
          <Button size="sm" icon="Sparkles" onClick={() => navigate("/prepare/new")}>New brief</Button>
        </>} />

      {briefsOutage ? <OutageSlot /> : <>
      <div className="mp-briefs-toolbar mp-fade">
        <div className="mp-search">
          <Icon name="Search" size={17} />
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search by company, person, or insight…" />
        </div>
        <span style={{ fontSize: "var(--fs-body-3)", color: "var(--fg-2)" }}>
          <b style={{ fontFamily: "var(--font-numbers)", color: "var(--fg-1)" }}>{filtered.length}</b> {filtered.length === 1 ? "brief" : "briefs"}{q ? " found" : ""}
        </span>
      </div>

      {sel.size > 0 && (
        <div className="mp-selbar">
          <span className="mp-selbar__count"><b>{sel.size}</b> selected</span>
          <div style={{ flex: 1 }}></div>
          <Button variant="secondary" size="sm" icon="Download" onClick={() => exportSel(selectedPreps)}>Export CSV</Button>
          <Button variant="secondary" size="sm" icon="Trash2" onClick={() => setConfirm({ ids: [...sel] })}>Delete</Button>
          <button className="mp-selbar__x" onClick={clearSel} aria-label="Clear selection"><Icon name="X" size={17} /></button>
        </div>
      )}

      <div className="mp-tablewrap mp-fade">
        {filtered.length === 0 ? (
          <div className="mp-empty">
            <div className="mp-empty__icon"><Icon name={q ? "SearchX" : "Inbox"} size={24} /></div>
            <p style={{ margin: 0 }}>{q ? "No briefs match \u201C" + q + "\u201D." : "No briefs yet. Generate your first one."}</p>
            {!q && <Button size="sm" icon="Sparkles" style={{ marginTop: 14 }} onClick={() => navigate("/prepare/new")}>New brief</Button>}
          </div>
        ) : (
          <table className="tm-table">
            <thead>
              <tr>
                <th className="mp-th-check">
                  <button className={`mp-check${allVisibleSelected ? " is-on" : ""}`} onClick={toggleAll} aria-label="Select all">
                    {allVisibleSelected && <Icon name="Check" size={13} strokeWidth={3} />}
                  </button>
                </th>
                <th>Prospect</th>
                <th style={{ width: 130 }}>Status</th>
                <th style={{ width: 130 }}>Who's meeting</th>
                <th>Key insight</th>
                <th style={{ width: 96 }}>Created</th>
                <th style={{ width: 44 }}></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(p => {
                const on = sel.has(p.id);
                return (
                  <tr key={p.id} className={`mp-prep-row${on ? " is-selected" : ""}`}>
                    <td className="mp-td-check" onClick={(e) => { e.stopPropagation(); toggle(p.id); }}>
                      <button className={`mp-check${on ? " is-on" : ""}`} aria-label="Select">
                        {on && <Icon name="Check" size={13} strokeWidth={3} />}
                      </button>
                    </td>
                    <td onClick={() => navigate("/prepare/" + p.id)}>
                      <div className="mp-cellflex">
                        <Avatar name={p.prospect} color="blue" size={36} soft />
                        <div style={{ minWidth: 0 }}>
                          <div className="mp-prospect-name">{p.prospect}</div>
                          <div className="mp-prospect-sub">{p.stage} · {p.url}</div>
                        </div>
                      </div>
                    </td>
                    <td onClick={() => navigate("/prepare/" + p.id)}>
                      {p.done ? <Chip tone="neutral" icon="Check">Done</Chip> : <Chip tone={confTone[p.confidence]} icon={confIcon[p.confidence]}>{confLabel[p.confidence]}</Chip>}
                    </td>
                    <td onClick={() => navigate("/prepare/" + p.id)}><PeopleStack contacts={p.contacts} /></td>
                    <td className="mp-td-insight" onClick={() => navigate("/prepare/" + p.id)}>{p.insight}</td>
                    <td onClick={() => navigate("/prepare/" + p.id)} style={{ color: "var(--fg-2)", fontSize: "var(--fs-body-3)" }}>{relTime(p.createdAt)}</td>
                    <td>
                      <button className="mp-rowdel" onClick={(e) => { e.stopPropagation(); setConfirm({ ids: [p.id] }); }} aria-label="Delete brief"><Icon name="Trash2" size={16} /></button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
      </>}

      {confirm && <ConfirmDelete count={confirm.ids.length} onCancel={() => setConfirm(null)} onConfirm={() => doDelete(confirm.ids)} />}
    </Shell>
  );
}

Object.assign(window, { BriefsPage, briefsToCSV });
