/* === Work items — typed work, optional stages, list or timeline view === */

const { useState: useStateWork } = React;

function WorkItems() {
  const items = window.WORK_ITEMS;
  const inFlight = items.filter(w => !w.completedDate);
  const completed = items.filter(w => w.completedDate);
  const stuck = inFlight.filter(w => w.stuckSince || (w.stageStatus && w.stageStatus.includes("stuck"))).length;

  const publishedFY = completed.filter(w => window.inCurrentFY(w.completedDate));

  const [showCompleted, setShowCompleted] = useStateWork(false);
  const [view, setView] = useStateWork("list"); // "list" | "timeline"
  const [ownerFilter, setOwnerFilter] = useStateWork("all");
  // ?item=W-07 deep-links straight to a work item's detail panel.
  const [selectedId, setSelectedId] = useStateWork(() => new URLSearchParams(location.search).get("item"));
  const [showNew, setShowNew] = useStateWork(false);
  const me = window.Store.session();
  const canCreate = me && me.role !== "viewer";

  const owners = [...new Set(items.map(w => w.owner).filter(Boolean))].sort();

  // Group all visible items by type
  const visible = (showCompleted ? items : inFlight)
    .filter(w => ownerFilter === "all" || w.owner === ownerFilter);
  const byType = {};
  for (const w of visible) (byType[w.type] = byType[w.type] || []).push(w);

  return (
    <div>
      <div className="work-head" data-comment-anchor="work-head">
        <div className="row" style={{ gap: 8 }}>
          <ViewToggle value={view} onChange={setView} />
          <select value={ownerFilter} onChange={e => setOwnerFilter(e.target.value)}
                  style={{ padding: "5px 8px", borderRadius: 5, border: "1px solid var(--border)",
                           background: ownerFilter === "all" ? "var(--surface)" : "var(--navy-bg)",
                           color: ownerFilter === "all" ? "var(--ink-2)" : "var(--navy)",
                           font: "500 11px/1.2 var(--mono)" }}>
            <option value="all">All owners</option>
            {owners.map(o => <option key={o} value={o}>{o}</option>)}
          </select>
          <label className="row" style={{ gap: 6, fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-2)", cursor: "pointer", userSelect: "none" }}>
            <input type="checkbox" checked={showCompleted} onChange={e => setShowCompleted(e.target.checked)} />
            Show completed
          </label>
        </div>
        {canCreate ? (
          <button className="btn btn--primary" onClick={() => setShowNew(true)}>+ New work item</button>
        ) : null}
      </div>

      {/* Tab summary */}
      <div className="tab-summary">
        <SumStat label="In flight" value={inFlight.length} />
        <SumStat label="Published this FY" value={publishedFY.length} accent="green" />
        <SumStat label="Stuck > 30 days" value={stuck} accent={stuck > 0 ? "yellow" : null} />
        <SumStat label="Completed total" value={completed.length} muted />
      </div>

      {selectedId ? <WorkPanel id={selectedId} onClose={() => setSelectedId(null)} /> : null}
      {showNew ? <NewWorkForm onClose={() => setShowNew(false)} onCreated={(id) => setSelectedId(id)} /> : null}

      {view === "timeline" ? (
        <FirmnessTimeline
          fuzziness="medium"
          title="In-flight work"
          sub="Each row = a work item · core bar runs to nominal due date · soft extension shows date confidence."
          items={window.workItemsToTimeline(visible.filter(w => !w.completedDate))}
        />
      ) : (
        <>
          {Object.entries(byType).map(([type, ws]) => {
            const live = ws.filter(w => !w.completedDate).length;
            const done = ws.filter(w => w.completedDate).length;
            return (
              <div key={type} style={{ marginBottom: 22 }}>
                <div style={{ display: "flex", alignItems: "baseline", gap: 8, margin: "6px 0 6px" }}>
                  <span className="eyebrow">{type}</span>
                  <span style={{ flex: 1, height: 1, background: "var(--rule)", marginLeft: 8 }}></span>
                  <span className="mono faint" style={{ fontSize: 11 }}>
                    {live} in flight{done > 0 ? ` · ${done} completed` : ""}
                  </span>
                </div>
                <div className="card">
                  {ws.map(w => <WorkRow key={w.id} w={w} onOpen={() => setSelectedId(w.id)} />)}
                </div>
              </div>
            );
          })}
        </>
      )}
    </div>
  );
}

function ViewToggle({ value, onChange }) {
  return (
    <div style={{
      display: "inline-flex", border: "1px solid var(--border)", borderRadius: 5, overflow: "hidden",
      fontFamily: "var(--mono)", fontSize: 11, background: "var(--surface)",
    }}>
      {[
        { id: "list", label: "List" },
        { id: "timeline", label: "Timeline" },
      ].map((o, i) => (
        <button key={o.id}
                onClick={() => onChange(o.id)}
                style={{
                  padding: "5px 11px",
                  background: value === o.id ? "var(--navy)" : "transparent",
                  color: value === o.id ? "white" : "var(--ink-2)",
                  borderLeft: i > 0 ? "1px solid var(--border)" : "none",
                  cursor: "pointer", fontFamily: "var(--mono)", fontSize: 11, fontWeight: 500,
                }}>{o.label}</button>
      ))}
    </div>
  );
}

function SumStat({ label, value, accent, muted }) {
  const fg = accent === "green" ? "var(--green)" :
             accent === "yellow" ? "var(--yellow)" :
             accent === "red" ? "var(--red)" :
             muted ? "var(--ink-mute)" : "var(--ink)";
  return (
    <div className="sum-stat">
      <div className="eyebrow">{label}</div>
      <div style={{ fontFamily: "var(--serif)", fontSize: 28, fontWeight: 600, lineHeight: 1, marginTop: 6, color: fg }}>{value}</div>
    </div>
  );
}

function WorkRow({ w, onOpen }) {
  const isCompleted = !!w.completedDate;
  const isStuck = w.stuckSince || (w.status && w.status.includes("blocked"));
  return (
    <div className={`list-row ${isCompleted ? "list-row--dim" : ""}`}
         onClick={onOpen}
         style={{
           borderLeft: isCompleted ? "3px solid transparent" :
                       isStuck ? "3px solid var(--red)" : "3px solid transparent",
           paddingLeft: 14,
           cursor: onOpen ? "pointer" : "default",
         }}>
      <div>
        <span className="mono faint" style={{ fontSize: 11 }}>{w.id}</span>
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontWeight: 600, fontSize: 13, color: isCompleted ? "var(--ink-2)" : "var(--ink)", textDecoration: isCompleted ? "none" : "none" }}>{w.title}</div>
        <div style={{ marginTop: 6, display: "flex", flexWrap: "wrap", gap: 6, alignItems: "center" }}>
          {w.milestones.map(id => <ODAChip key={id} id={id} />)}
          {w.oda.map(id => <Chip key={id} kind="soft">{id}</Chip>)}
          {w.state ? <Chip kind="ghost">{w.state}</Chip> : null}
          <span className="mono faint" style={{ fontSize: 11 }}>· owner {w.owner}</span>
          <span className="mono" style={{ fontSize: 11, color: "var(--ink-2)" }}>· {w.status}</span>
        </div>
        {!isCompleted && w.stages && w.stages.length > 0 ? (
          <div style={{ marginTop: 8 }}>
            <div className="stage-pipeline">
              {w.stages.map((s, i) => (
                <div key={i} className={`stage-pipeline__cell ${
                  w.stageStatus[i] === "done" ? "is-done" :
                  w.stageStatus[i] === "current" ? "is-current" :
                  w.stageStatus[i] === "stuck" ? "is-stuck" : ""
                }`} title={`${s}: ${w.stageStatus[i]}`}></div>
              ))}
            </div>
            <div style={{ marginTop: 4, display: "flex", justifyContent: "space-between", fontFamily: "var(--mono)", fontSize: 10, color: "var(--ink-faint)" }}>
              <span>{w.stages.map((s, i) => w.stageStatus[i] === "current" || w.stageStatus[i] === "stuck" ? `↑ ${s}` : null).filter(Boolean).join(" · ")}</span>
              {w.stuckSince ? <span style={{ color: "var(--yellow)" }}>stuck since {w.stuckSince}</span> : null}
            </div>
          </div>
        ) : null}
      </div>
      <div style={{ textAlign: "right" }}>
        <div className="mono" style={{ fontSize: 12, color: "var(--ink-2)" }}>
          {isCompleted ? <span>{w.completedDate}</span> : w.due}
        </div>
        <div style={{ marginTop: 4 }}>
          {isCompleted ? (
            <span className="mono" style={{ fontSize: 10, fontWeight: 600, color: "var(--green)", letterSpacing: ".12em" }}>COMPLETED</span>
          ) : <Firmness kind={w.firmness} />}
        </div>
      </div>
      <div>
        <span className="chip chip--soft">{w.terminal}</span>
      </div>
    </div>
  );
}

Object.assign(window, { WorkItems, WorkRow });
