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

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

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

function V2JobsTable({ jobs, onOpenJob, density = "normal" }) {
  const pad = density === "compact" ? "12px 18px" : "18px 18px";
  return (
    <V2TableShell>
      <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "var(--font-body)" }}>
        <thead>
          <tr>
            <V2TH>Job</V2TH>
            <V2TH>Client</V2TH>
            <V2TH>Location</V2TH>
            <V2TH right>Pay</V2TH>
            <V2TH>HCO progress</V2TH>
            <V2TH>Deadline</V2TH>
            <V2TH>Status</V2TH>
            <V2TH w={140}></V2TH>
          </tr>
        </thead>
        <tbody>
          {jobs.map((job, i) => {
            const client = CLIENTS[job.client];
            const fill = job.hcoFilled, total = job.hcoTotal;
            return (
              <tr key={job.id} onClick={() => onOpenJob?.(job)} style={{
                borderBottom: i < jobs.length - 1 ? `1px solid ${V2.hairlineSoft}` : "none",
                cursor: "pointer",
                background: "transparent",
              }}
              onMouseEnter={e => e.currentTarget.style.background = "#FAFAFA"}
              onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                <td style={{ padding: pad, minWidth: 240 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                    <span style={{ fontWeight: 600, fontSize: 14, color: V2.text }}>{job.title}</span>
                    {job.recurring && <V2RecurringChip recurring={job.recurring} />}
                  </div>
                  <div style={{ fontSize: 12, color: V2.textDim, marginTop: 3, fontVariantNumeric: "tabular-nums" }}>
                    Req {job.req}
                  </div>
                </td>
                <td style={{ padding: pad, fontSize: 13, color: V2.textMuted }}>{client.name}</td>
                <td style={{ padding: pad, fontSize: 13, color: V2.textMuted, whiteSpace: "nowrap" }}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
                    <Icon name="location-pin" size={12} style={{ color: V2.textDim }} />
                    {job.location}
                  </span>
                </td>
                <td style={{ padding: pad, textAlign: "right" }}>
                  <span style={{
                    fontWeight: 600, fontSize: 14, color: V2.text,
                    fontVariantNumeric: "tabular-nums",
                  }}>${job.payRange ? job.payRange : money(job.payRate)}</span>
                  <span style={{ fontSize: 11, color: V2.textDim, marginLeft: 2 }}>/hr</span>
                </td>
                <td style={{ padding: pad, minWidth: 200 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <div style={{ flex: 1 }}><V2Progress filled={fill} total={total} /></div>
                    <span style={{
                      fontSize: 12, fontWeight: 600, color: V2.text,
                      fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap",
                    }}>{fill}<span style={{ color: V2.textDim, fontWeight: 500 }}> / {total}</span></span>
                  </div>
                </td>
                <td style={{ padding: pad }}><V2DaysLeft days={job.daysLeft} /></td>
                <td style={{ padding: pad }}><V2StatusPill status={job.status} /></td>
                <td style={{ padding: pad, textAlign: "right" }}>
                  <V2Button size="sm" variant="primary" iconEnd="arrow-right"
                    isDisabled={job.status !== "Accepting"}>Submit</V2Button>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </V2TableShell>
  );
}

function V2JobsGrouped({ jobs, onOpenJob }) {
  const groups = useMemo(() => {
    const buckets = { critical: [], high: [], med: [], low: [] };
    jobs.forEach(j => buckets[urgencyOf(j.daysLeft)].push(j));
    return [
      { key: "critical", title: "Critical",      sub: "≤ 3 days left",   tone: "red",    jobs: buckets.critical },
      { key: "high",     title: "Urgent",        sub: "this week",       tone: "yellow", jobs: buckets.high },
      { key: "med",      title: "This month",    sub: "≤ 14 days",       tone: "blue",   jobs: buckets.med },
      { key: "low",      title: "Later",         sub: "> 14 days",       tone: "neutral",jobs: buckets.low },
    ].filter(g => g.jobs.length > 0)
     .map(g => ({ ...g, jobs: g.jobs.sort((a, b) => a.daysLeft - b.daysLeft) }));
  }, [jobs]);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 32 }}>
      {groups.map(group => (
        <div key={group.key}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
            <h3 style={{
              fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 700,
              margin: 0, color: V2.text,
            }}>{group.title}</h3>
            <V2Badge tone={group.tone}>{group.jobs.length}</V2Badge>
            <span style={{ fontSize: 13, color: V2.textDim }}>{group.sub}</span>
          </div>
          <V2TableShell>
            <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "var(--font-body)" }}>
              <tbody>
                {group.jobs.map((job, i) => {
                  const client = CLIENTS[job.client];
                  return (
                    <tr key={job.id} onClick={() => onOpenJob?.(job)} style={{
                      borderBottom: i < group.jobs.length - 1 ? `1px solid ${V2.hairlineSoft}` : "none",
                      cursor: "pointer",
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = "#FAFAFA"}
                    onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                      <td style={{ padding: "16px 20px", width: "40%" }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                          <span style={{ fontWeight: 600, fontSize: 15, color: V2.text }}>{job.title}</span>
                          {job.recurring && <V2RecurringChip recurring={job.recurring} />}
                          <V2StatusPill status={job.status} />
                        </div>
                        <div style={{ display: "flex", gap: 12, marginTop: 4, fontSize: 12, color: V2.textMuted }}>
                          <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={11} />{job.location}
                          </span>
                        </div>
                      </td>
                      <td style={{ padding: "16px 20px", width: 130, textAlign: "right" }}>
                        <div style={{ fontSize: 11, color: V2.textDim, fontWeight: 500, marginBottom: 2 }}>Pay rate</div>
                        <div style={{
                          fontWeight: 600, fontSize: 14, color: V2.text,
                          fontVariantNumeric: "tabular-nums",
                        }}>${job.payRange ? job.payRange : money(job.payRate)}<span style={{ fontSize: 11, color: V2.textDim, marginLeft: 2, fontWeight: 500 }}>/hr</span></div>
                      </td>
                      <td style={{ padding: "16px 20px", width: 200 }}>
                        <div style={{ fontSize: 11, color: V2.textDim, fontWeight: 500, marginBottom: 5 }}>
                          HCO · {job.hcoFilled}/{job.hcoTotal}
                        </div>
                        <V2Progress filled={job.hcoFilled} total={job.hcoTotal} height={6} />
                      </td>
                      <td style={{ padding: "16px 20px", width: 130 }}>
                        <V2DaysLeft days={job.daysLeft} />
                      </td>
                      <td style={{ padding: "16px 20px", width: 140, textAlign: "right" }}>
                        <V2Button size="md" variant="primary" iconEnd="arrow-right"
                          isDisabled={job.status !== "Accepting"}>Submit</V2Button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </V2TableShell>
        </div>
      ))}
    </div>
  );
}

function V2JobsView({ tweaks, onOpenJob }) {
  const { jobsLayout = "table", density = "normal" } = tweaks || {};
  const [q, setQ] = useState("");
  const [status, setStatus] = useState("all");

  const filtered = useMemo(() => {
    const qLower = q.toLowerCase().trim();
    return JOBS.filter(j => {
      if (status !== "all" && j.status !== status) 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]);

  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>
      <V2SectionHeader
        eyebrow="Jobs"
        title="Open sourcing priorities"
        sub="Sorted by HCO end date. Recurring jobs need ongoing submissions even when current commitments fill."
        actions={<>
          <V2Button variant="secondary" size="lg" iconStart="document-download">Export</V2Button>
          <V2Button variant="primary" size="lg" iconStart="plus">Browse all jobs</V2Button>
        </>}
      />

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

      <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap", marginBottom: 18 }}>
        <div style={{ flex: "0 0 320px" }}>
          <V2TextField placeholder="Search jobs, clients, req IDs…" value={q} onChange={e => setQ(e.target.value)} iconStart="search" />
        </div>
        <V2PillToggle
          value={status}
          onChange={setStatus}
          options={[
            { value: "all",       label: "All" },
            { value: "Accepting", label: "Accepting" },
            { value: "Paused",    label: "Paused" },
            { value: "Closed",    label: "Closed" },
          ]}
        />
      </div>

      {jobsLayout === "grouped"
        ? <V2JobsGrouped jobs={filtered} onOpenJob={onOpenJob} />
        : <V2JobsTable  jobs={filtered} onOpenJob={onOpenJob} density={density} />}
    </div>
  );
}

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