// pages.jsx — Dashboard, Exception Queue, placeholder pages
const { useState: useStateP, useMemo: useMemoP } = React;

/* ---------- segmented filter ---------- */
function FilterChips({ options, value, onChange }) {
  return (
    <div className="inline-flex items-center gap-0.5 p-0.5 rounded-lg bg-zinc-100 border border-zinc-200">
      {options.map(o => {
        const on = value === o.k;
        return (
          <button key={o.k} onClick={() => onChange(o.k)}
            className={`px-2.5 py-1 rounded-md text-[12px] font-medium transition-all ${on ? "bg-white text-zinc-800 shadow-sm" : "text-zinc-500 hover:text-zinc-700"}`}>
            {o.label}{o.count != null && <span className={`ml-1.5 ${on ? "text-zinc-400" : "text-zinc-400"}`}>{o.count}</span>}
          </button>
        );
      })}
    </div>
  );
}

function SelectMini({ icon, label, value, options, onChange }) {
  return (
    <div className="relative inline-flex items-center">
      <span className="absolute left-2.5 text-zinc-400 pointer-events-none"><Icon name={icon} size={14} /></span>
      <select value={value} onChange={e => onChange(e.target.value)}
        className="appearance-none h-8 pl-8 pr-7 rounded-lg bg-white border border-zinc-200 text-[12.5px] font-medium text-zinc-700 hover:border-zinc-300 focus:outline-none focus:border-zinc-400 cursor-pointer">
        {options.map(o => <option key={o.v} value={o.v}>{o.label}</option>)}
      </select>
      <span className="absolute right-2 text-zinc-400 pointer-events-none"><Icon name="chevdown" size={13} /></span>
    </div>
  );
}

