/* eslint-disable */
// Worker view — sidebar shell + dashboard home (modeled on the production HireArt
// worker app) + Assignments table. Action-needed treatment surfaces the SOW
// re-signing prompt in three places: sidebar nav item, dashboard Assignments card,
// and the Assignments page itself.

(function () {
const { Icon, Button, Badge, Card, Avatar } = window;
const { WORKERS, ONBOARDING_DOC_REQUIREMENTS, today, daysFromNow } = window;
const { SOWStatePill, Callout, PageHeader, SectionHeader, ExpiryRing, Pill } = window;
const { DropboxSignFrame, SOWPaper } = window;
const { useState } = React;

// ---------- Worker chrome — sidebar + topbar shell ----------
function WorkerNav({ worker, active, onNav, breadcrumb, children }) {
  const isReengage = worker.sow.state === "expiring" || worker.sow.state === "expired";

  const sections = [
    { label: null, items: [{ k: "home", label: "Home", icon: "home" }] },
    {
      label: "Job search",
      items: [
        { k: "applications", label: "Applications", icon: "bell" },
        { k: "interviews",   label: "Interviews",   icon: "voice-square" },
        { k: "offers",       label: "Offers",       icon: "document" },
      ],
    },
    {
      label: "Employment",
      items: [
        { k: "timecards",    label: "Time & attendance", icon: "clock" },
        { k: "paystubs",     label: "Paystubs",          icon: "credit-card" },
        { k: "assignments",  label: "Assignments",       icon: "briefcase", actionNeeded: isReengage },
        { k: "personal",     label: "Personal information", icon: "user" },
        { k: "payment",      label: "Payment setup",     icon: "credit-card" },
        { k: "expenses",     label: "Expenses",          icon: "calculator" },
        { k: "pto",          label: "Paid time off",     icon: "calendar" },
        { k: "documents",    label: "Documents",         icon: "document" },
        { k: "benefits",     label: "Benefits",          icon: "award" },
      ],
    },
  ];

  return (
    <div style={{ display: "grid", gridTemplateColumns: "260px 1fr", minHeight: "100vh", background: "var(--neutral-10)", fontFamily: "var(--font-body)" }}>
      <aside style={{
        borderRight: "1px solid var(--neutral-30)",
        padding: "20px 14px",
        display: "flex", flexDirection: "column", gap: 14,
        background: "var(--neutral-10)",
        position: "sticky", top: 0, height: "100vh", overflowY: "auto",
      }}>
        <div style={{ padding: "4px 8px 12px" }}>
          <img src="assets/logos/logo-primary.svg" alt="HireArt" style={{ height: 22 }} />
        </div>
        {sections.map((sec, si) => (
          <div key={si} style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            {sec.label && (
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "8px 10px 4px", fontSize: 11, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--neutral-70)" }}>
                <span>{sec.label}</span>
                <Icon name="chevron-up" size={12} />
              </div>
            )}
            {sec.items.map(it => {
              const isActive = active === it.k;
              return (
                <button key={it.k} onClick={() => onNav(it.k)} style={{
                  display: "flex", alignItems: "center", gap: 10,
                  padding: "10px 12px", borderRadius: 100,
                  border: isActive ? "2px solid var(--neutral-100)" : "2px solid transparent",
                  background: isActive ? "var(--neutral-10)" : "transparent",
                  boxShadow: isActive ? "var(--shadow-btn-sm)" : "none",
                  fontFamily: "var(--font-body)", fontSize: 13, fontWeight: isActive ? 700 : 500,
                  color: "var(--neutral-100)", cursor: "pointer", textAlign: "left",
                }}>
                  <Icon name={it.icon} size={16} />
                  <span style={{ flex: 1 }}>{it.label}</span>
                  {it.actionNeeded && (
                    <span style={{
                      display: "inline-flex", alignItems: "center", gap: 4,
                      background: "var(--purple-100)", color: "white",
                      fontSize: 10, fontWeight: 700, letterSpacing: "0.04em",
                      padding: "2px 7px", borderRadius: 100, textTransform: "uppercase",
                    }}>
                      <span style={{ width: 5, height: 5, borderRadius: "50%", background: "white" }} />
                      Action
                    </span>
                  )}
                </button>
              );
            })}
          </div>
        ))}
      </aside>

      <div style={{ display: "flex", flexDirection: "column", minWidth: 0 }}>
        <header style={{
          borderBottom: "1px solid var(--neutral-30)",
          padding: "14px 32px",
          display: "flex", alignItems: "center", justifyContent: "flex-end", gap: 16,
          background: "var(--neutral-10)",
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "4px 14px 4px 4px", border: "1px solid var(--neutral-30)", borderRadius: 100 }}>
            <Avatar name={worker.name} size={28} bg="var(--purple-20)" />
            <span style={{ fontSize: 13, fontWeight: 600 }}>{worker.name}</span>
            <Icon name="chevron-down" size={12} />
          </div>
        </header>
        <main style={{ padding: "20px 32px 60px", maxWidth: 1400, width: "100%" }}>
          {breadcrumb && (
            <div style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 13, color: "var(--neutral-70)", marginBottom: 18 }}>
              <Icon name="home" size={13} />
              <span>Dashboard</span>
              {breadcrumb !== "Dashboard" && (<>
                <span style={{ color: "var(--neutral-50)" }}>/</span>
                <span style={{ color: "var(--neutral-100)", fontWeight: 600 }}>{breadcrumb}</span>
              </>)}
            </div>
          )}
          {children}
        </main>
      </div>
    </div>
  );
}

