function App({ loadInfo, onReload, onLock }) {
  const [view, setView] = useState("network"); // network | departments | table
  const [filter, setFilter] = useState("*"); // "*", or dept id
  const [selection, setSelection] = useState(null); // { kind: 'tool'|'dept', id }
  const [hover, setHover] = useState(null);
  const [search, setSearch] = useState("");

  // Selection helpers
  const handleSelect = (sel) => setSelection(sel);
  const closeDetail = () => setSelection(null);

  const selectedTool =
    selection && selection.kind === "tool"
      ? TOOLS.find((t) => t.name === selection.id)
      : null;
  const selectedDept =
    selection && selection.kind === "dept"
      ? DEPARTMENTS.find((d) => d.id === selection.id)
      : null;

  // Search-driven highlight (treat search as virtual hover)
  const searchTool = useMemo(() => {
    if (!search.trim()) return null;
    const q = search.toLowerCase();
    return TOOLS.find(
      (t) =>
        t.name.toLowerCase().includes(q) ||
        (t.useCase || "").toLowerCase().includes(q)
    );
  }, [search]);

  const effectiveHover = hover || (searchTool ? { kind: "tool", id: searchTool.name } : null);

  // Expiring soon — within 180 days
  const expiringSoon = useMemo(() => {
    const now = new Date();
    return TOOLS.filter((t) => t.expires).map((t) => {
      const d = new Date(t.expires + "T12:00:00");
      const days = Math.round((d - now) / (1000 * 60 * 60 * 24));
      return { tool: t, days };
    }).sort((a, b) => a.days - b.days);
  }, []);

  return (
    <div className="app">
      {/* Top bar */}
      <header className="topbar">
        <div className="brand">
          <div className="brand-mark">Z</div>
          <div>
            <div className="brand-name">ZINTEX REMODELING</div>
            <div className="brand-sub">Tech Stack · FY2026</div>
          </div>
        </div>

        <div className="topbar-stats">
          <Stat label="Tools" value={STATS.total} />
          <Stat
            label="Monthly"
            value={`$${(STATS.totalMonthly / 1000).toFixed(1)}k`}
          />
          <Stat
            label="Annual run-rate"
            value={`$${(STATS.totalAnnual / 1000000).toFixed(2)}M`}
            highlight
          />
          <Stat
            label="Expiring < 180d"
            value={expiringSoon.filter((e) => e.days >= 0 && e.days <= 180).length}
          />
          <DataSource info={loadInfo} onReload={onReload} onLock={onLock} />
        </div>

        <div className="topbar-tools">
          <div className="search">
            <input
              type="text"
              placeholder="Search tools or use cases…"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
            {search && (
              <button className="search-clear" onClick={() => setSearch("")}>
                ×
              </button>
            )}
          </div>
          <div className="view-switch" role="tablist">
            {[
              { id: "network", label: "Network" },
              { id: "departments", label: "Departments" },
              { id: "table", label: "Table" },
            ].map((v) => (
              <button
                key={v.id}
                className={view === v.id ? "active" : ""}
                onClick={() => setView(v.id)}
              >
                {v.label}
              </button>
            ))}
          </div>
        </div>
      </header>

      {/* Department filter strip */}
      <nav className="filter-strip">
        <button
          className={`f-chip ${filter === "*" ? "active" : ""}`}
          onClick={() => setFilter("*")}
        >
          <span>All departments</span>
          <span className="f-chip-count">{STATS.total}</span>
        </button>
        {DEPARTMENTS.filter((d) => STATS.byDept[d.id]?.count > 0).map((d) => (
          <button
            key={d.id}
            className={`f-chip ${filter === d.id ? "active" : ""}`}
            style={{
              "--chip-color": deptColor(d.id, 0.78, 0.13),
            }}
            onMouseEnter={() => setHover({ kind: "dept", id: d.id })}
            onMouseLeave={() => setHover(null)}
            onClick={() => setFilter(d.id)}
          >
            <span className="f-chip-dot" />
            <span>{d.label}</span>
            <span className="f-chip-count">{STATS.byDept[d.id].count}</span>
          </button>
        ))}
      </nav>

      {/* Main */}
      <main className={`main ${selection ? "with-panel" : ""}`}>
        <div className="canvas">
          {view === "network" && (
            <NetworkView
              filter={filter === "*" ? null : filter}
              hover={effectiveHover}
              setHover={setHover}
              onSelect={handleSelect}
            />
          )}
          {view === "departments" && (
            <DepartmentsView
              filter={filter}
              onSelect={handleSelect}
              setHover={setHover}
            />
          )}
          {view === "table" && (
            <TableView
              filter={filter}
              onSelect={handleSelect}
              setHover={setHover}
            />
          )}

          {/* Expiring soon banner */}
          {view === "network" && (
            <div className="legend-card">
              <div className="legend-title">Expiring next</div>
              <div className="legend-list">
                {expiringSoon.slice(0, 4).map((e) => (
                  <button
                    key={e.tool.name}
                    className="legend-row"
                    onClick={() => handleSelect({ kind: "tool", id: e.tool.name })}
                    onMouseEnter={() => setHover({ kind: "tool", id: e.tool.name })}
                    onMouseLeave={() => setHover(null)}
                  >
                    <LogoTile tool={e.tool} size={22} />
                    <span className="lr-name">{e.tool.name}</span>
                    <span className={`lr-days ${e.days <= 90 ? "soon" : ""}`}>
                      {e.days < 0
                        ? `${-e.days}d ago`
                        : e.days === 0
                        ? "today"
                        : `${e.days}d`}
                    </span>
                  </button>
                ))}
              </div>
            </div>
          )}

          {view === "network" && (
            <div className="hint-card">
              <strong>Tip:</strong> Hover a tool to see its dept ties · click any node
              for full details.
            </div>
          )}
        </div>

        {selection && (
          <>
            {selectedTool && (
              <ToolDetail
                tool={selectedTool}
                onClose={closeDetail}
                onSelectDept={(deptId) => {
                  const d = DEPARTMENTS.find((x) => x.id === deptId);
                  if (d) setSelection({ kind: "dept", id: deptId });
                }}
              />
            )}
            {selectedDept && (
              <DepartmentDetail
                dept={selectedDept}
                onClose={closeDetail}
                onSelectTool={(name) => setSelection({ kind: "tool", id: name })}
              />
            )}
          </>
        )}
      </main>
    </div>
  );
}

