/* === Contracts — CAPS deadlines (list / timeline; show expired) === */

const { useState: useStateC } = React;

function ContractsView() {
  const contracts = window.CONTRACTS;
  const pending = window.PENDING_CONTRACTS || [];

  const [view, setView] = useStateC("list");
  const [showExpired, setShowExpired] = useStateC(false);

  // Bucket by expiry urgency (executed contracts)
  const today = new Date();
  function months(d) {
    const dt = new Date(d);
    return Math.round((dt - today) / (1000 * 60 * 60 * 24 * 30));
  }
  const buckets = {
    "Expired":            [],
    "1–3 months":         [],
    "3–5 months":         [],
    "5+ months / active": [],
  };
  for (const c of contracts) {
    const m = months(c.expire);
    if (m < 0) buckets["Expired"].push(c);
    else if (m <= 3) buckets["1–3 months"].push(c);
    else if (m <= 5) buckets["3–5 months"].push(c);
    else buckets["5+ months / active"].push(c);
  }

  const expired = buckets["Expired"].length;
  const within3 = buckets["1–3 months"].length;
  const within5 = buckets["3–5 months"].length;
  const active = buckets["5+ months / active"].length;

  return (
    <div>
      <div className="work-head">
        <div className="row" style={{ gap: 8 }}>
          <ViewToggle value={view} onChange={setView} />
          <label className="row" style={{ gap: 6, fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-2)", cursor: "pointer", userSelect: "none" }}>
            <input type="checkbox" checked={showExpired} onChange={(e) => setShowExpired(e.target.checked)} />
            Show expired
          </label>
        </div>
        <button className="btn">+ New contract request</button>
      </div>

      {/* Tab summary */}
      <div className="tab-summary">
        <SumStat label="Active" value={active} />
        <SumStat label="3–5 months" value={within5} muted />
        <SumStat label="1–3 months" value={within3} accent={within3 > 0 ? "yellow" : null} />
        <SumStat label="Expired" value={expired} accent={expired > 0 ? "red" : null} />
        <SumStat label="Pending in CAPS" value={pending.length} muted />
      </div>

      {view === "timeline" ? (
        <FirmnessTimeline
          fuzziness="medium"
          title="Contracts — expiry windows"
          sub="Real spans, begin → expire · navy = active, yellow = at risk, red = expired."
          items={[]}
          contracts={window.contractsToTimeline(contracts, { includeExpired: showExpired })}
          contractsLabel="Contracts"
        />
      ) : (
        <>
          {/* Pending — moving through CAPS, not yet executed */}
          {pending.length > 0 ? (
            <div style={{ marginBottom: 22 }}>
              <div className="section-head">
                <div>
                  <div className="section-title" style={{ fontSize: 16 }}>Pending in CAPS</div>
                  <div className="section-sub">Working through approvals — not yet executed.</div>
                </div>
                <Chip kind="accent">{pending.length}</Chip>
              </div>
              <div className="card">
                {pending.map((c, i) => (
                  <div className="list-row" key={i} style={{ gridTemplateColumns: "1.6fr 1fr 1fr auto", padding: "12px 16px" }}>
                    <div>
                      <div style={{ fontWeight: 600, fontSize: 13 }}>{c.vendor}</div>
                      <div className="mono faint" style={{ fontSize: 11, marginTop: 2 }}>{c.type} · {c.caps} · initiated {fmtDate(c.initiated)}</div>
                      <div style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 6, fontStyle: "italic" }}>{c.blocker}</div>
                    </div>
                    <div>
                      <Chip kind="soft">{c.stage}</Chip>
                    </div>
                    <div className="mono" style={{ fontSize: 12, color: c.daysInStage > 10 ? "var(--yellow)" : "var(--ink-2)" }}>
                      {c.daysInStage} days in stage
                    </div>
                    <div>
                      <button className="btn btn--ghost">Detail →</button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ) : null}

          {/* Executed by expiry */}
          <div className="section-head">
            <div>
              <div className="section-title" style={{ fontSize: 16 }}>Executed — by expiry urgency</div>
            </div>
          </div>
          <div className="contracts-grid">
            {Object.entries(buckets).map(([title, rows]) => {
              if (title === "Expired" && !showExpired) return null;
              const cls = title === "Expired" ? "expired" : title === "1–3 months" ? "soon" : "";
              return (
                <div key={title} className={`contract-bucket ${cls ? `contract-bucket--${cls}` : ""}`}>
                  <div className="contract-bucket__head">
                    <div className="contract-bucket__title">{title}</div>
                    <div className="contract-bucket__count">{rows.length}</div>
                  </div>
                  <div style={{ marginTop: 8 }}>
                    {rows.length === 0 && <div className="muted" style={{ fontSize: 12 }}>—</div>}
                    {rows.map((c, i) => (
                      <div className="contract-row" key={i}>
                        <div className="contract-row__name">{c.vendor}</div>
                        <div className="contract-row__meta">
                          <span style={{ color: c.type === "GRT" ? "var(--navy)" : "var(--ink-2)" }}>{c.type}</span>
                          <span> · expires {fmtDate(c.expire)}</span>
                        </div>
                        <PercentBar pct={c.pctRemaining} contract={c} />
                        {c.followup && c.followup !== "—" ? (
                          <div style={{ fontSize: 11, color: "var(--ink-2)", marginTop: 4, fontStyle: "italic" }}>{c.followup}</div>
                        ) : null}
                      </div>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
        </>
      )}
    </div>
  );
}

function PercentBar({ pct, contract }) {
  // 0..1; computed at ingestion. We never store the underlying $ amount.
  const v = Math.round(pct * 100);
  // Burn rate: compare %-remaining vs %-time-remaining
  const today = new Date();
  const begin = new Date(contract.begin);
  const expire = new Date(contract.expire);
  const totalDays = (expire - begin) / (1000 * 60 * 60 * 24);
  const remainingDays = Math.max(0, (expire - today) / (1000 * 60 * 60 * 24));
  const timeLeftPct = totalDays > 0 ? remainingDays / totalDays : 0;
  // Burn signal: budget remaining - time remaining (positive = under-burning, negative = over-burning)
  const burn = pct - timeLeftPct;
  let burnLabel = null, burnColor = "var(--ink-mute)", burnSym = "—";
  if (remainingDays <= 0) {
    burnLabel = "expired"; burnColor = "var(--red)"; burnSym = "·";
  } else if (burn < -0.15) {
    burnLabel = "burning hot"; burnColor = "var(--red)"; burnSym = "↑";
  } else if (burn < -0.05) {
    burnLabel = "spending fast"; burnColor = "var(--yellow)"; burnSym = "↗";
  } else if (burn > 0.15) {
    burnLabel = "under-utilizing"; burnColor = "var(--yellow)"; burnSym = "↓";
  } else {
    burnLabel = "on pace"; burnColor = "var(--green)"; burnSym = "→";
  }
  return (
    <div style={{ marginTop: 6 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <div style={{
          flex: 1, height: 4, borderRadius: 99, background: "var(--surface-3)", overflow: "hidden",
        }}>
          <div style={{ width: `${v}%`, height: "100%", background: "var(--navy)", transition: "width .2s" }}></div>
        </div>
        <span className="mono" style={{ fontSize: 11, color: "var(--ink-2)", fontWeight: 500, minWidth: 60, textAlign: "right" }}>
          {v}% remaining
        </span>
      </div>
      <div style={{ marginTop: 3, display: "flex", justifyContent: "space-between", fontFamily: "var(--mono)", fontSize: 10, color: "var(--ink-faint)" }}>
        <span>{Math.round(timeLeftPct * 100)}% time left</span>
        <span style={{ color: burnColor, fontWeight: 600, textTransform: "uppercase", letterSpacing: ".08em" }}>
          {burnSym} {burnLabel}
        </span>
      </div>
    </div>
  );
}

function fmtDate(d) {
  const dt = new Date(d);
  const mo = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][dt.getMonth()];
  return `${mo} ${dt.getDate()}, ${dt.getFullYear()}`;
}

Object.assign(window, { ContractsView, PercentBar });