// ---------- Dashboard home — two-column "My applications" + "My jobs" ----------
function WorkerHome({ worker, onSignSOW, onAssignments }) {
  const isReengage = worker.sow.state === "expiring" || worker.sow.state === "expired";
  const days = worker.sow.validThruDate ? daysFromNow(worker.sow.validThruDate) : null;

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 64 }}>
      {/* Left: My applications */}
      <div>
        <h1 style={{ fontFamily: "var(--font-headline)", fontSize: 32, fontWeight: 800, margin: "0 0 18px", letterSpacing: "-0.01em" }}>My applications</h1>
        <DashGroup title="Applications" body={<>1 active application</>} />
        <DashGroup title="Interviews" body={<span style={{ color: "var(--neutral-60)" }}>0 interviews</span>} />
        <DashGroup title="Offers" body={<>2 offers</>} />
      </div>

      {/* Right: My jobs */}
      <div>
        <h1 style={{ fontFamily: "var(--font-headline)", fontSize: 32, fontWeight: 800, margin: "0 0 18px", letterSpacing: "-0.01em" }}>My jobs</h1>
        <DashGroup title="Time & attendance" />
        <DashGroup
          title="Assignments"
          actionNeeded={isReengage}
          actionMessage={
            isReengage ? (
              <span>
                {worker.sow.state === "expired"
                  ? `Your Statement of Work expired ${Math.abs(days)} days ago — sign your new SOW now.`
                  : `Your Statement of Work expires in ${days} days — sign your new SOW to keep working.`}
              </span>
            ) : null
          }
          onActionClick={onSignSOW}
          actionLabel="Sign new SOW"
          onClick={onAssignments}
          body={<>
            <div>1 active assignment</div>
            <div>1 past assignment</div>
          </>}
        />
        <DashGroup title="Benefits" body={<span style={{ color: "var(--neutral-60)" }}>4 benefits available</span>} />
        <DashGroup title="Payments" body={<>Latest payment for Apr 27, 2026 - May 3, 2026</>} />
        <DashGroup title="Expenses" />
        <DashGroup title="Personal info" />
        <DashGroup title="Payment setup" />
      </div>
    </div>
  );
}

