// VIEW 2 — List. Operator console.
// Sortable 13-column register with search, KPI strip, inline rollup bars,
// and a drawer on row click.
const ListView = ({ onSwitchView }) => {
  const [sel, setSel] = useState(null);
  const [q, setQ] = useState("");
  const [sort, setSort] = useState({ k: "titled", dir: -1 });
  const rollups = useMemo(() => {
    const m = {};
    D.properties.forEach((p) => { m[p.id] = rollupProperty(p.id).rollup; });
    return m;
  }, []);

  let props = D.properties.filter((p) => !q || (p.name + p.region + p.province).toLowerCase().includes(q.toLowerCase()));
  props = [...props].sort((a, b) => (a[sort.k] - b[sort.k]) * sort.dir);
  const toggle = (k) => setSort((s) => (s.k === k ? { k, dir: -s.dir } : { k, dir: -1 }));

  const totalShown = props.reduce(
    (t, p) => ({
      titled: t.titled + p.titled,
      owned: t.owned + p.owned,
      rented: t.rented + p.rented,
      parcels: t.parcels + p.parcels,
      assessment: t.assessment + p.assessment,
    }),
    { titled: 0, owned: 0, rented: 0, parcels: 0, assessment: 0 }
  );

  return (
    <div style={{ minHeight: "100%", background: "var(--paper)", fontSize: 13 }}>
      <div style={{ padding: "20px 32px", borderBottom: "1px solid var(--ink)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 18 }}>
          <div className="serif" style={{ fontSize: 26 }}>Monette · Register</div>
          <div style={{ fontFamily: '"JetBrains Mono", monospace', fontSize: 10, letterSpacing: "0.1em", color: "var(--mute)" }}>CCAA DAY 0 · APR 21, 2026 · ASSET REGISTER</div>
        </div>
        <div style={{ display: "flex", gap: 12 }}>
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search…" style={{
            fontFamily: "inherit", fontSize: 12, padding: "8px 10px",
            border: "1px solid var(--rule-2)", background: "var(--paper)", width: 240,
          }} />
          <button className="btn">Export CSV</button>
          <button className="btn btn-dark">Submit tip</button>
        </div>
      </div>
      <HeadlineTicker />
      <div style={{ padding: "16px 32px", background: "var(--paper-2)", borderBottom: "1px solid var(--ink)", display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 24 }}>
        {[
          ["Properties", props.length],
          ["Titled ac", fmt(totalShown.titled)],
          ["Owned",     fmt(totalShown.owned)],
          ["Parcels",   fmt(totalShown.parcels)],
          ["Assessed",  fmtM(totalShown.assessment)],
        ].map(([l, v]) => (
          <div key={l}>
            <div style={{ fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--mute)" }}>{l}</div>
            <div className="serif" style={{ fontSize: 28, lineHeight: 1, marginTop: 4 }}>{v}</div>
          </div>
        ))}
      </div>
      <div style={{ padding: "0 32px 32px" }}>
        <table style={{ width: "100%", borderCollapse: "collapse" }}>
          <thead>
            <tr style={{ borderBottom: "2px solid var(--ink)" }}>
              {[
                ["#"],
                ["Property", "name"],
                ["Prov", "province"],
                ["Parcels", "parcels"],
                ["Titled", "titled"],
                ["Owned", "owned"],
                ["Rented", "rented"],
                ["Sold q", "sold"],
                ["For sale q", "forSale"],
                ["Seeded q", "seeded"],
                ["Sprayed q", "sprayed"],
                ["2025", "crop25"],
                ["Rollup"],
              ].map(([l, k]) => (
                <th key={l} onClick={() => k && toggle(k)} style={{
                  padding: "10px 8px",
                  textAlign: ["Parcels", "Titled", "Owned", "Rented", "Sold q", "For sale q", "Seeded q", "Sprayed q"].includes(l) ? "right" : "left",
                  color: "var(--mute)", cursor: k ? "pointer" : "default", fontSize: 10,
                  letterSpacing: "0.1em", textTransform: "uppercase", fontWeight: 500,
                }}>
                  {l}
                  {sort.k === k && <span style={{ marginLeft: 4, color: "var(--ink)" }}>{sort.dir === 1 ? "↑" : "↓"}</span>}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {props.map((p, i) => {
              const r = rollups[p.id];
              return (
                <tr key={p.id} onClick={() => setSel(p)} style={{ borderBottom: "1px solid var(--rule)", cursor: "pointer" }}
                    onMouseOver={(e) => (e.currentTarget.style.background = "var(--paper-2)")}
                    onMouseOut={(e) => (e.currentTarget.style.background = "")}>
                  <td style={{ padding: "10px 8px", fontFamily: '"JetBrains Mono", monospace', color: "var(--mute)" }}>{String(i + 1).padStart(2, "0")}</td>
                  <td style={{ padding: "10px 8px" }}>
                    <div style={{ fontWeight: 500 }}>{p.name}</div>
                    <div style={{ fontFamily: '"JetBrains Mono", monospace', fontSize: 10, color: "var(--mute)" }}>{p.region}</div>
                  </td>
                  <td style={{ padding: "10px 8px", fontFamily: '"JetBrains Mono", monospace' }}>{p.province}</td>
                  <td style={{ padding: "10px 8px", textAlign: "right", fontFamily: '"JetBrains Mono", monospace' }}>{p.parcels}</td>
                  <td style={{ padding: "10px 8px", textAlign: "right", fontFamily: '"JetBrains Mono", monospace' }}>{fmt(p.titled)}</td>
                  <td style={{ padding: "10px 8px", textAlign: "right", fontFamily: '"JetBrains Mono", monospace' }}>{fmt(p.owned)}</td>
                  <td style={{ padding: "10px 8px", textAlign: "right", fontFamily: '"JetBrains Mono", monospace', color: "var(--mute)" }}>{fmt(p.rented)}</td>
                  <td style={{ padding: "10px 8px", textAlign: "right", fontFamily: '"JetBrains Mono", monospace', color: OWN.sold.color }}>{r.sold}</td>
                  <td style={{ padding: "10px 8px", textAlign: "right", fontFamily: '"JetBrains Mono", monospace', color: LIST["listed-for-sale"].color }}>{r.forSale}</td>
                  <td style={{ padding: "10px 8px", textAlign: "right", fontFamily: '"JetBrains Mono", monospace', color: "#4e6a30" }}>{r.seeded}</td>
                  <td style={{ padding: "10px 8px", textAlign: "right", fontFamily: '"JetBrains Mono", monospace', color: "#b48638" }}>{r.sprayed}</td>
                  <td style={{ padding: "10px 8px" }}>{p.crops2025[0]?.[0] || "—"}</td>
                  <td style={{ padding: "10px 8px", width: 110 }}><RollupBar rollup={r} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      <PropertyDrawer prop={sel} onClose={() => setSel(null)} onZoomMap={(p) => { setSel(null); onSwitchView && onSwitchView("map", p.id); }} />
    </div>
  );
};
window.ListView = ListView;
