// FORGE pump tenant — ProgramCard
// M-27418 program card: derived progress, next milestone, lead avatar, days-to-due.
// All numbers computed on render from PUMP_TENANT.work_orders + .program.
//
// Babel-standalone IIFE pattern. NO module imports.
// Attaches: window.ProgramCard
(function () {
  const { useMemo, useEffect } = React;

  // ── Initials helper (matches activity-stream) ────────────────────────
  function initialsOf(name) {
    if (!name) return "??";
    const parts = String(name).trim().split(/\s+/);
    const first = parts[0] ? parts[0][0] : "";
    const last = parts.length > 1 ? parts[parts.length - 1][0] : "";
    return (first + last).toUpperCase();
  }

  // ── Days-to-due (color band) ─────────────────────────────────────────
  // Prefers working-day arithmetic via window.forgeCalendar, anchored
  // against the tenant's holiday calendar (IN-2026 / US-2026 / DE-2026
  // — see migrate-003-cosmopolitan.mjs). Falls back to calendar-day
  // arithmetic when forge-calendar.js hasn't bootstrapped yet, so the
  // card still paints something on first render.
  function daysUntil(dateStr) {
    if (!dateStr) return null;
    if (window.forgeCalendar && typeof window.forgeCalendar.workingDaysBetween === "function") {
      const today = new Date().toISOString().slice(0, 10);
      return window.forgeCalendar.workingDaysBetween(
        today,
        dateStr,
        window.__forgeHolidaysCache || []
      );
    }
    const due = new Date(dateStr).getTime();
    const now = Date.now();
    return Math.round((due - now) / 86400000);
  }

  function dueColor(days) {
    if (days == null) return "var(--ink-3)";
    if (days < 7)  return "var(--err)";
    if (days < 30) return "var(--warn)";
    return "var(--ok)";
  }

  // ── Derive program progress (avg of station_progress means for WOs in program) ─
  // Spec: avg(work_orders.filter(wo.program === 'M-27418').map(w => w.station_progress || 0))
  // Fixture reality: work_orders have `sku` not `program`; station_progress is {s1..s7}.
  // We average station values per WO, then average across matching WOs.
  function deriveProgress(workOrders, code) {
    const matched = (workOrders || []).filter(function (w) { return w.sku === code; });
    if (matched.length === 0) return 0;
    const perWoAvg = matched.map(function (w) {
      const sp = w.station_progress;
      if (!sp || typeof sp !== "object") return typeof sp === "number" ? sp : 0;
      const vals = Object.keys(sp).map(function (k) { return Number(sp[k]) || 0; });
      if (vals.length === 0) return 0;
      return vals.reduce(function (a, b) { return a + b; }, 0) / vals.length;
    });
    return perWoAvg.reduce(function (a, b) { return a + b; }, 0) / perWoAvg.length;
  }

  // ── ProgramCard ──────────────────────────────────────────────────────
  function ProgramCard({ tenant, code, onOpen }) {
    const t = tenant || (typeof window !== "undefined" && typeof window.getActiveTenant === "function" ? window.getActiveTenant() : null);
    const program = (t && t.program) || {};
    const wos = (t && t.work_orders) || [];
    const targetCode = code || program.code || "M-27418";

    // Preload the tenant holiday calendar on mount so subsequent renders
    // (and other cards on the same screen) get working-day arithmetic.
    // Cached on window.__forgeHolidaysCache; the IIFE in forge-calendar.js
    // also memoises per-tab.
    useEffect(function () {
      if (window.forgeCalendar && typeof window.forgeCalendar.loadHolidays === "function") {
        window.forgeCalendar.loadHolidays().then(function (h) {
          window.__forgeHolidaysCache = h || [];
        });
      }
    }, []);

    const progress = useMemo(function () { return deriveProgress(wos, targetCode); }, [wos, targetCode]);
    const matchedWOs = wos.filter(function (w) { return w.sku === targetCode; });
    const days = daysUntil(program.due_date);
    const dColor = dueColor(days);

    const open = function () {
      if (typeof onOpen === "function") onOpen(program);
      else if (typeof window.navigate === "function") window.navigate("/plan/gantt");
      else window.location.hash = "/plan/gantt";
    };

    const _wrapStyle = {
      padding: 14,
      border: "1px solid var(--line-soft)",
      borderRadius: 8,
      background: "var(--bg-1)",
      display: "grid",
      gap: 10,
    };
    const _avatarStyle = {
      width: 36, height: 36, borderRadius: 36,
      background: "var(--bg-3)",
      border: "1px solid var(--accent)",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--accent)",
      flexShrink: 0,
    };

    return (
      <Panel
        title={"Program · " + (program.code || targetCode)}
        right={
          <>
            <Pill tone="accent">Rev {program.revision || "B"}</Pill>
            <Btn size="sm" icon="ArrowR" onClick={open}>Open program</Btn>
          </>
        }
      >
        <div style={_wrapStyle}>
          {/* Header: name + lead avatar */}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12 }}>
            <div style={{ minWidth: 0 }}>
              <div className="serif" style={{ fontSize: 22, lineHeight: 1.15 }}>
                {program.name || targetCode}
              </div>
              <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>
                {(program.customer || "—") + " · " + (program.qty || "—") + " units · " + (program.phase || "Industrialize")}
              </div>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span style={_avatarStyle} title={"Program lead · " + (program.lead || "—")}>
                {initialsOf(program.lead)}
              </span>
              <div style={{ minWidth: 0 }}>
                <div className="label">Lead</div>
                <div className="mono" style={{ fontSize: 12, color: "var(--ink-2)" }}>
                  {program.lead || "—"}
                </div>
              </div>
            </div>
          </div>

          {/* Progress bar */}
          <div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
              <span className="label">Progress · derived from {matchedWOs.length} WO{matchedWOs.length === 1 ? "" : "s"}</span>
              <span className="mono tnum" style={{ fontSize: 12, color: "var(--ink)" }}>
                {Math.round(progress * 100)}%
              </span>
            </div>
            <Progress value={progress} />
          </div>

          {/* Milestone + due strip */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, borderTop: "1px solid var(--line-soft)", paddingTop: 10 }}>
            <div>
              <div className="label">Next milestone</div>
              <div style={{ fontSize: 13, color: "var(--ink)", marginTop: 3 }}>
                {program.nextMilestone || "—"}
              </div>
              <div className="mono" style={{ fontSize: 12, color: "var(--ink-4)", marginTop: 2 }}>
                {(function () {
                  if (!program.nextDate) return "—";
                  var i18n = (typeof window !== "undefined") ? window.forgeI18n : null;
                  if (i18n && typeof i18n.formatDate === "function") {
                    return i18n.formatDate(program.nextDate) || program.nextDate;
                  }
                  return program.nextDate;
                })()}
              </div>
            </div>
            <div>
              <div className="label">Working days to due</div>
              <div className="mono tnum" style={{ fontSize: 22, color: dColor, marginTop: 3 }}>
                {days == null ? "—" : (days < 0 ? Math.abs(days) + "d over" : days + "d")}
              </div>
              <div className="mono" style={{ fontSize: 12, color: "var(--ink-4)", marginTop: 2 }}>
                due {(function () {
                  if (!program.due_date) return "—";
                  // Locale-aware: en-IN renders "24-06-2026", en-US renders
                  // "06/24/2026", de-DE renders "24.06.2026".
                  var i18n = (typeof window !== "undefined") ? window.forgeI18n : null;
                  if (i18n && typeof i18n.formatDate === "function") {
                    return i18n.formatDate(program.due_date) || program.due_date;
                  }
                  return program.due_date;
                })()}
              </div>
            </div>
          </div>
        </div>
      </Panel>
    );
  }

  window.ProgramCard = ProgramCard;
})();