// Single dashboard "card row" — title bar + optional body underneath, mimicking
// the screenshot: bold black underline rule under the title, then text body.
function DashGroup({ title, body, onClick, actionNeeded, actionMessage, onActionClick, actionLabel }) {
  return (
    <div style={{ marginBottom: 28 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", paddingBottom: 8, borderBottom: "2px solid var(--neutral-100)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ fontSize: 18, fontWeight: 800 }}>{title}</span>
          {actionNeeded && (
            <span style={{
              display: "inline-flex", alignItems: "center", gap: 5,
              background: "var(--purple-100)", color: "white",
              fontSize: 11, fontWeight: 700, letterSpacing: "0.04em",
              padding: "3px 9px", borderRadius: 100, textTransform: "uppercase",
            }}>
              <span style={{ width: 5, height: 5, borderRadius: "50%", background: "white" }} />
              Action needed
            </span>
          )}
        </div>
        <button
          onClick={onClick}
          style={{ background: "none", border: 0, fontSize: 14, fontWeight: 500, color: "var(--neutral-90)", cursor: "pointer", textDecoration: "underline", textUnderlineOffset: 3, fontFamily: "inherit" }}
        >view</button>
      </div>
      {actionNeeded && actionMessage ? (
        <div style={{
          marginTop: 12, padding: "12px 14px",
          border: "2px solid var(--purple-100)", borderRadius: 8,
          background: "var(--purple-20)",
          display: "flex", alignItems: "center", gap: 12,
        }}>
          <Icon name="alert-triangle" size={16} />
          <div style={{ flex: 1, fontSize: 13, color: "var(--neutral-100)", lineHeight: 1.45 }}>{actionMessage}</div>
          {onActionClick && (
            <Button color="primary-purple" size="sm" iconStart="signature" onClick={onActionClick}>{actionLabel || "Take action"}</Button>
          )}
        </div>
      ) : null}
      {body && (
        <div style={{ paddingTop: 14, fontSize: 15, color: "var(--neutral-100)", lineHeight: 1.5 }}>{body}</div>
      )}
    </div>
  );
}

