// Briefs page — API-wired list + markdown reader.

// React hooks (Babel-standalone — make hooks visible per-script)
const { useState, useEffect, useRef, useMemo, useCallback, createContext, useContext } = React;

const briefsStyles = {
  root: { display: "flex", height: "100%", minHeight: 0 },
  list: {
    width: 240, flex: "0 0 240px",
    borderRight: "1px solid var(--vk-border-subtle)",
    background: "var(--vk-surface-1)", overflowY: "auto",
  },
  listItem: {
    padding: "12px 14px", borderBottom: "1px solid var(--vk-border-subtle)",
    cursor: "pointer", display: "flex", flexDirection: "column", gap: 4,
  },
  listItemActive: { background: "var(--vk-surface-2)" },
  reader: { flex: 1, overflowY: "auto", padding: 24, display: "flex", flexDirection: "column", gap: 16 },
  body: { fontSize: 14, lineHeight: 1.65, color: "var(--vk-text-primary)", maxWidth: 720, fontFamily: "var(--vk-font-sans)" },
};

function renderMd(md, openEntity, openEvidence) {
  if (!md) return null;
  const lines = md.split("\n");
  const out = [];
  let buf = [];
  function flushList() {
    if (buf.length) {
      out.push(
        <ul key={"ul" + out.length} style={{ paddingLeft: 18, margin: "8px 0", display: "flex", flexDirection: "column", gap: 6 }}>
          {buf.map((b, i) => <li key={i} style={{ color: "var(--vk-text-primary)", fontSize: 13.5 }}>{renderInline(b)}</li>)}
        </ul>
      );
      buf = [];
    }
  }
  function renderInline(line) {
    const parts = [];
    const re = /\[([^\]]+)\]\(#([^)]+)\)/g;
    let m, last = 0;
    while ((m = re.exec(line)) !== null) {
      if (m.index > last) parts.push(line.slice(last, m.index));
      parts.push(
        <a
          key={"el" + parts.length}
          href="#"
          className="vk-link"
          onClick={(e) => {
            e.preventDefault();
            window.VK_API.fetchPath("/entities/" + m[2]).then((r) => {
              if (r?.entity) openEntity(r.entity);
            }).catch(() => {});
          }}
        >{m[1]}</a>
      );
      last = m.index + m[0].length;
    }
    if (last < line.length) parts.push(line.slice(last));
    return parts.flatMap((p, idx) => {
      if (typeof p !== "string") return p;
      const sub = [];
      const cre = /\[\^(\d+)\]/g;
      let cm, clast = 0;
      while ((cm = cre.exec(p)) !== null) {
        if (cm.index > clast) sub.push(p.slice(clast, cm.index));
        sub.push(
          <sup key={"sup" + idx + cm.index}>
            <a href="#" style={{ color: "var(--vk-text-link)", fontFamily: "var(--vk-font-mono)" }}
              onClick={(ev) => { ev.preventDefault(); openEvidence(null); }}
            >[{cm[1]}]</a>
          </sup>
        );
        clast = cm.index + cm[0].length;
      }
      if (clast < p.length) sub.push(p.slice(clast));
      return sub;
    });
  }
  lines.forEach((line, idx) => {
    if (/^##\s/.test(line)) {
      flushList();
      out.push(<h3 key={idx} style={{ fontSize: 14, fontWeight: 500, color: "var(--vk-text-primary)", letterSpacing: "0.04em", textTransform: "uppercase", margin: "20px 0 4px" }}>{line.slice(3).trim()}</h3>);
    } else if (/^-\s/.test(line)) {
      buf.push(line.slice(2));
    } else if (/^\[\^\d+\]/.test(line)) {
      flushList();
      const m = line.match(/^\[\^(\d+)\]:\s*(.+)$/);
      if (m) out.push(
        <div key={idx} style={{ fontSize: 11, color: "var(--vk-text-tertiary)", fontFamily: "var(--vk-font-mono)", paddingLeft: 8, borderLeft: "1px solid var(--vk-border-subtle)" }}>
          [{m[1]}] {m[2]}
        </div>
      );
    } else if (line.trim() === "") {
      flushList();
    } else {
      flushList();
      out.push(<p key={idx} style={{ margin: "6px 0", color: "var(--vk-text-primary)", fontSize: 13.5 }}>{renderInline(line)}</p>);
    }
  });
  flushList();
  return out;
}

function Briefs({ openEntity, openEvidence }) {
  const app = useAppState();
  const listQ = useApi("/briefs", { city: app.city }, [app.city]);
  const briefs = Array.isArray(listQ.data) ? listQ.data : [];
  const [activeId, setActiveId] = useState(null);

  useEffect(() => {
    if (briefs.length && !activeId) setActiveId(briefs[0].brief_id);
  }, [briefs.length]);

  const detailQ = useApi(activeId ? "/briefs/" + activeId : "/briefs", activeId ? {} : { city: app.city, limit: 0 }, [activeId]);
  const active = activeId ? detailQ.data : briefs[0];

  return (
    <div style={briefsStyles.root}>
      <aside style={briefsStyles.list}>
        <div style={{ padding: "12px 14px", borderBottom: "1px solid var(--vk-border-emphasis)", display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
          <span style={{ fontSize: 13, fontWeight: 500 }}>All briefs</span>
          <span style={{ fontSize: 11, color: "var(--vk-text-tertiary)", fontFamily: "var(--vk-font-mono)" }}>{briefs.length}</span>
        </div>
        {listQ.loading && <SkeletonBlock rows={4} />}
        {!listQ.loading && briefs.length === 0 && <EmptyState icon="FileText" title="No briefs for this city." />}
        {briefs.map((b) => (
          <div
            key={b.brief_id}
            style={{ ...briefsStyles.listItem, ...(activeId === b.brief_id ? briefsStyles.listItemActive : {}) }}
            onClick={() => setActiveId(b.brief_id)}
          >
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <span style={{ fontSize: 13, fontWeight: 500, color: "var(--vk-text-primary)" }}>{b.city}</span>
              <ConfPill confidence={b.overall_confidence} />
            </div>
            <span style={{ fontSize: 11, color: "var(--vk-text-tertiary)", fontFamily: "var(--vk-font-mono)" }}>
              {(b.generated_at || "").slice(0, 10)}
            </span>
            <span style={{ fontSize: 11, color: "var(--vk-text-secondary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
              {b.brief_title}
            </span>
          </div>
        ))}
      </aside>

      <div style={briefsStyles.reader}>
        {!active && <EmptyState icon="FileText" title="Select a brief to read." />}
        {active && (
          <>
            <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 12 }}>
              <div>
                <h1 style={{ fontSize: 22, fontWeight: 500, color: "var(--vk-text-primary)", margin: 0 }}>{active.brief_title}</h1>
                <div style={{ fontSize: 11, color: "var(--vk-text-tertiary)", fontFamily: "var(--vk-font-mono)", marginTop: 4 }}>
                  {active.source_count} sources · {active.entity_count} entities · {active.relationship_count} relationships · model {active.model_used}
                </div>
              </div>
              <div style={{ display: "flex", gap: 6 }}>
                <button className="vk-btn"><Icon name="FileText" size={14} /> PDF</button>
                <button className="vk-btn"><Icon name="FileCode" size={14} /> Markdown</button>
                <button className="vk-btn"><Icon name="Code" size={14} /> HTML</button>
              </div>
            </div>
            <div style={briefsStyles.body}>{renderMd(active.markdown_body, openEntity, openEvidence)}</div>
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Briefs });
