/* eslint-disable */
// Staffing Partner — Workers roster view

(function () {
const { Icon, Button, Badge, TextField, Avatar } = window;
const { WORKERS, JOBS, CLIENTS, AGENTS } = window;
const { SectionHeader, AgentChip } = window;
const { useState, useMemo } = React;

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

function StatusDot({ status }) {
  const map = {
    "Active":   { color: "green",  dot: true },
    "On leave": { color: "yellow", dot: true },
    "Ended":    { color: "neutral", dot: true },
  };
  const m = map[status] || map["Ended"];
  return <Badge color={m.color} dot>{status}</Badge>;
}

function TimecardChip({ status }) {
  const map = {
    "Approved": "green",
    "Pending":  "yellow",
    "Disputed": "red",
  };
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 4,
      padding: "2px 8px", border: "2px solid var(--neutral-100)",
      background: `var(--${map[status]}-20)`, color: `var(--${map[status]}-100)`,
      borderRadius: 100, fontSize: 11, fontWeight: 700, letterSpacing: "0.04em",
      fontFamily: "var(--font-body)",
    }}>
      {status}
    </span>
  );
}

// Inline bar showing hours worked within a max (for quick comparison)
function HoursBar({ hours, max }) {
  const pct = Math.min(100, (hours / max) * 100);
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
      <span style={{
        fontFamily: "var(--font-body)", fontVariantNumeric: "tabular-nums",
        fontWeight: 700, fontSize: 13, width: 46, textAlign: "right",
      }}>{hours}</span>
      <div style={{
        flex: 1, height: 6, borderRadius: 100,
        background: "var(--neutral-20)",
        border: "1.5px solid var(--neutral-100)", overflow: "hidden",
        minWidth: 30,
      }}>
        <div style={{ height: "100%", width: `${pct}%`, background: "var(--green-60)" }} />
      </div>
    </div>
  );
}

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

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

  const maxHoursInView = Math.max(...WORKERS.map(w => w.hours[timeframe]), 1);

  // Aggregate stats
  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 = [
    { key: "lastWeek",    label: "Last week"    },
    { key: "lastMonth",   label: "Last month"   },
    { key: "lastQuarter", label: "Last quarter" },
    { key: "ytd",         label: "YTD"          },
  ];

  const pad = density === "compact" ? "10px 14px" : "14px 14px";

  const Header = ({ children, right, w }) => (
    <th style={{
      textAlign: right ? "right" : "left",
      padding: "10px 14px",
      fontSize: 11, fontWeight: 700, letterSpacing: "0.08em",
      textTransform: "uppercase", color: "var(--neutral-70)",
      borderBottom: "2px solid var(--neutral-100)",
      background: "var(--neutral-20)", whiteSpace: "nowrap", width: w,
    }}>{children}</th>
  );

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

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

      {/* Filter bar */}
      <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap", marginBottom: 14 }}>
        <div style={{ flex: "0 0 280px" }}>
          <TextField placeholder="Search workers…" value={q} onChange={e => setQ(e.target.value)} iconStart="search" />
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          {["all","Active","On leave","Ended"].map(s => {
            const on = statusFilter === s;
            return (
              <button key={s} onClick={() => setStatusFilter(s)} style={{
                padding: "6px 12px", borderRadius: 100,
                border: "2px solid var(--neutral-100)",
                background: on ? "var(--neutral-100)" : "var(--neutral-10)",
                color: on ? "var(--neutral-10)" : "var(--neutral-100)",
                fontWeight: 600, fontSize: 13, cursor: "pointer",
                fontFamily: "var(--font-body)",
              }}>{s === "all" ? "All" : s}</button>
            );
          })}
        </div>
        <div style={{ marginLeft: "auto", display: "flex", gap: 6, alignItems: "center" }}>
          <span style={{ fontSize: 12, color: "var(--neutral-60)", fontWeight: 600 }}>Hours:</span>
          <div style={{ display: "flex", border: "2px solid var(--neutral-100)", borderRadius: 8, overflow: "hidden", background: "var(--neutral-10)" }}>
            {timeframes.map((t, i) => {
              const on = timeframe === t.key;
              return (
                <button key={t.key} onClick={() => setTimeframe(t.key)} style={{
                  padding: "6px 12px", border: 0, cursor: "pointer",
                  borderRight: i < timeframes.length - 1 ? "2px solid var(--neutral-100)" : "none",
                  background: on ? "var(--neutral-100)" : "transparent",
                  color: on ? "var(--neutral-10)" : "var(--neutral-100)",
                  fontWeight: 600, fontSize: 12,
                  fontFamily: "var(--font-body)",
                }}>{t.label}</button>
              );
            })}
          </div>
        </div>
      </div>

      {/* Table */}
      <div style={{
        border: "2px solid var(--neutral-100)", borderRadius: 12,
        background: "var(--neutral-10)", overflow: "hidden",
        boxShadow: "var(--shadow-md)",
      }}>
        <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "var(--font-body)" }}>
          <thead>
            <tr>
              <Header>Worker</Header>
              <Header>Job / Client</Header>
              <Header>Agent</Header>
              <Header>Status</Header>
              <Header right>SP pay rate</Header>
              {showSecondary && <Header right>Bill rate</Header>}
              <Header>Hours ({timeframes.find(t => t.key === timeframe).label})</Header>
              <Header right>Earnings</Header>
              <Header>Timecard</Header>
            </tr>
          </thead>
          <tbody>
            {filtered.map(w => {
              const job = JOBS.find(j => j.id === w.jobId);
              const client = CLIENTS[job.client];
              const agent = AGENTS.find(a => a.id === w.agentId);
              const hours = w.hours[timeframe];
              const earnings = hours * w.spPayRate;
              const margin = w.clientBillRate - w.spPayRate;
              return (
                <tr key={w.id} style={{ borderBottom: "1.5px solid var(--neutral-30)" }}>
                  <td style={{ padding: pad }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <Avatar name={w.name} size={34} bg={`var(--${w.color}-20)`} />
                      <div>
                        <div style={{ fontWeight: 700, fontSize: 14 }}>{w.name}</div>
                        {showSecondary && (
                          <div style={{ fontSize: 11, color: "var(--neutral-60)" }}>
                            Start {w.startDate} · Ends {w.endDate}
                          </div>
                        )}
                      </div>
                    </div>
                  </td>
                  <td style={{ padding: pad }}>
                    <div style={{ fontWeight: 600, fontSize: 13 }}>{job.title}</div>
                    <div style={{ fontSize: 11, color: "var(--neutral-60)" }}>{client.name}</div>
                  </td>
                  <td style={{ padding: pad }}>
                    <AgentChip agent={agent} />
                  </td>
                  <td style={{ padding: pad }}>
                    <StatusDot status={w.status} />
                  </td>
                  <td style={{ padding: pad, textAlign: "right", fontVariantNumeric: "tabular-nums", fontWeight: 700, fontSize: 13 }}>
                    ${money(w.spPayRate)}<span style={{ fontSize: 10, color: "var(--neutral-60)", fontWeight: 500 }}>/hr</span>
                  </td>
                  {showSecondary && (
                    <td style={{ padding: pad, textAlign: "right", fontVariantNumeric: "tabular-nums", fontSize: 12, color: "var(--neutral-70)" }}>
                      ${money(w.clientBillRate)}
                      <div style={{ fontSize: 10, color: "var(--green-100)", fontWeight: 600 }}>+${money(margin)} margin</div>
                    </td>
                  )}
                  <td style={{ padding: pad, minWidth: 180 }}>
                    <HoursBar hours={hours} max={maxHoursInView} />
                  </td>
                  <td style={{ padding: pad, textAlign: "right", fontVariantNumeric: "tabular-nums", fontWeight: 700, fontSize: 13 }}>
                    ${Math.round(earnings).toLocaleString()}
                  </td>
                  <td style={{ padding: pad }}>
                    <TimecardChip status={w.timecard} />
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function BigStat({ label, value, sub, tone, icon }) {
  return (
    <div style={{
      padding: "14px 16px", border: "2px solid var(--neutral-100)",
      borderRadius: 10, background: "var(--neutral-10)",
      boxShadow: "var(--shadow-sm)", fontFamily: "var(--font-body)",
      position: "relative", overflow: "hidden",
    }}>
      <div style={{
        position: "absolute", top: 0, left: 0, width: 4, height: "100%",
        background: `var(--${tone}-60)`,
      }} />
      <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--neutral-70)", display: "inline-flex", alignItems: "center", gap: 4 }}>
        {icon && <Icon name={icon} size={12} />}{label}
      </div>
      <div style={{ fontFamily: "var(--font-display)", fontSize: 34, fontWeight: 700, color: "var(--neutral-100)", lineHeight: 1, marginTop: 6, fontVariantNumeric: "tabular-nums" }}>{value}</div>
      <div style={{ fontSize: 12, color: "var(--neutral-60)", marginTop: 2 }}>{sub}</div>
    </div>
  );
}

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