/* ============================================================
   FacilityOS — Work Orders list screen
   ============================================================ */
window.Screens = window.Screens || {};

function FilterSelect({ icon, label, value, options, onChange }) {
  return (
    <label style={{ position: "relative", display: "inline-flex", alignItems: "center" }}>
      <Icon name={icon} size={15} style={{ position: "absolute", left: 11, color: "var(--text-faint)", pointerEvents: "none" }} />
      <select value={value} onChange={(e) => onChange(e.target.value)} style={{
        appearance: "none", height: 38, padding: "0 30px 0 33px", borderRadius: "var(--radius-sm)",
        border: "1px solid var(--border-strong)", background: value !== "all" ? UI.tint("--accent", 10) : "var(--surface)",
        color: value !== "all" ? "var(--accent-strong)" : "var(--text)", fontSize: 13, fontWeight: 600,
        fontFamily: "var(--font-sans)", cursor: "pointer", outline: "none", maxWidth: 180,
      }}>
        <option value="all">{label}: All</option>
        {options.map((o) => <option key={o.v} value={o.v}>{o.l}</option>)}
      </select>
      <Icon name="chevDown" size={15} style={{ position: "absolute", right: 9, color: "var(--text-faint)", pointerEvents: "none" }} />
    </label>
  );
}

function Th({ children, sortKey, sort, setSort, style, align, className }) {
  const active = sortKey && sort && sort.key === sortKey;
  return (
    <th className={className} onClick={sortKey && setSort ? () => setSort({ key: sortKey, dir: active && sort.dir === "asc" ? "desc" : "asc" }) : undefined}
      style={{ position: "sticky", top: 0, zIndex: 2, background: "var(--surface-2)", textAlign: align || "left", padding: "11px 14px",
        fontSize: 11.5, fontWeight: 700, letterSpacing: ".04em", textTransform: "uppercase", color: "var(--text-faint)",
        cursor: sortKey ? "pointer" : "default", whiteSpace: "nowrap", userSelect: "none", borderBottom: "1px solid var(--border)", ...style }}>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 5, justifyContent: align === "right" ? "flex-end" : "flex-start" }}>
        {children}
        {sortKey && <Icon name={active ? (sort.dir === "asc" ? "arrowUp" : "arrowDown") : "chevDown"} size={12} style={{ opacity: active ? 1 : 0.3 }} />}
      </span>
    </th>
  );
}