function Stat({ label, value, highlight }) {
  return (
    <div className={`stat ${highlight ? "stat-hi" : ""}`}>
      <div className="stat-value">{value}</div>
      <div className="stat-label">{label}</div>
    </div>
  );
}

function DataSource({ info, onReload, onLock }) {
  const [now, setNow] = useState(Date.now());
  React.useEffect(() => {
    const t = setInterval(() => setNow(Date.now()), 30000);
    return () => clearInterval(t);
  }, []);
  if (!info) return null;
  const updated = info.updatedAt ? new Date(info.updatedAt) : null;
  const ago = updated ? Math.max(0, Math.round((now - updated.getTime()) / 1000)) : null;
  const fmtAgo = (s) => {
    if (s == null) return "—";
    if (s < 60) return s + "s ago";
    if (s < 3600) return Math.round(s / 60) + "m ago";
    return Math.round(s / 3600) + "h ago";
  };
  const sourceLabel = info.source === "sheet"
    ? "Live sheet"
    : info.source === "bundled-fallback"
    ? "Bundled (sheet unreachable)"
    : "Bundled defaults";
  const sourceClass = info.source === "sheet" ? "ds-live" : info.source === "bundled-fallback" ? "ds-warn" : "ds-bundled";
  return (
    <div className={`data-source ${sourceClass}`} title={info.error || ""}>
      <span className="ds-dot" />
      <div className="ds-text">
        <div className="ds-source">{sourceLabel}</div>
        <div className="ds-time">{updated ? `Updated ${fmtAgo(ago)}` : "From file"}</div>
      </div>
      <button className="ds-btn" onClick={onReload} title="Reload data">↻</button>
      <button className="ds-btn" onClick={onLock} title="Lock session">🔒</button>
    </div>
  );
}

window.App = App;