// ---------- Assignments table view ----------
function WorkerAssignmentsView({ worker, onSignSOW }) {
  const isReengage = worker.sow.state === "expiring" || worker.sow.state === "expired";
  const days = worker.sow.validThruDate ? daysFromNow(worker.sow.validThruDate) : null;

  // Mock assignment rows — current + a past (terminated) one for context.
  const rows = [
    {
      role: `${worker.job} (Full-Time) at ${worker.client}`,
      company: worker.client,
      tagline: "A Global Leader in AI Development",
      start: worker.startDate,
      payRate: worker.payRate,
      status: "active",
      actionNeeded: isReengage,
      bgInitial: worker.client[0],
      bgColor: "var(--neutral-20)",
    },
    {
      role: "Data Annotator - Phaedra (Task-Based) at Snorkel AI, Inc.",
      company: "Snorkel AI, Inc.",
      tagline: "A Pioneering AI Data Company",
      start: "January 7, 2025",
      payRate: "$36.00 USD/hr",
      status: "terminated",
      actionNeeded: false,
      bgInitial: "S",
      bgColor: "var(--blue-20)",
    },
  ];

  return (
    <>
      <h1 style={{ fontFamily: "var(--font-headline)", fontSize: 36, fontWeight: 800, margin: "0 0 20px", letterSpacing: "-0.01em" }}>Assignments</h1>

      {isReengage && (
        <div style={{ marginBottom: 18 }}>
          <Callout
            tone={worker.sow.state === "expired" ? "danger" : "warning"}
            icon={worker.sow.state === "expired" ? "alert-circle" : "alert-triangle"}
            title={
              worker.sow.state === "expired"
                ? `Your Statement of Work expired ${Math.abs(days)} days ago.`
                : `Your Statement of Work expires in ${days} days — action needed.`
            }
            action={<Button color="primary-purple" size="md" iconStart="signature" onClick={onSignSOW}>Sign new SOW</Button>}
          >
            HireArt has prepared a fresh SOW for the next phase of your work with {worker.client}. Sign it here to keep your assignment active.
          </Callout>
        </div>
      )}

      <div style={{ border: "1px solid var(--neutral-30)", borderRadius: 8, background: "var(--neutral-10)", overflow: "hidden" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "var(--font-body)" }}>
          <thead>
            <tr style={{ borderBottom: "1px solid var(--neutral-30)" }}>
              {["", "Role", "Company", "Start date", "Pay Rate", "Status", ""].map((h, i) => (
                <th key={i} style={{ textAlign: "left", padding: "14px 18px", fontSize: 13, fontWeight: 700, color: "var(--neutral-100)" }}>
                  {h && <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>{h}<Icon name="arrow-up-down" size={11} /></span>}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((r, i) => (
              <tr key={i} style={{ borderBottom: i < rows.length - 1 ? "1px solid var(--neutral-30)" : "none" }}>
                <td style={{ padding: "14px 18px", width: 56 }}>
                  <div style={{ width: 36, height: 36, borderRadius: "50%", background: r.bgColor, border: "1px solid var(--neutral-30)", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700, color: "var(--neutral-90)" }}>{r.bgInitial}</div>
                </td>
                <td style={{ padding: "14px 18px", fontSize: 14, color: "var(--neutral-100)" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                    <span>{r.role}</span>
                    {r.actionNeeded && (
                      <span style={{
                        display: "inline-flex", alignItems: "center", gap: 5,
                        background: "var(--purple-100)", color: "white",
                        fontSize: 10, fontWeight: 700, letterSpacing: "0.04em",
                        padding: "2px 8px", borderRadius: 100, textTransform: "uppercase",
                      }}>
                        <span style={{ width: 5, height: 5, borderRadius: "50%", background: "white" }} />
                        Action needed
                      </span>
                    )}
                  </div>
                </td>
                <td style={{ padding: "14px 18px", fontSize: 14, color: "var(--neutral-90)" }}>{r.tagline}</td>
                <td style={{ padding: "14px 18px", fontSize: 14, color: "var(--neutral-90)" }}>{r.start}</td>
                <td style={{ padding: "14px 18px", fontSize: 14, color: "var(--neutral-90)" }}>{r.payRate}</td>
                <td style={{ padding: "14px 18px", fontSize: 14, color: r.status === "active" ? "var(--neutral-100)" : "var(--neutral-60)" }}>{r.status}</td>
                <td style={{ padding: "14px 18px", textAlign: "right" }}>
                  {r.actionNeeded && (
                    <Button color="primary-purple" size="sm" iconStart="signature" onClick={onSignSOW}>Sign new SOW</Button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

// ---------- W2 / W3 — the embedded SOW signing flow ----------
function WorkerSignFlow({ worker, onBack, onComplete }) {
  const [signed, setSigned] = useState(worker.sow.state === "signed" || worker.sow.state === "active" || worker.sow.state === "open-ended");
  const isReengage = worker.sow.state === "expiring" || worker.sow.state === "expired";

  return (
    <>
      <PageHeader
        eyebrow={`${worker.client} · ${worker.job}`}
        title={isReengage ? "Re-sign your Statement of Work" : "Sign your Statement of Work"}
        subtitle={
          isReengage
            ? `Your previous SOW was for the period through ${worker.sow.validThru}. Here's the new one — review and sign below.`
            : "Read the document carefully, then sign at the bottom. The signed PDF will be saved to your documents."
        }
      />

      <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 24, alignItems: "start" }}>
        <div>
          {!signed ? (
            <DropboxSignFrame worker={worker} onSigned={() => setSigned(true)} />
          ) : (
            <Card padding={24} style={{ textAlign: "center" }}>
              <div style={{
                width: 56, height: 56, borderRadius: 100,
                background: "var(--green-40)", border: "2px solid var(--neutral-100)",
                display: "flex", alignItems: "center", justifyContent: "center",
                margin: "0 auto 16px", boxShadow: "var(--shadow-md)",
              }}>
                <Icon name="check" size={28} />
              </div>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 24, fontWeight: 700, marginBottom: 8 }}>You're done.</div>
              <div style={{ fontSize: 14, color: "var(--neutral-70)", marginBottom: 20, maxWidth: 480, margin: "0 auto 20px", lineHeight: 1.5 }}>
                Your Statement of Work has been signed and stored. The countersignature from HireArt usually lands within an hour.
                {isReengage && " Your previous SOW is preserved in your document history."}
              </div>
              <div style={{ display: "flex", gap: 8, justifyContent: "center" }}>
                <Button color="secondary" size="md" iconStart="download-1">Download PDF</Button>
                <Button color="primary-green" size="md" iconStart="arrow-left" onClick={onComplete}>Back to home</Button>
              </div>
            </Card>
          )}
        </div>

        <div style={{ position: "sticky", top: 24, display: "flex", flexDirection: "column", gap: 16 }}>
          <Card padding={16}>
            <SectionHeader title="At a glance" />
            <div style={{ display: "flex", flexDirection: "column", gap: 8, fontSize: 13 }}>
              <Stat2 label="Project" value={worker.sow.mergeValues.project_name} />
              <Stat2 label="Pay rate" value={worker.sow.mergeValues.pay_rate} />
              <Stat2 label="Start date" value={worker.sow.mergeValues.start_date} />
              <Stat2 label="End date" value={worker.sow.mergeValues.end_date || "Open-ended"} />
            </div>
          </Card>
        </div>
      </div>
    </>
  );
}

function Stat2({ label, value }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", borderBottom: "1px solid var(--neutral-20)" }}>
      <span style={{ color: "var(--neutral-70)", fontWeight: 600 }}>{label}</span>
      <span style={{ color: "var(--neutral-100)", fontWeight: 600, textAlign: "right", maxWidth: 200 }}>{value}</span>
    </div>
  );
}

// ---------- Documents view ----------
function WorkerDocumentsView({ worker }) {
  return (
    <>
      <h1 style={{ fontFamily: "var(--font-headline)", fontSize: 36, fontWeight: 800, margin: "0 0 20px", letterSpacing: "-0.01em" }}>Documents</h1>
      <Card padding={0} shadow="sm" style={{ overflow: "hidden" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "var(--font-body)" }}>
          <thead>
            <tr style={{ background: "var(--neutral-20)", borderBottom: "2px solid var(--neutral-100)" }}>
              {["Document", "Type", "Signed", "Status", ""].map(h => (
                <th key={h} style={{ textAlign: "left", padding: "11px 14px", fontSize: 11, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--neutral-80)" }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {ONBOARDING_DOC_REQUIREMENTS.map(r => {
              const b = worker.badges[r.key] || { state: "not-started" };
              return (
                <tr key={r.key} style={{ borderBottom: "1px solid var(--neutral-20)" }}>
                  <td style={{ padding: "12px 14px", fontSize: 13, fontWeight: 600 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <Icon name={r.hellosign ? "document" : "file-text"} size={16} />
                      {r.label}
                      {r.key === "sow" && worker.sow.state === "expiring" && <Badge color="yellow">Expiring</Badge>}
                    </div>
                  </td>
                  <td style={{ padding: "12px 14px", fontSize: 12, color: "var(--neutral-70)" }}>
                    {r.category === "worker" ? "Worker-level" : "Per-assignment"}
                  </td>
                  <td style={{ padding: "12px 14px", fontSize: 13, fontVariantNumeric: "tabular-nums" }}>{b.at || <span style={{ color: "var(--neutral-50)" }}>—</span>}</td>
                  <td style={{ padding: "12px 14px" }}>
                    <Badge color={b.state === "signed" ? "green" : b.state === "expired" ? "red" : b.state === "in-progress" ? "blue" : "neutral"} dot={["signed","expired","in-progress"].includes(b.state)}>
                      {b.state === "signed" ? "Signed" : b.state === "expired" ? "Expired" : b.state === "in-progress" ? "In progress" : b.state === "n/a" ? "Not required" : "Not started"}
                    </Badge>
                  </td>
                  <td style={{ padding: "12px 14px", textAlign: "right" }}>
                    {b.state === "signed" && <Button color="secondary" size="sm" iconStart="download-1">PDF</Button>}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>
    </>
  );
}

Object.assign(window, { WorkerNav, WorkerHome, WorkerAssignmentsView, WorkerSignFlow, WorkerDocumentsView });

})();