Screens.WorkOrders = function WorkOrders({ go, search }) {
  const DB = window.DB;
  const { Button, StatusBadge, PriorityPill, Avatar } = UI;
  const [tab, setTab] = useState("all");
  const [fPriority, setFPriority] = useState("all");
  const [fFacility, setFFacility] = useState("all");
  const [fAssignee, setFAssignee] = useState("all");
  const [sort, setSort] = useState({ key: "id", dir: "desc" });
  const [sel, setSel] = useState({});

  const tabMatch = (w) => tab === "all" ? true : tab === "open" ? w.status === "open" : tab === "in_progress" ? w.status === "in_progress" : w.status === "completed";
  const q = (search || "").toLowerCase();

  let rows = DB.workOrders.filter((w) =>
    tabMatch(w) &&
    (fPriority === "all" || w.priority === fPriority) &&
    (fFacility === "all" || w.facility === fFacility) &&
    (fAssignee === "all" || w.assignee === fAssignee) &&
    (!q || w.title.toLowerCase().includes(q) || w.id.toLowerCase().includes(q) || w.asset.toLowerCase().includes(q))
  );
  rows = [...rows].sort((a, b) => {
    let av, bv;
    if (sort.key === "priority") { av = DB.PRIORITY[a.priority].rank; bv = DB.PRIORITY[b.priority].rank; }
    else if (sort.key === "facility") { av = DB.facById(a.facility).name; bv = DB.facById(b.facility).name; }
    else { av = a[sort.key]; bv = b[sort.key]; }
    if (av < bv) return sort.dir === "asc" ? -1 : 1;
    if (av > bv) return sort.dir === "asc" ? 1 : -1;
    return 0;
  });

  const counts = {
    all: DB.workOrders.length,
    open: DB.workOrders.filter((w) => w.status === "open").length,
    in_progress: DB.workOrders.filter((w) => w.status === "in_progress").length,
    completed: DB.workOrders.filter((w) => w.status === "completed").length,
  };
  const selIds = Object.keys(sel).filter((k) => sel[k]);
  const allSel = rows.length > 0 && rows.every((r) => sel[r.id]);
  const toggleAll = () => { const n = {}; if (!allSel) rows.forEach((r) => (n[r.id] = true)); setSel(n); };

  const overdue = (w) => ["May 30", "May 29", "May 28"].includes(w.due) && w.status !== "completed";

  return (
    <div className="page fade-up">
      {/* Tabs + new button */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16, flexWrap: "wrap" }}>
        <UI.Segmented value={tab} onChange={setTab} counts={counts}
          options={[{ key: "all", label: "All" }, { key: "open", label: "Open" }, { key: "in_progress", label: "In Progress" }, { key: "completed", label: "Completed" }]} />
        <Button variant="primary" icon="plus" style={{ marginLeft: "auto" }}>New Work Order</Button>
      </div>

      {/* Filter bar */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14, flexWrap: "wrap" }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 7, fontSize: 12.5, fontWeight: 600, color: "var(--text-faint)" }}><Icon name="filter" size={15} /> Filter</span>
        <FilterSelect icon="zap" label="Priority" value={fPriority} onChange={setFPriority} options={Object.entries(DB.PRIORITY).map(([k, v]) => ({ v: k, l: v.label }))} />
        <FilterSelect icon="building" label="Facility" value={fFacility} onChange={setFFacility} options={DB.facilities.map((f) => ({ v: f.id, l: f.name }))} />
        <FilterSelect icon="user" label="Assignee" value={fAssignee} onChange={setFAssignee} options={DB.techs.filter(t=>t.id!=="u0").map((t) => ({ v: t.id, l: t.name }))} />
        {(fPriority !== "all" || fFacility !== "all" || fAssignee !== "all") && (
          <button onClick={() => { setFPriority("all"); setFFacility("all"); setFAssignee("all"); }} style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12.5, fontWeight: 600, color: "var(--text-muted)", background: "transparent", border: "none", cursor: "pointer" }}>
            <Icon name="x" size={14} /> Clear
          </button>
        )}
        <span style={{ marginLeft: "auto", fontSize: 12.5, color: "var(--text-faint)" }} className="tnum">{rows.length} of {DB.workOrders.length}</span>
      </div>

      {/* Bulk toolbar */}
      {selIds.length > 0 && (
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12, padding: "9px 14px", borderRadius: "var(--radius-sm)", background: UI.tint("--accent", 10), border: `1px solid ${UI.tint("--accent", 30)}`, animation: "fadeIn .2s ease" }}>
          <span style={{ fontSize: 13, fontWeight: 650, color: "var(--accent-strong)" }}>{selIds.length} selected</span>
          <div style={{ display: "flex", gap: 6, marginLeft: 4 }}>
            <Button size="sm" variant="default" icon="user">Assign</Button>
            <Button size="sm" variant="default" icon="zap">Set priority</Button>
            <Button size="sm" variant="default" icon="check">Mark complete</Button>
          </div>
          <button onClick={() => setSel({})} style={{ marginLeft: "auto", background: "transparent", border: "none", cursor: "pointer", color: "var(--text-muted)", display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12.5, fontWeight: 600 }}><Icon name="x" size={14} /> Clear</button>
        </div>
      )}

      {/* Table */}
      <UI.Card pad={false} style={{ overflow: "hidden" }}>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 880 }}>
            <thead>
              <tr>
                <th style={{ position: "sticky", top: 0, zIndex: 2, background: "var(--surface-2)", padding: "11px 14px", borderBottom: "1px solid var(--border)", width: 44 }}>
                  <Checkbox checked={allSel} onChange={toggleAll} />
                </th>
                <Th sortKey="id" sort={sort} setSort={setSort}>ID</Th>
                <Th sortKey="title" sort={sort} setSort={setSort}>Title</Th>
                <Th sortKey="facility" sort={sort} setSort={setSort} className="hide-md">Facility</Th>
                <Th sortKey="priority" sort={sort} setSort={setSort}>Priority</Th>
                <Th sortKey="status" sort={sort} setSort={setSort}>Status</Th>
                <Th className="hide-sm">Assignee</Th>
                <Th sortKey="due" sort={sort} setSort={setSort} align="right">Due</Th>
                <th style={{ position: "sticky", top: 0, zIndex: 2, background: "var(--surface-2)", borderBottom: "1px solid var(--border)", width: 40 }}></th>
              </tr>
            </thead>
            <tbody>
              {rows.map((w, i) => {
                const f = DB.facById(w.facility);
                const od = overdue(w);
                return (
                  <tr key={w.id} onClick={() => go("wo-detail", { id: w.id })}
                    style={{ cursor: "pointer", background: sel[w.id] ? UI.tint("--accent", 8) : (i % 2 ? "var(--surface)" : "color-mix(in oklch, var(--surface-2) 45%, var(--surface))"), transition: "background .12s" }}
                    onMouseEnter={(e) => { if (!sel[w.id]) e.currentTarget.style.background = "var(--surface-2)"; }}
                    onMouseLeave={(e) => { if (!sel[w.id]) e.currentTarget.style.background = i % 2 ? "var(--surface)" : "color-mix(in oklch, var(--surface-2) 45%, var(--surface))"; }}>
                    <td style={{ padding: "0 14px" }} onClick={(e) => e.stopPropagation()}>
                      <Checkbox checked={!!sel[w.id]} onChange={() => setSel({ ...sel, [w.id]: !sel[w.id] })} />
                    </td>
                    <td style={{ padding: "12px 14px" }}><span className="mono" style={{ fontSize: 12, fontWeight: 600, color: "var(--text-muted)" }}>{w.id}</span></td>
                    <td style={{ padding: "12px 14px", maxWidth: 280 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{w.title}</div>
                      <div style={{ fontSize: 11.5, color: "var(--text-faint)", marginTop: 1, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{w.asset} · {w.category}</div>
                    </td>
                    <td className="hide-md" style={{ padding: "12px 14px", fontSize: 13, color: "var(--text-muted)", whiteSpace: "nowrap" }}>{f.name}</td>
                    <td style={{ padding: "12px 14px" }}><PriorityPill priority={w.priority} /></td>
                    <td style={{ padding: "12px 14px" }}><StatusBadge status={w.status} /></td>
                    <td className="hide-sm" style={{ padding: "12px 14px" }}><span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}><Avatar id={w.assignee} size={26} /><span style={{ fontSize: 13, fontWeight: 500, whiteSpace: "nowrap" }}>{DB.techById(w.assignee).name}</span></span></td>
                    <td style={{ padding: "12px 14px", textAlign: "right", whiteSpace: "nowrap" }}>
                      <span className="mono tnum" style={{ fontSize: 12.5, fontWeight: 600, color: od ? "var(--c-critical)" : "var(--text-muted)" }}>{od && "⚠ "}{w.due}</span>
                    </td>
                    <td style={{ padding: "0 8px", textAlign: "center", color: "var(--text-faint)" }}><Icon name="chevRight" size={16} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {rows.length === 0 && (
          <div style={{ padding: "56px 20px", textAlign: "center" }}>
            <div style={{ width: 52, height: 52, borderRadius: 14, background: "var(--surface-3)", display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--text-faint)" }}><Icon name="search" size={24} /></div>
            <div style={{ marginTop: 14, fontWeight: 650, fontSize: 15 }}>No work orders match</div>
            <div style={{ marginTop: 4, fontSize: 13, color: "var(--text-faint)" }}>Try clearing filters or changing the tab.</div>
          </div>
        )}
      </UI.Card>
    </div>
  );
};

function Checkbox({ checked, onChange }) {
  return (
    <span onClick={(e) => { e.stopPropagation(); onChange(); }} style={{
      width: 18, height: 18, borderRadius: 5, display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer",
      border: `1.5px solid ${checked ? "var(--accent)" : "var(--border-strong)"}`, background: checked ? "var(--accent)" : "transparent",
      color: "var(--accent-fg)", transition: "all .12s",
    }}>
      {checked && <Icon name="check" size={13} stroke={3} />}
    </span>
  );
}
window.FilterSelect = FilterSelect;
