/* FORGE · pump tenant — Factory Acceptance Test (FAT) certificate.
   Babel-standalone in-browser; NO ES imports / exports.
   Wrapped in IIFE; exposes ScreenFAT on window.

   Printable per-serial view: lists all 7 station check-ins, every captured
   measurement, all 30 quality gates with pass/fail flags. Signature blocks
   for Neha G. (test) and Rohit B. (final QC). Print button uses window.print().

   Route registered as /traveler/fat (mode=traveler).
   Read `?serial=` from window.location.hash or fall back to first serial
   whose completed_stations covers all 7 routing IDs.
*/
(function _initScreenFAT() {
  if (typeof window === "undefined") return;
  if (typeof React === "undefined") return;

  const { useState, useMemo, useEffect } = React;

  function _fatNowISO() {
    return new Date().toISOString().replace("T", " ").slice(0, 16) + "Z";
  }

  // Parse `?serial=...` from a URL-like string. Supports both real URLs and hash routes.
  function _fatGetSerialFromUrl() {
    if (typeof window === "undefined") return null;
    const search = (window.location && window.location.search) || "";
    const hash = (window.location && window.location.hash) || "";
    const blob = search + " " + hash;
    const m = blob.match(/[?&]serial=([A-Za-z0-9_-]+)/);
    return m ? m[1] : null;
  }

  function _fatSpecPass(spec, captured) {
    if (captured === "" || captured === null || captured === undefined) return null;
    const n = Number(captured);
    if (Number.isNaN(n)) {
      // string spec: pass if captured contains "pass" or matches spec keywords
      const c = String(captured).toLowerCase();
      if (/pass|ok|no breakdown|zero|match/.test(c)) return true;
      if (/fail|breakdown|leak|short/.test(c)) return false;
      return true;
    }
    const s = String(spec || "");
    let m;
    if ((m = s.match(/(-?\d+(?:\.\d+)?)\s*[-–]\s*(-?\d+(?:\.\d+)?)/))) {
      return n >= Number(m[1]) && n <= Number(m[2]);
    }
    if ((m = s.match(/(-?\d+(?:\.\d+)?)\s*±\s*(\d+(?:\.\d+)?)\s*%/))) {
      const c = Number(m[1]); const p = Number(m[2]) / 100;
      return n >= c * (1 - p) && n <= c * (1 + p);
    }
    if ((m = s.match(/(-?\d+(?:\.\d+)?)\s*±\s*(-?\d+(?:\.\d+)?)/))) {
      const c = Number(m[1]); const d = Number(m[2]);
      return n >= c - d && n <= c + d;
    }
    if ((m = s.match(/[<≤]\s*(-?\d+(?:\.\d+)?)/))) return n <= Number(m[1]);
    if ((m = s.match(/[>≥]\s*(-?\d+(?:\.\d+)?)/))) return n >= Number(m[1]);
    return true;
  }

  const _FAT_PRINT_STYLE = `
    @media print {
      body * { visibility: hidden; }
      #forge-fat-doc, #forge-fat-doc * { visibility: visible; }
      #forge-fat-doc { position: absolute; left: 0; top: 0; width: 100%; background: white; }
      .fat-no-print { display: none !important; }
      .fat-page-break { page-break-after: always; }
    }
  `;

  function ScreenFAT() {
    const tenant = (typeof useActiveTenant === "function") ? useActiveTenant() : (window.PUMP_TENANT || {});
    if (typeof window.hydratePumpTenant === "function") window.hydratePumpTenant();

    const allTravelers = (tenant && tenant.travelers) || [];
    const routing = ((tenant && tenant.routing) || []).slice().sort(function(a, b) { return a.seq - b.seq; });
    const allGates = (tenant && tenant.quality_gates) || [];
    const routingIds = routing.map(function(r) { return r.id; });

    // Pick serial — URL param > first traveler that has completed all 7 stations > first traveler.
    const urlSerial = _fatGetSerialFromUrl();
    const fallbackSerial = allTravelers.find(function(t) {
      return routingIds.every(function(sid) { return (t.completed_stations || []).indexOf(sid) >= 0; });
    }) || allTravelers[0];
    const [serial, setSerial] = useState(urlSerial || (fallbackSerial && fallbackSerial.serial) || "");

    const traveler = useMemo(function() {
      return allTravelers.find(function(t) { return t.serial === serial; });
    }, [serial, allTravelers.length]);

    const wo = useMemo(function() {
      if (!traveler) return null;
      return ((tenant && tenant.work_orders) || []).find(function(w) { return w.id === traveler.wo; });
    }, [traveler, tenant]);

    const sku = wo && wo.sku;
    const customer = wo && wo.customer;
    const sigTest = "Neha G.";
    const sigFinal = "Rohit B.";
    const certId = "FAT-" + (serial || "—") + "-" + _fatNowISO().slice(0, 10).replace(/-/g, "");

    function printNow() { if (typeof window !== "undefined") window.print(); }

    if (!traveler) {
      return React.createElement(
        "div",
        { style: { padding: 24, textAlign: "center", color: "var(--ink-4)" } },
        "Serial not found. Choose a serial below.",
        React.createElement(
          "div",
          { style: { marginTop: 16, display: "flex", justifyContent: "center", gap: 8 } },
          allTravelers.slice(0, 10).map(function(t) {
            return React.createElement(
              "button",
              { key: t.serial, className: "btn", onClick: function() { setSerial(t.serial); } },
              t.serial
            );
          })
        )
      );
    }

    // Group gates by station (in routing order) and join with check-ins for this serial.
    const checkinsByStation = {};
    (traveler.checkins || []).forEach(function(c) {
      const sid = c.station_id;
      if (!checkinsByStation[sid]) checkinsByStation[sid] = [];
      checkinsByStation[sid].push(c);
    });

    return React.createElement(
      "div",
      { style: { display: "flex", flexDirection: "column", height: "100%", minHeight: 0 } },
      React.createElement("style", null, _FAT_PRINT_STYLE),

      // Toolbar (hidden on print)
      React.createElement(
        "div",
        {
          className: "fat-no-print",
          style: {
            padding: "10px 14px", background: "var(--bg-2)",
            borderBottom: "1px solid var(--line)",
            display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12,
          },
        },
        React.createElement("div", null,
          React.createElement("div", { style: { fontSize: 14, color: "var(--ink)", fontWeight: 500 } }, "Factory Acceptance Test"),
          React.createElement("div", { className: "mono", style: { fontSize: 12, color: "var(--ink-4)", marginTop: 2 } }, certId)
        ),
        React.createElement("div", { style: { display: "flex", gap: 8, alignItems: "center" } },
          React.createElement("label", { className: "label", htmlFor: "fat-serial-select" }, "serial:"),
          React.createElement(
            "select",
            {
              id: "fat-serial-select",
              name: "fat-serial-select",
              value: serial,
              onChange: function(e) { setSerial(e.target.value); },
              style: { padding: "5px 8px", border: "1px solid var(--line)", background: "var(--bg-0)", color: "var(--ink)", borderRadius: 3, fontSize: 13, fontFamily: "var(--font-mono)" },
            },
            allTravelers.map(function(t) {
              const done = routingIds.every(function(sid) { return (t.completed_stations || []).indexOf(sid) >= 0; });
              return React.createElement("option", { key: t.serial, value: t.serial }, t.serial + (done ? " ✓" : ""));
            })
          ),
          React.createElement(window.Btn || "button", { variant: "primary", icon: "File", onClick: printNow }, "Print certificate")
        )
      ),

      // The printable doc
      React.createElement(
        "div",
        {
          id: "forge-fat-doc",
          style: {
            flex: 1, overflow: "auto",
            padding: "32px 48px",
            background: "white",
            color: "#222",
            fontFamily: "var(--font-ui), system-ui, sans-serif",
          },
        },

        // Title
        React.createElement(
          "div",
          { style: { display: "flex", justifyContent: "space-between", alignItems: "flex-end", borderBottom: "2px solid #333", paddingBottom: 12, marginBottom: 18 } },
          React.createElement("div", null,
            React.createElement("div", { style: { fontSize: 11, letterSpacing: "0.18em", color: "#666", fontFamily: "var(--font-mono)" } }, "FORGE · " + (tenant && tenant.tenant && tenant.tenant.id || "tritan").toUpperCase()),
            React.createElement("div", { style: { fontSize: 24, fontWeight: 700, marginTop: 4 } }, "Factory Acceptance Test"),
            React.createElement("div", { style: { fontSize: 13, color: "#444", marginTop: 4 } }, (tenant && tenant.tenant && tenant.tenant.name) || "Tritan Pumps Pvt Ltd"),
          ),
          React.createElement("div", { style: { textAlign: "right" } },
            React.createElement("div", { style: { fontSize: 11, letterSpacing: "0.12em", color: "#666", fontFamily: "var(--font-mono)" } }, "CERTIFICATE NO."),
            React.createElement("div", { style: { fontSize: 14, fontFamily: "var(--font-mono)", fontWeight: 600, marginTop: 2 } }, certId),
            React.createElement("div", { style: { fontSize: 12, color: "#666", marginTop: 4 } }, "Issued " + _fatNowISO())
          )
        ),

        // Identification block
        React.createElement(
          "div",
          { style: { display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", gap: 18, marginBottom: 24, fontSize: 13 } },
          React.createElement("div", null,
            React.createElement("div", { style: { fontSize: 10, letterSpacing: "0.12em", color: "#888", textTransform: "uppercase" } }, "Serial number"),
            React.createElement("div", { style: { fontFamily: "var(--font-mono)", fontWeight: 600, marginTop: 4 } }, traveler.serial)
          ),
          React.createElement("div", null,
            React.createElement("div", { style: { fontSize: 10, letterSpacing: "0.12em", color: "#888", textTransform: "uppercase" } }, "Work order"),
            React.createElement("div", { style: { fontFamily: "var(--font-mono)", marginTop: 4 } }, traveler.wo)
          ),
          React.createElement("div", null,
            React.createElement("div", { style: { fontSize: 10, letterSpacing: "0.12em", color: "#888", textTransform: "uppercase" } }, "SKU"),
            React.createElement("div", { style: { fontFamily: "var(--font-mono)", marginTop: 4 } }, sku || "—")
          ),
          React.createElement("div", null,
            React.createElement("div", { style: { fontSize: 10, letterSpacing: "0.12em", color: "#888", textTransform: "uppercase" } }, "Customer"),
            React.createElement("div", { style: { fontSize: 13, marginTop: 4 } }, customer || "—")
          )
        ),

        // Stations summary table
        React.createElement(
          "div",
          { style: { marginBottom: 20 } },
          React.createElement("div", { style: { fontSize: 11, letterSpacing: "0.12em", color: "#888", textTransform: "uppercase", marginBottom: 8 } }, "Station traversal · 7 of 7"),
          React.createElement(
            "table",
            { style: { width: "100%", borderCollapse: "collapse", fontSize: 12 } },
            React.createElement(
              "thead",
              null,
              React.createElement(
                "tr",
                { style: { borderBottom: "1px solid #ccc", textAlign: "left" } },
                ["Seq", "Station", "Owner", "Cycle", "Check-ins", "Status"].map(function(h) {
                  return React.createElement("th", { key: h, style: { padding: "6px 4px", color: "#666", fontWeight: 500, fontSize: 11, letterSpacing: "0.06em", textTransform: "uppercase" } }, h);
                })
              )
            ),
            React.createElement(
              "tbody",
              null,
              routing.map(function(stn) {
                const stnCheckins = checkinsByStation[stn.id] || [];
                const done = (traveler.completed_stations || []).indexOf(stn.id) >= 0;
                return React.createElement(
                  "tr",
                  { key: stn.id, style: { borderBottom: "1px solid #eee" } },
                  React.createElement("td", { style: { padding: "6px 4px", fontFamily: "var(--font-mono)" } }, stn.seq),
                  React.createElement("td", { style: { padding: "6px 4px" } }, stn.name + " (" + stn.id + ")"),
                  React.createElement("td", { style: { padding: "6px 4px" } }, stn.owner),
                  React.createElement("td", { style: { padding: "6px 4px", fontFamily: "var(--font-mono)" } }, stn.cycle_min + " min"),
                  React.createElement("td", { style: { padding: "6px 4px", fontFamily: "var(--font-mono)" } }, stnCheckins.length),
                  React.createElement("td", { style: { padding: "6px 4px", color: done ? "#1a7f37" : "#9a3412", fontWeight: 600 } }, done ? "PASS" : (traveler.current_station === stn.id ? "IN-PROCESS" : "PENDING"))
                );
              })
            )
          )
        ),

        // Quality gates by station — one block per gate (30 in total).
        React.createElement(
          "div",
          { style: { marginBottom: 24 } },
          React.createElement("div", { style: { fontSize: 11, letterSpacing: "0.12em", color: "#888", textTransform: "uppercase", marginBottom: 8 } }, "Quality gates · 30 critical-to-quality checks"),
          routing.map(function(stn) {
            const stnGates = allGates.filter(function(g) { return g.station === stn.id; });
            if (stnGates.length === 0) return null;
            return React.createElement(
              "div",
              { key: stn.id, style: { marginBottom: 16, border: "1px solid #ddd", borderRadius: 4, padding: 12 } },
              React.createElement("div", { style: { fontSize: 12, color: "#444", fontWeight: 600, marginBottom: 8, paddingBottom: 6, borderBottom: "1px solid #eee" } },
                stn.id.toUpperCase() + " — " + stn.name + " · " + stnGates.length + " gates"
              ),
              stnGates.map(function(g) {
                // Find a captured value for this gate in any check-in for this serial.
                let captured = null;
                (traveler.checkins || []).forEach(function(c) {
                  if (c.dimensions && c.dimensions[g.gate_id] !== undefined) captured = c.dimensions[g.gate_id];
                });
                const pass = _fatSpecPass(g.spec, captured);
                const passLabel = captured === null ? "—" : (pass ? "PASS" : "FAIL");
                const passColor = captured === null ? "#9ca3af" : (pass ? "#1a7f37" : "#b91c1c");
                return React.createElement(
                  "div",
                  {
                    key: g.gate_id,
                    style: {
                      display: "grid", gridTemplateColumns: "60px 1.6fr 1.2fr 1fr 1fr 70px",
                      gap: 8, alignItems: "baseline",
                      padding: "5px 0",
                      borderBottom: "1px dashed #eee",
                      fontSize: 11,
                    },
                  },
                  React.createElement("span", { style: { fontFamily: "var(--font-mono)", fontWeight: 600, color: "#444" } }, g.gate_id),
                  React.createElement("span", null, g.ctq_param),
                  React.createElement("span", { style: { color: "#666" } }, g.instrument),
                  React.createElement("span", { style: { fontFamily: "var(--font-mono)", color: "#444" } }, g.spec),
                  React.createElement("span", { style: { fontFamily: "var(--font-mono)", color: "#222" } }, captured === null ? "—" : String(captured)),
                  React.createElement("span", { style: { fontFamily: "var(--font-mono)", color: passColor, fontWeight: 600 } }, passLabel)
                );
              })
            );
          })
        ),

        // Notes & disposition history
        (traveler.checkins || []).filter(function(c) { return c.type === "disposition" || c.type === "hold"; }).length > 0 && React.createElement(
          "div",
          { style: { marginBottom: 24 } },
          React.createElement("div", { style: { fontSize: 11, letterSpacing: "0.12em", color: "#888", textTransform: "uppercase", marginBottom: 8 } }, "Hold / disposition history"),
          (traveler.checkins || []).filter(function(c) { return c.type === "disposition" || c.type === "hold"; }).map(function(c, i) {
            return React.createElement(
              "div",
              { key: i, style: { padding: "6px 0", fontSize: 12, borderBottom: "1px dashed #eee" } },
              React.createElement("span", { style: { fontFamily: "var(--font-mono)", color: "#666", marginRight: 8 } }, new Date(c.ts).toISOString().slice(0, 16)),
              React.createElement("span", { style: { color: "#b91c1c", fontWeight: 600, marginRight: 8 } }, (c.type || "event").toUpperCase()),
              React.createElement("span", { style: { color: "#444" } }, "at " + (c.station_id || "—") + " — " + (c.reason || c.measurement_notes || "—") + (c.dispo_path ? " · path=" + c.dispo_path : ""))
            );
          })
        ),

        // Signatures
        React.createElement(
          "div",
          { style: { marginTop: 32, paddingTop: 18, borderTop: "2px solid #333", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32 } },
          React.createElement(
            "div",
            null,
            React.createElement("div", { style: { fontSize: 10, letterSpacing: "0.12em", color: "#666", textTransform: "uppercase" } }, "Test cell sign-off"),
            React.createElement("div", { style: { marginTop: 28, paddingTop: 6, borderTop: "1px solid #999", fontSize: 13, fontWeight: 600 } }, sigTest),
            React.createElement("div", { style: { fontSize: 11, color: "#666", marginTop: 2 } }, "Motor Assy / Test Operator (s5+s6)"),
            React.createElement("div", { style: { fontSize: 11, fontFamily: "var(--font-mono)", color: "#888", marginTop: 6 } }, "Signed · " + _fatNowISO())
          ),
          React.createElement(
            "div",
            null,
            React.createElement("div", { style: { fontSize: 10, letterSpacing: "0.12em", color: "#666", textTransform: "uppercase" } }, "Final QC sign-off"),
            React.createElement("div", { style: { marginTop: 28, paddingTop: 6, borderTop: "1px solid #999", fontSize: 13, fontWeight: 600 } }, sigFinal),
            React.createElement("div", { style: { fontSize: 11, color: "#666", marginTop: 2 } }, "Machine Shop / Pump Assy Lead (s4+s7)"),
            React.createElement("div", { style: { fontSize: 11, fontFamily: "var(--font-mono)", color: "#888", marginTop: 6 } }, "Signed · " + _fatNowISO())
          )
        ),

        // Footer
        React.createElement(
          "div",
          { style: { marginTop: 32, paddingTop: 12, borderTop: "1px solid #ddd", fontSize: 10, color: "#888", fontFamily: "var(--font-mono)", display: "flex", justifyContent: "space-between" } },
          React.createElement("span", null, "Forge ledger · ed25519-signed event chain"),
          React.createElement("span", null, certId + " · 1 of 1")
        )
      )
    );
  }

  window.ScreenFAT = ScreenFAT;

  if (typeof window.registerPumpRoute === "function") {
    window.registerPumpRoute({
      path: "/traveler/fat",
      mode: "traveler",
      title: "FAT certificate",
      renderer: function() { return React.createElement(ScreenFAT); },
    });
  }
})();
