// Evidence page — API-wired.

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

const evidenceStyles = {
  page: { padding: 16, display: "flex", flexDirection: "column", gap: 12, height: "100%", overflow: "hidden" },
  filters: { display: "flex", gap: 8, alignItems: "center" },
  tableWrap: { flex: 1, overflow: "auto", background: "var(--vk-surface-1)", borderRadius: 5, boxShadow: "var(--vk-ring-ambient)" },
  table: { width: "100%", borderCollapse: "separate", borderSpacing: 0, fontSize: 13 },
  th: {
    fontSize: 11, color: "var(--vk-text-tertiary)", letterSpacing: "0.08em",
    textTransform: "uppercase", fontWeight: 500, textAlign: "left",
    padding: "10px 12px", borderBottom: "1px solid var(--vk-border-emphasis)",
    background: "var(--vk-surface-1)", position: "sticky", top: 0, zIndex: 1,
  },
  td: { padding: "9px 12px", borderBottom: "1px solid var(--vk-border-subtle)", color: "var(--vk-text-primary)" },
};

function Evidence({ openEvidence }) {
  const app = useAppState();
  const [type, setType] = useState("all");
  const [conf, setConf] = useState("all");
  const [search, setSearch] = useState("");

  const { data, loading } = useApi("/evidence", {
    city: app.city,
    limit: 100,
    confidence: conf !== "all" ? conf : undefined,
    source_type: type !== "all" ? type : undefined,
  }, [app.city, conf, type]);

  const allRows = Array.isArray(data) ? data : [];
  const filtered = useMemo(() => {
    if (!search) return allRows;
    const q = search.toLowerCase();
    return allRows.filter((e) =>
      (e.source_title || "").toLowerCase().includes(q) ||
      (e.snippet || "").toLowerCase().includes(q)
    );
  }, [allRows, search]);

  const sourceTypes = useMemo(() => Array.from(new Set(allRows.map((r) => r.source_type))).filter(Boolean), [allRows]);

  return (
    <div style={evidenceStyles.page}>
      <div style={evidenceStyles.filters}>
        <h2 style={{ margin: 0, fontSize: 18, fontWeight: 500 }}>Evidence</h2>
        <span style={{ fontSize: 11, color: "var(--vk-text-tertiary)" }}>
          {loading ? "loading…" : `${filtered.length} of ${allRows.length} sources`}
        </span>
        <div style={{ flex: 1 }} />
        <input
          className="vk-input"
          placeholder="search snippet…" style={{ width: 220 }}
          value={search} onChange={(e) => setSearch(e.target.value)}
        />
        <Dropdown label="Type" value={type}
          options={["all", ...sourceTypes].map((t) => ({ label: t, value: t }))}
          onChange={(o) => setType(o.value)}
        />
        <Dropdown label="Conf." value={conf}
          options={["all", "high", "medium", "low"].map((c) => ({ label: c, value: c }))}
          onChange={(o) => setConf(o.value)}
        />
      </div>

      {loading ? <SkeletonBlock rows={10} /> : filtered.length === 0 ? (
        <EmptyState icon="Folder" title="No evidence matches these filters." />
      ) : (
        <div style={evidenceStyles.tableWrap}>
          <table style={evidenceStyles.table}>
            <thead>
              <tr>
                <th style={evidenceStyles.th}>Title</th>
                <th style={evidenceStyles.th}>Publisher</th>
                <th style={evidenceStyles.th}>Type</th>
                <th style={{ ...evidenceStyles.th, textAlign: "right" }}>Date</th>
                <th style={{ ...evidenceStyles.th, textAlign: "right" }}>Conf.</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((r) => (
                <tr key={r.evidence_id}
                  style={{ cursor: "pointer" }}
                  onClick={() => openEvidence(r)}
                  onMouseEnter={(ev) => (ev.currentTarget.style.background = "var(--vk-surface-2)")}
                  onMouseLeave={(ev) => (ev.currentTarget.style.background = "transparent")}
                >
                  <td style={evidenceStyles.td}>
                    <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                      <span style={{ fontWeight: 500 }}>{r.source_title}</span>
                      <span style={{ fontSize: 11, color: "var(--vk-text-tertiary)", fontFamily: "var(--vk-font-mono)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: 460 }}>
                        {r.source_url}
                      </span>
                    </div>
                  </td>
                  <td style={{ ...evidenceStyles.td, color: "var(--vk-text-secondary)" }}>{r.publisher_or_owner}</td>
                  <td style={{ ...evidenceStyles.td, color: "var(--vk-text-secondary)" }}>{r.source_type}</td>
                  <td style={{ ...evidenceStyles.td, textAlign: "right", color: "var(--vk-text-secondary)", fontFamily: "var(--vk-font-mono)" }}>{r.date_published}</td>
                  <td style={{ ...evidenceStyles.td, textAlign: "right" }}><ConfPill confidence={r.confidence} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Evidence });
