// ADM-PROC-13 · Gate-in detail (AMOMS Module 1)
// Admin Web · Procurement Manager · P0 · 1440×900
// A single accepted offer → gate-in. The gate pass (QR) only goes live once the
// farmer confirms in their app; it is then shown to both sides. Registered as window.Pages.approve

const Ic13 = window.Icons;
const KES13 = (n) => "KSh " + (Number(n) || 0).toLocaleString("en-US");

// The gate-in being viewed (Mary Wairimu's accepted offer against PR-2026-0184)
const GI = {
  gpn: "GPN-26851",
  farmer: "Mary Wairimu", farmerId: "F-2731", region: "Kangema, Murang'a", tier: "A",
  req: "PR-2026-0184", product: "Hass",
  qty: 6200, rate: 92,
  date: "Thu 15 May 2026", window: "08:00 – 11:00", gateLoc: "Gate 2 · AMOMS, Kangema Road",
};

// ── Deterministic QR-ish block (faithful placeholder, not scannable) ──
const QR13 = ({ value = "GPN", size = 200 }) => {
  const n = 27;
  const cells = useMemo(() => {
    let h = 2166136261;
    for (let i = 0; i < value.length; i++) { h ^= value.charCodeAt(i); h = Math.imul(h, 16777619); }
    const rng = () => { h ^= h << 13; h ^= h >>> 17; h ^= h << 5; return (h >>> 0) / 4294967296; };
    const g = Array.from({ length: n }, () => Array.from({ length: n }, () => rng() > 0.52));
    const finder = (r, c) => {
      for (let i = -1; i <= 7; i++) for (let j = -1; j <= 7; j++) {
        const rr = r + i, cc = c + j; if (rr < 0 || cc < 0 || rr >= n || cc >= n) continue;
        if (i >= 0 && i <= 6 && j >= 0 && j <= 6) {
          const border = (i === 0 || i === 6) || (j === 0 || j === 6);
          const core = i >= 2 && i <= 4 && j >= 2 && j <= 4;
          g[rr][cc] = border || core;
        } else g[rr][cc] = false;
      }
    };
    finder(0, 0); finder(0, n - 7); finder(n - 7, 0);
    return g;
  }, [value]);
  const m = size / n;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ display: "block" }}>
      {cells.map((row, r) => row.map((on, c) => on
        ? <rect key={r + "-" + c} x={c * m} y={r * m} width={m + 0.4} height={m + 0.4} rx={m * 0.16} fill="#10140f" />
        : null))}
    </svg>
  );
};