/* ---------- Dashboard ---------- */
function DashboardPage({ loading, selectedId, onSelect, density, onRefresh, onNav }) {
  const today = EXCEPTIONS.filter(e => e.status !== "resolved").slice(0, 8);
  const [filter, setFilter] = useStateP("all");
  const filtered = filter === "all" ? today : today.filter(e => e.priority === filter);
  const counts = {
    all: today.length,
    high: today.filter(e => e.priority === "high").length,
    medium: today.filter(e => e.priority === "medium").length,
  };

  return (
    <div className="p-6 space-y-6">
      {/* KPI grid */}
      <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-5 gap-3.5">
        {KPIS.map(k => <KpiCard key={k.key} kpi={k} loading={loading} />)}
      </div>

      {/* AI operational insights */}
      <InsightsPanel onAction={(p) => onNav && onNav(p)} />

      {/* Today's exceptions */}
      <div className="bg-white rounded-xl border border-zinc-200 overflow-hidden">
        <div className="flex items-center gap-3 px-5 py-3.5 border-b border-zinc-200 flex-wrap">
          <div>
            <h2 className="text-[14.5px] font-semibold text-zinc-900 tracking-tight">Today's Exceptions</h2>
            <p className="text-[11.5px] text-zinc-400 leading-tight mt-0.5">Live queue · auto-refreshes every 60s</p>
          </div>
          <div className="ml-auto flex items-center gap-2.5 flex-wrap">
            <FilterChips value={filter} onChange={setFilter}
              options={[{ k: "all", label: "All", count: counts.all }, { k: "high", label: "High", count: counts.high }, { k: "medium", label: "Medium", count: counts.medium }]} />
            <Button variant="default" size="sm" icon="refresh" onClick={onRefresh}>Refresh</Button>
          </div>
        </div>
        <ExceptionTable rows={filtered} loading={loading} selectedId={selectedId} onSelect={onSelect} density={density} />
        {!loading && (
          <div className="flex items-center justify-between px-5 py-3 border-t border-zinc-100 bg-zinc-50/40">
            <span className="text-[12px] text-zinc-400">Showing {filtered.length} of 47 open exceptions</span>
            <button onClick={() => onNav && onNav("queue")} className="text-[12.5px] font-medium inline-flex items-center gap-1" style={{ color: "var(--accent-ink)" }}>
              View full queue <Icon name="arrow_r" size={13} />
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

/* ---------- Exception Queue ---------- */
function QueuePage({ loading, selectedId, onSelect, density }) {
  const [prio, setPrio] = useStateP("all");
  const [status, setStatus] = useStateP("all");
  const [issue, setIssue] = useStateP("all");
  const [assignee, setAssignee] = useStateP("all");
  const [q, setQ] = useStateP("");
  const [sort, setSort] = useStateP("wait");

  const issues = [...new Set(EXCEPTIONS.map(e => e.issue))];

  const rows = useMemoP(() => {
    let r = EXCEPTIONS.filter(e => {
      if (prio !== "all" && e.priority !== prio) return false;
      if (status !== "all" && e.status !== status) return false;
      if (issue !== "all" && e.issue !== issue) return false;
      if (assignee === "unassigned" && e.staff) return false;
      if (assignee !== "all" && assignee !== "unassigned" && e.staff !== assignee) return false;
      if (q) {
        const hay = (e.id + e.customer.name + e.car + e.issue).toLowerCase();
        if (!hay.includes(q.toLowerCase())) return false;
      }
      return true;
    });
    r = [...r].sort((a, b) => sort === "wait" ? b.waitH - a.waitH : sort === "value" ? b.value - a.value
      : ({ high: 0, medium: 1, low: 2 })[a.priority] - ({ high: 0, medium: 1, low: 2 })[b.priority]);
    return r;
  }, [prio, status, issue, assignee, q, sort]);

  return (
    <div className="p-6 space-y-4">
      {/* stat strip */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3.5">
        {[
          { label: "Total open", value: EXCEPTIONS.filter(e=>e.status!=="resolved").length, tone: "text-zinc-900" },
          { label: "High priority", value: EXCEPTIONS.filter(e=>e.priority==="high").length, tone: "text-red-600" },
          { label: "Unassigned", value: EXCEPTIONS.filter(e=>!e.staff).length, tone: "text-orange-600" },
          { label: "Past SLA (48h+)", value: EXCEPTIONS.filter(e=>e.waitH>=48).length, tone: "text-red-600" },
        ].map(s => (
          <div key={s.label} className="bg-white rounded-xl border border-zinc-200 px-4 py-3">
            <div className="text-[11.5px] text-zinc-500">{s.label}</div>
            <div className={`text-[22px] font-semibold tabular-nums mt-0.5 ${s.tone}`}>{s.value}</div>
          </div>
        ))}
      </div>

      <div className="bg-white rounded-xl border border-zinc-200 overflow-hidden">
        {/* filter toolbar */}
        <div className="flex items-center gap-2.5 px-4 py-3 border-b border-zinc-200 flex-wrap">
          <div className="flex items-center gap-2 w-56 h-8 px-2.5 rounded-lg bg-zinc-100/80 border border-transparent focus-within:bg-white focus-within:border-zinc-300 transition-colors">
            <Icon name="search" size={15} className="text-zinc-400" />
            <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search this queue…"
              className="bg-transparent outline-none text-[12.5px] text-zinc-700 placeholder:text-zinc-400 w-full" />
          </div>
          <SelectMini icon="alert" value={prio} onChange={setPrio} options={[
            { v: "all", label: "All priorities" }, { v: "high", label: "High" }, { v: "medium", label: "Medium" }, { v: "low", label: "Low" }]} />
          <SelectMini icon="flag" value={status} onChange={setStatus} options={[
            { v: "all", label: "All statuses" }, ...Object.keys(STATUS).map(k => ({ v: k, label: STATUS[k].label }))]} />
          <SelectMini icon="filter" value={issue} onChange={setIssue} options={[
            { v: "all", label: "All issue types" }, ...issues.map(i => ({ v: i, label: i }))]} />
          <SelectMini icon="user" value={assignee} onChange={setAssignee} options={[
            { v: "all", label: "Anyone" }, { v: "unassigned", label: "Unassigned" }, ...Object.keys(STAFF).map(k => ({ v: k, label: STAFF[k].name }))]} />
          <div className="ml-auto flex items-center gap-2">
            <SelectMini icon="sliders" value={sort} onChange={setSort} options={[
              { v: "wait", label: "Sort: Waiting time" }, { v: "priority", label: "Sort: Priority" }, { v: "value", label: "Sort: Order value" }]} />
            <Button variant="default" size="sm" icon="download">Export</Button>
          </div>
        </div>

        <ExceptionTable rows={rows} loading={loading} selectedId={selectedId} onSelect={onSelect} density={density} />

        <div className="flex items-center justify-between px-5 py-3 border-t border-zinc-100 bg-zinc-50/40">
          <span className="text-[12px] text-zinc-400">{rows.length} result{rows.length !== 1 ? "s" : ""}{(prio!=="all"||status!=="all"||issue!=="all"||assignee!=="all"||q) ? " · filtered" : ""}</span>
          <div className="flex items-center gap-1">
            <button className="w-7 h-7 rounded-md flex items-center justify-center text-zinc-400 hover:bg-zinc-100" disabled><Icon name="chevleft" size={15} /></button>
            <span className="px-2.5 text-[12px] font-medium text-zinc-600">1</span>
            <button className="w-7 h-7 rounded-md flex items-center justify-center text-zinc-400 hover:bg-zinc-100"><Icon name="chevright" size={15} /></button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- placeholder for not-built pages ---------- */
function PlaceholderPage({ navKey }) {
  const item = NAV.find(n => n.key === navKey);
  return (
    <div className="p-6">
      <div className="bg-white rounded-xl border border-zinc-200 border-dashed flex flex-col items-center justify-center text-center py-20 px-8">
        <div className="flex items-center justify-center w-14 h-14 rounded-2xl mb-4 text-zinc-400 bg-zinc-100">
          <Icon name={item?.icon || "grid"} size={26} />
        </div>
        <h3 className="text-[15px] font-semibold text-zinc-700">{item?.label}</h3>
        <p className="text-[13px] text-zinc-400 mt-1.5 max-w-sm leading-relaxed">
          This section isn't part of the current prototype. The build focuses on <span className="font-medium text-zinc-600">Dashboard</span>, <span className="font-medium text-zinc-600">Exception Queue</span> and <span className="font-medium text-zinc-600">Admin Rules</span>.
        </p>
      </div>
    </div>
  );
}

Object.assign(window, { DashboardPage, QueuePage, PlaceholderPage, FilterChips, SelectMini });
