// Department drill-in view + Table view

function DepartmentsView({ filter, onSelect, setHover }) {
  const liveDepts = DEPARTMENTS.filter((d) => STATS.byDept[d.id]?.count > 0);
  const filtered = filter && filter !== "*"
    ? liveDepts.filter((d) => d.id === filter)
    : liveDepts;

  return (
    <div className="dept-grid">
      {filtered.map((d) => {
        const tools = TOOLS.filter((t) => t.dept === d.id);
        const color = deptColor(d.id, 0.72, 0.13);
        return (
          <div
            key={d.id}
            className="dept-card"
            style={{ "--dept-color": color }}
          >
            <header className="dept-card-head">
              <div className="dept-card-title">
                <span className="dept-pill" style={{ background: color }}>
                  {d.short}
                </span>
                <h3>{d.label}</h3>
              </div>
              <div className="dept-card-stats">
                <span className="num">{STATS.byDept[d.id].count}</span>
                <span className="lbl">tools</span>
                <span className="num">
                  ${(STATS.byDept[d.id].annual / 1000).toFixed(0)}k
                </span>
                <span className="lbl">annual</span>
              </div>
            </header>
            <div className="dept-tools">
              {tools.map((t) => (
                <button
                  key={t.name}
                  className="dept-tool-row"
                  onMouseEnter={() => setHover({ kind: "tool", id: t.name })}
                  onMouseLeave={() => setHover(null)}
                  onClick={() => onSelect({ kind: "tool", id: t.name })}
                >
                  <LogoTile tool={t} size={36} />
                  <div className="dept-tool-info">
                    <div className="dept-tool-name">{t.name}</div>
                    <div className="dept-tool-use">{t.useCase || "—"}</div>
                  </div>
                  <div className="dept-tool-price">
                    <div className="dept-tool-annual">
                      ${t.annual.toLocaleString(undefined, { maximumFractionDigits: 0 })}
                    </div>
                    <div className="dept-tool-monthly">
                      ${t.monthly.toLocaleString(undefined, { maximumFractionDigits: 0 })}/mo
                    </div>
                  </div>
                  {t.connects && t.connects.filter((x) => x !== t.dept).length > 0 && (
                    <div className="dept-tool-connects">
                      {t.connects
                        .filter((x) => x !== t.dept)
                        .map((c) => {
                          const dd = DEPARTMENTS.find((x) => x.id === c);
                          if (!dd) return null;
                          return (
                            <span
                              key={c}
                              className="connect-chip"
                              style={{ color: deptColor(c, 0.78, 0.13) }}
                              title={c}
                            >
                              {dd.short}
                            </span>
                          );
                        })}
                    </div>
                  )}
                </button>
              ))}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function TableView({ filter, onSelect, setHover }) {
  const [sort, setSort] = useState({ key: "annual", dir: -1 });
  const rows = useMemo(() => {
    let r = [...TOOLS];
    if (filter && filter !== "*") {
      r = r.filter(
        (t) => t.dept === filter || (t.connects || []).includes(filter)
      );
    }
    r.sort((a, b) => {
      const av = a[sort.key];
      const bv = b[sort.key];
      if (typeof av === "number") return (av - bv) * sort.dir;
      return String(av).localeCompare(String(bv)) * sort.dir;
    });
    return r;
  }, [filter, sort]);

  const setSortKey = (key) =>
    setSort((s) => ({ key, dir: s.key === key ? -s.dir : -1 }));

  const Hd = ({ k, children, align }) => (
    <th
      onClick={() => setSortKey(k)}
      style={{ textAlign: align || "left", cursor: "pointer" }}
    >
      {children}
      {sort.key === k && (
        <span className="sort-arrow">{sort.dir === 1 ? " ▲" : " ▼"}</span>
      )}
    </th>
  );

  return (
    <div className="table-wrap">
      <table className="stack-table">
        <thead>
          <tr>
            <Hd k="name">Tool</Hd>
            <Hd k="useCase">Use case</Hd>
            <Hd k="dept">Department</Hd>
            <Hd k="monthly" align="right">Monthly</Hd>
            <Hd k="annual" align="right">Annual</Hd>
            <th>Billing / notes</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((t) => (
            <tr
              key={t.name}
              onClick={() => onSelect({ kind: "tool", id: t.name })}
              onMouseEnter={() => setHover({ kind: "tool", id: t.name })}
              onMouseLeave={() => setHover(null)}
            >
              <td>
                <div className="t-name-cell">
                  <LogoTile tool={t} size={28} />
                  <span>{t.name}</span>
                </div>
              </td>
              <td className="muted">{t.useCase || "—"}</td>
              <td>
                <span
                  className="dept-tag"
                  style={{ color: deptColor(t.dept, 0.78, 0.13) }}
                >
                  {t.dept}
                </span>
              </td>
              <td className="num-cell">
                ${t.monthly.toLocaleString(undefined, { maximumFractionDigits: 2 })}
              </td>
              <td className="num-cell">
                ${t.annual.toLocaleString(undefined, { maximumFractionDigits: 0 })}
              </td>
              <td className="muted small">{t.billing || "Monthly"}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

window.DepartmentsView = DepartmentsView;
window.TableView = TableView;