const GateInDetail = ({ tweaks }) => {
  const toast = useToast();
  const go = window.makeGo(toast);
  const state = (tweaks && tweaks.gateInState) || "awaitingFarmer"; // awaitingFarmer | confirmed | arrived
  const live = state === "confirmed" || state === "arrived";
  const arrived = state === "arrived";
  const value = GI.qty * GI.rate;

  // Timeline steps with their done/active state
  const steps = [
    { key: "accepted",  title: "Offer accepted by you", desc: `You accepted ${GI.farmer}'s offer of ${GI.qty.toLocaleString("en-US")} kg @ ${KES13(GI.rate)}/kg.`, done: true },
    { key: "awaiting",  title: "Awaiting farmer confirmation", desc: "Sent to the farmer's app. They confirm the proposed date & time.", done: live, active: !live },
    { key: "confirmed", title: "Farmer confirmed — gate pass active", desc: "The QR gate pass is now live and visible to both of you.", done: live, active: false },
    { key: "arrived",   title: "Arrived at gate", desc: arrived ? "Truck verified at Gate 2. Proceeding to weighbridge & QC." : "The gate keeper scans the pass on arrival.", done: arrived, active: false },
  ];

  return (
    <div className="page gi-page">
      <div className="gi-head">
        <button className="btn btn-ghost btn-icon" aria-label="Back" onClick={() => go("ADM-PROC-10.html")}><Ic13.ChevronLeft size={18} /></button>
        <div style={{ flex: 1, minWidth: 0 }}>
          <h1 className="gi-title">Gate-in — <span className="mono" style={{ fontWeight: 600 }}>{GI.gpn}</span></h1>
          <div className="muted" style={{ fontSize: 12.5, marginTop: 2 }}>{GI.farmer} · {GI.req} · {GI.product}</div>
        </div>
        <span className={`gi-state-badge ${live ? (arrived ? "arrived" : "live") : "awaiting"}`}>
          {live ? <Ic13.CheckCircle size={14} /> : <Ic13.Clock size={14} />}
          {arrived ? "Arrived" : live ? "Gate pass active" : "Awaiting farmer"}
        </span>
        <Button variant="outline" icon={Ic13.Calendar} onClick={() => go("ADM-PROC-16.html")}>Schedule</Button>
      </div>

      <div className="gi-cols">
        {/* Left — timeline + details */}
        <div>
          <Card style={{ marginBottom: 16 }}>
            <CardHead title="Gate-in status" desc="One shared lifecycle from acceptance to arrival." />
            <div className="card-body" style={{ paddingTop: 4 }}>
              <div className="gi-timeline">
                {steps.map((s, i) => (
                  <div key={s.key} className={`gi-step${s.done ? " done" : ""}${s.active ? " active" : ""}`}>
                    <div className="gi-step-rail">
                      <span className="gi-step-dot">{s.done ? <Ic13.Check size={13} /> : s.active ? <span className="gi-step-pulse" /> : i + 1}</span>
                      {i < steps.length - 1 && <span className="gi-step-line" />}
                    </div>
                    <div className="gi-step-body">
                      <div className="gi-step-title">{s.title}</div>
                      <div className="gi-step-desc">{s.desc}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </Card>

          <Card>
            <CardHead title="Gate-in details" desc="Date & time come from the farmer's offer." />
            <div className="card-body" style={{ paddingTop: 2 }}>
              <div className="gi-detail-grid">
                <div><div className="gi-dl">Farmer</div><div className="gi-dv"><span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}><Avatar initials="MW" size="sm" />{GI.farmer} <Badge tone="avocado">Tier {GI.tier}</Badge></span></div></div>
                <div><div className="gi-dl">Region</div><div className="gi-dv">{GI.region}</div></div>
                <div><div className="gi-dl">Accepted quantity</div><div className="gi-dv">{GI.qty.toLocaleString("en-US")} kg <span className="muted">@ {KES13(GI.rate)}/kg</span></div></div>
                <div><div className="gi-dl">Order value</div><div className="gi-dv">{KES13(value)}</div></div>
                <div><div className="gi-dl">Gate-in date</div><div className="gi-dv">{GI.date}</div></div>
                <div><div className="gi-dl">Time window</div><div className="gi-dv">{GI.window}</div></div>
                <div style={{ gridColumn: "1 / -1" }}><div className="gi-dl">Gate</div><div className="gi-dv">{GI.gateLoc}</div></div>
              </div>
            </div>
          </Card>
        </div>

        {/* Right — gate pass (gated) + fallback */}
        <div>
          <Card className="gi-qr-card">
            <CardHead title="Gate pass" desc={live ? "Active — shown to the farmer too." : "Locked until the farmer confirms."} />
            <div className="card-body" style={{ paddingTop: 4 }}>
              {live ? (
                <div className="gi-qr-live">
                  <div className="gi-qr-frame"><QR13 value={GI.gpn} size={196} /></div>
                  <div className="gi-gpn">{GI.gpn}</div>
                  <div className="muted" style={{ fontSize: 12.5, textAlign: "center", lineHeight: 1.5 }}>The gate keeper scans this on arrival. Valid ±2h around the slot.</div>
                  <div style={{ display: "flex", gap: 8, width: "100%", marginTop: 4 }}>
                    <Button variant="outline" icon={Ic13.Printer || Ic13.File} onClick={() => toast({ title: "Sent to gate printer" })} style={{ flex: 1 }}>Print</Button>
                    <Button variant="outline" icon={Ic13.Share || Ic13.ArrowRight} onClick={() => toast({ title: "Shared with farmer" })} style={{ flex: 1 }}>Share</Button>
                  </div>
                </div>
              ) : (
                <div className="gi-qr-locked">
                  <div className="gi-qr-frame locked"><QR13 value={GI.gpn} size={196} /><div className="gi-qr-lock"><Ic13.Clock size={26} /></div></div>
                  <div style={{ fontSize: 14, fontWeight: 600, textAlign: "center" }}>Waiting for {GI.farmer} to confirm</div>
                  <div className="muted" style={{ fontSize: 12.5, textAlign: "center", lineHeight: 1.5 }}>The gate pass goes live the moment the farmer accepts the gate-in in their app.</div>
                  <Button variant="primary" icon={Ic13.Bell} onClick={() => toast({ title: "Reminder sent", desc: `${GI.farmer} was nudged to confirm.` })} style={{ width: "100%", marginTop: 4 }}>Resend confirmation request</Button>
                </div>
              )}
            </div>
          </Card>

          <div className="alert" style={{ background: "var(--surface)", marginTop: 16 }}>
            <span className="alert-icon" style={{ color: "var(--muted-foreground)" }}><Ic13.Info size={16} /></span>
            <div className="alert-body">
              <div className="alert-title">Farmer arrives without confirming?</div>
              <div className="alert-desc">The gate keeper can issue a <b>manual gate-in</b> on the tablet and generate the pass on the spot — delivery still goes through QC.</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.Pages = Object.assign(window.Pages || {}, { approve: GateInDetail });
