/* Data inspector — table-style view of every JSON-backed table.
   Use this to eyeball the dataset like a DB admin, verify FK joins,
   and debug new profile data before it lights up the UI. */

const { useState: useStateDI } = React;

const TABLE_ORDER = [
  "profiles",
  "theses",
  "criteria",
  "anti_theses",
  "candidates",
  "candidate_scores",
  "candidate_anti_triggers",
  "news",
  "refinements",
];

function DataInspectorScreen() {
  const [activeTable, setActiveTable] = useStateDI(TABLE_ORDER[0]);
  const [query, setQuery] = useStateDI("");
  const [profileFilter, setProfileFilter] = useStateDI("all");

  const rows = db[activeTable] || [];
  const filtered = rows.filter((r) => {
    if (profileFilter !== "all") {
      const pid = r.profile_id || resolveProfileId(activeTable, r);
      if (pid && pid !== profileFilter) return false;
    }
    if (!query) return true;
    const q = query.toLowerCase();
    return Object.values(r).some((v) => JSON.stringify(v).toLowerCase().includes(q));
  });

  const columns = filtered.length > 0
    ? Array.from(new Set(filtered.flatMap((r) => Object.keys(r))))
    : (rows[0] ? Object.keys(rows[0]) : []);

  return (
    <div style={{ maxWidth: 1280, margin: "0 auto", padding: "24px 24px 100px" }}>
      <div style={{ marginBottom: 18 }}>
        <div className="label">Data inspector</div>
        <h1 style={{ margin: "6px 0 4px", fontFamily: "var(--font-serif)", fontWeight: 500, fontSize: 32, letterSpacing: "-0.02em" }}>
          Tables backing the prototype
        </h1>
        <div style={{ fontSize: 13, color: "var(--ink-3)" }}>
          Each table maps 1-to-1 to a future DB table. UUID primary keys, explicit FKs.
          Edit JSON in <span className="mono">data/</span> or re-run <span className="mono">scripts/seed.py</span> to regenerate.
        </div>
      </div>

      {/* Table tabs */}
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 14 }}>
        {TABLE_ORDER.map((name) => (
          <button
            key={name}
            onClick={() => setActiveTable(name)}
            className={"btn btn-sm " + (activeTable === name ? "btn-primary" : "btn-ghost")}
            style={{ borderRadius: "var(--d-radius)" }}
          >
            <span className="mono" style={{ fontSize: 11 }}>{name}</span>
            <span className="mono" style={{ fontSize: 10, marginLeft: 6, opacity: 0.7 }}>
              {(db[name] || []).length}
            </span>
          </button>
        ))}
      </div>

      {/* Filters */}
      <div style={{ display: "flex", gap: 10, alignItems: "center", marginBottom: 12, flexWrap: "wrap" }}>
        <input
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Search rows…"
          style={{
            flex: "1 1 240px",
            padding: "6px 10px",
            border: "1px solid var(--line-2)",
            borderRadius: "var(--d-radius)",
            background: "var(--bg)",
            outline: "none",
            fontSize: 13,
          }}
        />
        <ProfileFilter value={profileFilter} onChange={setProfileFilter} />
        <span className="mono" style={{ fontSize: 11, color: "var(--ink-4)" }}>
          {filtered.length} / {rows.length} rows
        </span>
      </div>

      {/* Table */}
      <div className="card" style={{ padding: 0, overflow: "auto", maxHeight: "calc(100vh - 280px)" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
          <thead>
            <tr style={{ background: "var(--bg-2)", position: "sticky", top: 0 }}>
              {columns.map((col) => (
                <th key={col} className="mono" style={{
                  textAlign: "left",
                  padding: "8px 10px",
                  fontSize: 10,
                  fontWeight: 600,
                  color: "var(--ink-3)",
                  textTransform: "uppercase",
                  letterSpacing: "0.06em",
                  borderBottom: "1px solid var(--line)",
                  whiteSpace: "nowrap",
                }}>
                  {col}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {filtered.slice(0, 500).map((row, idx) => (
              <tr key={row.id || idx} style={{ borderBottom: "1px solid var(--line)" }}>
                {columns.map((col) => (
                  <td key={col} style={{
                    padding: "8px 10px",
                    verticalAlign: "top",
                    fontFamily: isIdColumn(col) ? "var(--font-mono)" : "inherit",
                    color: isIdColumn(col) ? "var(--ink-4)" : "var(--ink-2)",
                    fontSize: isIdColumn(col) ? 10 : 12,
                    maxWidth: 360,
                    whiteSpace: "pre-wrap",
                    wordBreak: "break-word",
                  }}>
                    {formatCell(row[col])}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
        {filtered.length > 500 && (
          <div className="mono" style={{ padding: 10, fontSize: 11, color: "var(--ink-4)", textAlign: "center" }}>
            … truncated to 500 rows
          </div>
        )}
      </div>
    </div>
  );
}

function ProfileFilter({ value, onChange }) {
  const profiles = dbq.allProfiles();
  if (profiles.length <= 1) return null;
  return (
    <select
      value={value}
      onChange={(e) => onChange(e.target.value)}
      className="mono"
      style={{ fontSize: 12, padding: "5px 8px", border: "1px solid var(--line-2)", borderRadius: "var(--d-radius)", background: "var(--bg)" }}
    >
      <option value="all">all profiles</option>
      {profiles.map((p) => (
        <option key={p.id} value={p.id}>{p.slug}</option>
      ))}
    </select>
  );
}

function isIdColumn(col) {
  return col === "id" || col.endsWith("_id");
}

function formatCell(v) {
  if (v === null || v === undefined) return <span style={{ color: "var(--ink-4)" }}>—</span>;
  if (typeof v === "boolean") return v ? "true" : "false";
  if (typeof v === "number") return v;
  if (typeof v === "string") return v;
  if (Array.isArray(v) || typeof v === "object") {
    return <span className="mono" style={{ fontSize: 10 }}>{JSON.stringify(v)}</span>;
  }
  return String(v);
}

// For tables without a direct profile_id, walk the FK to find one for filtering.
function resolveProfileId(table, row) {
  if (table === "anti_theses") {
    const t = dbq.thesisById(row.thesis_id);
    return t?.profile_id;
  }
  if (table === "candidate_scores") {
    const c = dbq.candidateById(row.candidate_id);
    return c?.profile_id;
  }
  if (table === "candidate_anti_triggers") {
    const c = dbq.candidateById(row.candidate_id);
    return c?.profile_id;
  }
  return null;
}

Object.assign(window, { DataInspectorScreen });
