/* eslint-disable */
// Staffing Partner v2 — Workers roster view (soft aesthetic)

(function () {
const {
  Icon, Avatar,
  V2, V2Card, V2Button, V2Badge, V2TextField, V2PillToggle,
  V2SectionHeader, V2StatTile, V2TableShell, V2TH, V2StatusPill,
} = window;
const { WORKERS, JOBS, CLIENTS, AGENTS } = window;
const { useState, useMemo } = React;

function money(n) {
  return n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function V2TimecardChip({ status }) {
  const tone = { Approved: "green", Pending: "yellow", Disputed: "red" }[status] || "neutral";
  return <V2Badge tone={tone} dot>{status}</V2Badge>;
}

function V2HoursCell({ hours }) {
  return (
    <span style={{
      fontVariantNumeric: "tabular-nums", fontWeight: 600,
      fontSize: 14, color: V2.text,
    }}>{hours.toLocaleString()}<span style={{ fontSize: 11, color: V2.textDim, fontWeight: 500, marginLeft: 2 }}>h</span></span>
  );
}

function V2WorkersView({ tweaks }) {
  const [q, setQ] = useState("");
  const [timeframe, setTimeframe] = useState("lastMonth");
  const [statusFilter, setStatusFilter] = useState("all");

  const filtered = useMemo(() => {
    const qL = q.toLowerCase().trim();
    return WORKERS.filter(w => {
      if (statusFilter !== "all" && w.status !== statusFilter) return false;
      if (!qL) return true;
      const job = JOBS.find(j => j.id === w.jobId);
      return [w.name, job?.title || ""].some(s => s.toLowerCase().includes(qL));
    });
  }, [q, statusFilter]);

  const active = WORKERS.filter(w => w.status === "Active");
  const totalHoursMo = active.reduce((s, w) => s + w.hours.lastMonth, 0);
  const totalEarningsMo = active.reduce((s, w) => s + w.hours.lastMonth * w.spPayRate, 0);
  const pendingTimecards = WORKERS.filter(w => w.timecard !== "Approved").length;

  const timeframes = [
    { value: "lastWeek",    label: "Last week" },
    { value: "lastMonth",   label: "Last month" },
    { value: "lastQuarter", label: "Last quarter" },
    { value: "ytd",         label: "YTD" },
  ];

  return (
    <div>
      <V2SectionHeader
        eyebrow="Workers"
        title="Active roster"
        sub="Every worker you've placed. Verify hours, track SP pay rates, and forecast earnings."
        actions={<V2Button variant="secondary" size="lg" iconStart="document-download">Export roster</V2Button>}
      />

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, marginBottom: 24 }}>
        <V2StatTile label="Active workers" value={active.length} sub={`${WORKERS.length - active.length} inactive`} tone="green" icon="user-check" />
        <V2StatTile label="Hours last month" value={totalHoursMo.toLocaleString()} sub="across active roster" tone="blue" icon="clock" />
        <V2StatTile label="Earnings last month" value={`$${Math.round(totalEarningsMo).toLocaleString()}`} sub="SP pay × hours" tone="purple" icon="document-text" />
        <V2StatTile label="Timecards pending" value={pendingTimecards} sub="need review" tone="yellow" icon="alert-triangle" />
      </div>

      <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap", marginBottom: 18 }}>
        <div style={{ flex: "0 0 280px" }}>
          <V2TextField placeholder="Search workers…" value={q} onChange={e => setQ(e.target.value)} iconStart="search" />
        </div>
        <V2PillToggle value={statusFilter} onChange={setStatusFilter}
          options={[
            { value: "all",      label: "All" },
            { value: "Active",   label: "Active" },
            { value: "On leave", label: "On leave" },
            { value: "Ended",    label: "Ended" },
          ]} />
        <div style={{ marginLeft: "auto", display: "flex", gap: 8, alignItems: "center" }}>
          <span style={{ fontSize: 12, color: V2.textDim, fontWeight: 500 }}>Hours</span>
          <V2PillToggle value={timeframe} onChange={setTimeframe} options={timeframes} />
        </div>
      </div>

      <V2TableShell>
        <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "var(--font-body)" }}>
          <thead>
            <tr>
              <V2TH>Worker</V2TH>
              <V2TH>Job / Client</V2TH>
              <V2TH>Status</V2TH>
              <V2TH right>SP pay rate</V2TH>
              <V2TH>Hours ({timeframes.find(t => t.value === timeframe).label})</V2TH>
              <V2TH right>Earnings</V2TH>
              <V2TH>Timecard</V2TH>
            </tr>
          </thead>
          <tbody>
            {filtered.map((w, i) => {
              const job = JOBS.find(j => j.id === w.jobId);
              const client = CLIENTS[job.client];
              const hours = w.hours[timeframe];
              const earnings = hours * w.spPayRate;
              return (
                <tr key={w.id} style={{
                  borderBottom: i < filtered.length - 1 ? `1px solid ${V2.hairlineSoft}` : "none",
                }}
                onMouseEnter={e => e.currentTarget.style.background = "#FAFAFA"}
                onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                  <td style={{ padding: "16px 18px" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <Avatar name={w.name} size={36} bg={`var(--${w.color}-20)`} />
                      <div>
                        <div style={{ fontWeight: 600, fontSize: 14, color: V2.text }}>{w.name}</div>
                        <div style={{ fontSize: 12, color: V2.textDim }}>Started {w.startDate}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{ padding: "16px 18px" }}>
                    <div style={{ fontWeight: 500, fontSize: 13, color: V2.text }}>{job.title}</div>
                    <div style={{ fontSize: 12, color: V2.textDim }}>{client.name}</div>
                  </td>
                  <td style={{ padding: "16px 18px" }}><V2StatusPill status={w.status} /></td>
                  <td style={{ padding: "16px 18px", textAlign: "right", fontVariantNumeric: "tabular-nums", fontWeight: 600, fontSize: 13, color: V2.text }}>
                    ${money(w.spPayRate)}<span style={{ fontSize: 11, color: V2.textDim, fontWeight: 500 }}>/hr</span>
                  </td>
                  <td style={{ padding: "16px 18px", minWidth: 160 }}>
                    <V2HoursCell hours={hours} />
                  </td>
                  <td style={{ padding: "16px 18px", textAlign: "right", fontVariantNumeric: "tabular-nums", fontWeight: 600, fontSize: 13, color: V2.text }}>
                    ${Math.round(earnings).toLocaleString()}
                  </td>
                  <td style={{ padding: "16px 18px" }}><V2TimecardChip status={w.timecard} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </V2TableShell>
    </div>
  );
}

Object.assign(window, { V2WorkersView });
})();
