/* eslint-disable */
// Staffing Partner — Jobs view (primary, 2 variations)

(function () {
const { Icon, Button, Badge, TextField } = window;
const { JOBS, CLIENTS } = window;
const { RecurringBadge, HcoBar, StatusPill, DaysLeft, SectionHeader,
        urgencyOf, urgencyLabel, urgencyColor } = window;
const { useState, useMemo } = React;

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

function payRateCell(job) {
  return (
    <span style={{
      fontFamily: "var(--font-body)", fontVariantNumeric: "tabular-nums lining-nums",
      fontWeight: 700, fontSize: 14, color: "var(--neutral-100)",
    }}>
      ${job.payRange ? job.payRange : money(job.payRate)}
      <span style={{ fontSize: 11, color: "var(--neutral-60)", fontWeight: 500, marginLeft: 2 }}>
        /hr
      </span>
    </span>
  );
}

function recurringNote(job) {
  if (!job.recurring) return null;
  const r = job.recurring;
  const totalRemaining = r.rate * r.remainingCycles;
  return (
    <div style={{
      fontSize: 11, color: "var(--purple-100)", fontWeight: 600,
      display: "inline-flex", alignItems: "center", gap: 4, marginTop: 3,
    }}>
      <Icon name="refresh" size={11} />
      +{totalRemaining} more needed through {r.through} — keep submitting
    </div>
  );
}

// --- Filters bar ------------------------------------------------------
function JobFilters({ q, setQ, status, setStatus, client, setClient, recurringOnly, setRecurringOnly }) {
  const pill = (active, label, onClick, count) => (
    <button onClick={onClick} style={{
      padding: "6px 12px", borderRadius: 100,
      border: "2px solid var(--neutral-100)",
      background: active ? "var(--neutral-100)" : "var(--neutral-10)",
      color: active ? "var(--neutral-10)" : "var(--neutral-100)",
      fontWeight: 600, fontSize: 13, cursor: "pointer",
      fontFamily: "var(--font-body)",
      display: "inline-flex", alignItems: "center", gap: 6,
    }}>
      {label}
      {count != null && <span style={{
        fontSize: 11, fontWeight: 700, padding: "0 6px",
        background: active ? "var(--neutral-80)" : "var(--neutral-20)",
        color: active ? "var(--neutral-10)" : "var(--neutral-100)",
        borderRadius: 100, fontVariantNumeric: "tabular-nums",
      }}>{count}</span>}
    </button>
  );

  return (
    <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap", marginBottom: 16 }}>
      <div style={{ flex: "0 0 300px" }}>
        <TextField placeholder="Search jobs, clients, req IDs…" value={q} onChange={e => setQ(e.target.value)} iconStart="search" />
      </div>
      <div style={{ display: "flex", gap: 6 }}>
        {pill(status === "all",        "All",        () => setStatus("all"))}
        {pill(status === "Accepting",  "Accepting",  () => setStatus("Accepting"))}
        {pill(status === "Paused",     "Paused",     () => setStatus("Paused"))}
        {pill(status === "Closed",     "Closed",     () => setStatus("Closed"))}
      </div>
      <div style={{ width: 1, height: 24, background: "var(--neutral-30)" }} />
      {pill(recurringOnly, (<><Icon name="refresh" size={12} />&nbsp;Recurring only</>), () => setRecurringOnly(!recurringOnly))}
      <div style={{ flex: 1 }} />
      <Button color="secondary" size="md" iconStart="document-download">Export</Button>
    </div>
  );
}

// ======================================================================
// VARIATION A — Dense table, sortable by urgency
// ======================================================================
function JobsTableDense({ jobs, density = "normal", showSecondary = true, onOpenJob }) {
  const rowPad = density === "compact" ? "10px 14px" : "16px 14px";

  const Header = ({ children, w, right }) => (
    <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 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 w={46}></Header>
            <Header>Job</Header>
            <Header>Client</Header>
            <Header>Location</Header>
            <Header right>Pay rate</Header>
            <Header>HCO progress</Header>
            <Header>Deadline</Header>
            <Header right>Submitted</Header>
            <Header>Status</Header>
            <Header w={160}></Header>
          </tr>
        </thead>
        <tbody>
          {jobs.map(job => {
            const client = CLIENTS[job.client];
            const u = urgencyOf(job.daysLeft);
            const fill = job.hcoFilled;
            const total = job.hcoTotal;
            const full = fill >= total;
            return (
              <tr key={job.id} onClick={() => onOpenJob?.(job)} style={{
                borderBottom: "1.5px solid var(--neutral-30)",
                cursor: "pointer",
                background: job.recurring ? "linear-gradient(to right, rgba(176,141,255,0.06), transparent 40%)" : "transparent",
              }}>
                <td style={{ padding: rowPad, textAlign: "center" }}>
                  <span title={urgencyLabel(u)} style={{
                    display: "inline-block", width: 10, height: 10, borderRadius: 100,
                    background: `var(--${urgencyColor(u)}-60)`,
                    border: "1.5px solid var(--neutral-100)",
                  }} />
                </td>
                <td style={{ padding: rowPad, minWidth: 240 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{ fontWeight: 700, fontSize: 14, color: "var(--neutral-100)" }}>
                      {job.title}
                    </span>
                    {job.recurring && <RecurringBadge recurring={job.recurring} size="sm" />}
                  </div>
                  <div style={{ fontSize: 11, color: "var(--neutral-60)", fontWeight: 500, marginTop: 2, fontVariantNumeric: "tabular-nums" }}>
                    Req {job.req}
                  </div>
                </td>
                <td style={{ padding: rowPad, fontSize: 13, color: "var(--neutral-90)" }}>
                  {client.name}
                </td>
                <td style={{ padding: rowPad, fontSize: 13, color: "var(--neutral-90)", whiteSpace: "nowrap" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
                    <Icon name="location-pin" size={12} style={{ color: "var(--neutral-60)", flexShrink: 0 }} />
                    {job.location}
                  </div>
                  {showSecondary && <div style={{ fontSize: 11, color: "var(--neutral-60)", marginTop: 2, paddingLeft: 16 }}>{job.workStyle}</div>}
                </td>
                <td style={{ padding: rowPad, textAlign: "right" }}>
                  {payRateCell(job)}
                </td>
                <td style={{ padding: rowPad, minWidth: 180 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <div style={{ flex: 1 }}><HcoBar filled={fill} total={total} /></div>
                    <span style={{
                      fontFamily: "var(--font-body)", fontSize: 12, fontWeight: 700,
                      fontVariantNumeric: "tabular-nums", color: "var(--neutral-100)",
                      whiteSpace: "nowrap",
                    }}>
                      {fill}<span style={{ color: "var(--neutral-50)" }}> / {total}</span>
                    </span>
                  </div>
                  {recurringNote(job)}
                </td>
                <td style={{ padding: rowPad }}>
                  <DaysLeft days={job.daysLeft} />
                </td>
                <td style={{ padding: rowPad, textAlign: "right", fontVariantNumeric: "tabular-nums", fontSize: 13, color: "var(--neutral-90)" }}>
                  {job.submitted}
                </td>
                <td style={{ padding: rowPad }}>
                  <StatusPill status={job.status} />
                </td>
                <td style={{ padding: rowPad, textAlign: "right" }}>
                  <Button size="sm" color="primary-green" iconEnd="arrow-right" isDisabled={job.status !== "Accepting"}>
                    Submit
                  </Button>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

// ======================================================================
// VARIATION B — Urgency-grouped rows (hybrid card/list)
// ======================================================================
function JobsGrouped({ jobs, grouping = "urgency", showSecondary = true, onOpenJob }) {

  // Build groups based on grouping mode
  const groups = useMemo(() => {
    if (grouping === "client") {
      const by = {};
      jobs.forEach(j => {
        const k = CLIENTS[j.client].name;
        (by[k] = by[k] || []).push(j);
      });
      return Object.entries(by).map(([name, js]) => ({
        key: name, title: name, count: js.length, tone: "neutral",
        sub: `${js.length} job${js.length === 1 ? "" : "s"}`,
        jobs: js.sort((a, b) => a.daysLeft - b.daysLeft),
      }));
    }
    if (grouping === "deadline") {
      const buckets = { "This week": [], "This month": [], "Later": [] };
      jobs.forEach(j => {
        if (j.daysLeft <= 7) buckets["This week"].push(j);
        else if (j.daysLeft <= 30) buckets["This month"].push(j);
        else buckets["Later"].push(j);
      });
      return Object.entries(buckets).map(([k, js]) => ({
        key: k, title: k, count: js.length, tone: k === "This week" ? "red" : k === "This month" ? "yellow" : "neutral",
        sub: js.length === 0 ? "Nothing here" : `${js.length} job${js.length === 1 ? "" : "s"}`,
        jobs: js.sort((a, b) => a.daysLeft - b.daysLeft),
      })).filter(g => g.count > 0);
    }
    // default: urgency
    const buckets = { critical: [], high: [], med: [], low: [] };
    jobs.forEach(j => { buckets[urgencyOf(j.daysLeft)].push(j); });
    return [
      { key: "critical", title: "Critical — ≤ 3 days", tone: "red",     jobs: buckets.critical },
      { key: "high",     title: "Urgent — this week",  tone: "yellow",  jobs: buckets.high },
      { key: "med",      title: "This month",          tone: "blue",    jobs: buckets.med },
      { key: "low",      title: "Later",               tone: "neutral", jobs: buckets.low },
    ].filter(g => g.jobs.length > 0)
     .map(g => ({ ...g, count: g.jobs.length,
                   sub: `${g.jobs.length} job${g.jobs.length === 1 ? "" : "s"}`,
                   jobs: g.jobs.sort((a, b) => a.daysLeft - b.daysLeft) }));
  }, [jobs, grouping]);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
      {groups.map(group => (
        <div key={group.key}>
          <div style={{
            display: "flex", alignItems: "center", gap: 10, marginBottom: 10,
            fontFamily: "var(--font-body)",
          }}>
            <span style={{
              width: 10, height: 10, borderRadius: 100,
              background: `var(--${group.tone === "neutral" ? "neutral-60" : group.tone + "-60"})`,
              border: "1.5px solid var(--neutral-100)",
            }} />
            <h3 style={{
              fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 700,
              margin: 0, color: "var(--neutral-100)",
            }}>{group.title}</h3>
            <Badge color={group.tone === "neutral" ? "neutral" : group.tone}>{group.count}</Badge>
            <span style={{ fontSize: 12, color: "var(--neutral-60)" }}>{group.sub}</span>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {group.jobs.map(job => (
              <JobGroupedRow key={job.id} job={job} showSecondary={showSecondary} onOpen={onOpenJob} />
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function JobGroupedRow({ job, showSecondary, onOpen }) {
  const client = CLIENTS[job.client];
  const full = job.hcoFilled >= job.hcoTotal;
  return (
    <div onClick={() => onOpen?.(job)} style={{
      display: "grid",
      gridTemplateColumns: "1fr 160px 180px 160px 140px",
      gap: 16, alignItems: "center",
      padding: "16px 18px",
      border: "2px solid var(--neutral-100)", borderRadius: 10,
      background: "var(--neutral-10)", cursor: "pointer",
      boxShadow: "var(--shadow-sm)",
      fontFamily: "var(--font-body)",
    }}>
      {/* Title column */}
      <div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
          <span style={{ fontWeight: 700, fontSize: 15, color: "var(--neutral-100)" }}>{job.title}</span>
          {job.recurring && <RecurringBadge recurring={job.recurring} size="sm" />}
          <StatusPill status={job.status} />
        </div>
        <div style={{ display: "flex", gap: 12, marginTop: 4, fontSize: 12, color: "var(--neutral-70)", flexWrap: "wrap" }}>
          <span style={{ fontVariantNumeric: "tabular-nums" }}>Req {job.req}</span>
          <span>·</span>
          <span>{client.name}</span>
          <span>·</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 3 }}>
            <Icon name="location-pin" size={12} />{job.location} · {job.workStyle}
          </span>
        </div>
        {showSecondary && job.recurring && (
          <div style={{ fontSize: 11, color: "var(--purple-100)", fontWeight: 600, marginTop: 4,
                        display: "inline-flex", alignItems: "center", gap: 4 }}>
            <Icon name="refresh" size={11} />
            Ongoing: {job.recurring.rate} every {job.recurring.period} through {job.recurring.through}
          </div>
        )}
      </div>
      {/* Pay rate */}
      <div style={{ textAlign: "right" }}>
        <div style={{ fontSize: 11, color: "var(--neutral-60)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em" }}>Pay rate</div>
        {payRateCell(job)}
      </div>
      {/* HCO */}
      <div>
        <div style={{ fontSize: 11, color: "var(--neutral-60)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 4 }}>
          HCO · {job.hcoFilled}/{job.hcoTotal}{full && !job.recurring ? " · filled" : ""}
        </div>
        <HcoBar filled={job.hcoFilled} total={job.hcoTotal} height={8} />
      </div>
      {/* Days */}
      <div style={{ display: "flex", flexDirection: "column", gap: 4, alignItems: "flex-start" }}>
        <DaysLeft days={job.daysLeft} />
        <span style={{ fontSize: 11, color: "var(--neutral-60)" }}>
          {job.submitted} submitted
        </span>
      </div>
      {/* Action */}
      <div style={{ textAlign: "right" }}>
        <Button size="md" color="primary-green" iconEnd="arrow-right" isDisabled={job.status !== "Accepting"}>
          Submit
        </Button>
      </div>
    </div>
  );
}

// ======================================================================
// Jobs view wrapper
// ======================================================================
function JobsView({ tweaks, onOpenJob }) {
  const { jobsLayout, density, jobsGrouping, showSecondary } = tweaks;

  const [q, setQ] = useState("");
  const [status, setStatus] = useState("all");
  const [recurringOnly, setRecurringOnly] = useState(false);

  const filtered = useMemo(() => {
    const qLower = q.toLowerCase().trim();
    return JOBS.filter(j => {
      if (status !== "all" && j.status !== status) return false;
      if (recurringOnly && !j.recurring) return false;
      if (!qLower) return true;
      const client = CLIENTS[j.client].name;
      return [j.title, j.req, client, j.location].some(s => s.toLowerCase().includes(qLower));
    }).sort((a, b) => a.daysLeft - b.daysLeft);
  }, [q, status, recurringOnly]);

  // Summary stats
  const stats = useMemo(() => ({
    active: JOBS.filter(j => j.status === "Accepting").length,
    openHco: JOBS.filter(j => j.status === "Accepting").reduce((s, j) => s + (j.hcoTotal - j.hcoFilled), 0),
    critical: JOBS.filter(j => j.status === "Accepting" && urgencyOf(j.daysLeft) === "critical").length,
    recurring: JOBS.filter(j => j.recurring).length,
  }), []);

  return (
    <div>
      <SectionHeader
        eyebrow="Jobs"
        title="Open sourcing priorities"
        sub="Sorted by HCO end date. Recurring jobs highlighted — keep submitting even when the near-term count fills."
      />

      {/* Stat row */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 22 }}>
        <StatTile label="Accepting apps" value={stats.active} sub="open jobs" tone="green" />
        <StatTile label="Open HCOs" value={stats.openHco} sub="across open jobs" tone="blue" />
        <StatTile label="Critical" value={stats.critical} sub="≤ 3 days left" tone="red" icon="alert-triangle" />
        <StatTile label="Recurring" value={stats.recurring} sub="ongoing commitments" tone="purple" icon="refresh" />
      </div>

      <JobFilters
        q={q} setQ={setQ}
        status={status} setStatus={setStatus}
        recurringOnly={recurringOnly} setRecurringOnly={setRecurringOnly}
      />

      {jobsLayout === "grouped"
        ? <JobsGrouped jobs={filtered} grouping={jobsGrouping} showSecondary={showSecondary} onOpenJob={onOpenJob} />
        : <JobsTableDense jobs={filtered} density={density} showSecondary={showSecondary} onOpenJob={onOpenJob} />}
    </div>
  );
}

function StatTile({ 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: 40, fontWeight: 700, color: "var(--neutral-100)", lineHeight: 1, margin: "6px 0 2px", fontVariantNumeric: "tabular-nums" }}>{value}</div>
      <div style={{ fontSize: 12, color: "var(--neutral-60)" }}>{sub}</div>
    </div>
  );
}

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