// OPT-GATE-06 · Truck details — capture & verify each truck on the gate pass
// One gate pass (GPN) can cover several trucks. Every truck shows its full
// details and its own photo capture set, and gets its own "Continue to verify"
// button. Trucks whose details were not entered at booking can be added manually.
const CaptureDriverScreen = ({ t, go }) => {
  const { Btn, Banner, Stepper, PhotoTile, Pill, Modal } = window.Op;
  const Ic = window.Icons, FD = window.OD;
  const state = t.captureDriver; // empty | partial | filled | storageLow
  const order = FD.ORDER;

  // Seed each truck's photo set from the tweak state (entered trucks only).
  const seedShots = () => state === "filled" ? [true, true, true]
    : state === "partial" ? [true, false, false]
    : state === "storageLow" ? [true, true, false]
    : [false, false, false];

  const [trucks, setTrucks] = useState(() => order.trucks.map(tk => ({ ...tk, shots: tk.entered ? seedShots() : [false, false, false] })));
  useEffect(() => { setTrucks(order.trucks.map(tk => ({ ...tk, shots: tk.entered ? seedShots() : [false, false, false] }))); }, [state]);

  const [editId, setEditId] = useState(null); // truck whose details are being added/edited
  const blank = { plate: "", driver: "", phone: "", trailer: "", load: 0 };
  const [form, setForm] = useState(blank);
  const fset = (patch) => setForm(f => ({ ...f, ...patch }));
  const formValid = form.plate.trim().length >= 4 && form.driver.trim().length >= 2 && form.phone.trim().length >= 7;

  const openEdit = (tk) => { setEditId(tk.id); setForm({ plate: tk.plate, driver: tk.driver, phone: tk.phone, trailer: tk.trailer, load: tk.load }); };
  const saveDetails = () => {
    if (!formValid) return;
    setTrucks(list => list.map(x => x.id === editId ? { ...x, ...form, entered: true } : x));
    setEditId(null);
  };
  const toggleShot = (id, i) => setTrucks(list => list.map(x => x.id === id ? { ...x, shots: x.shots.map((v, j) => j === i ? !v : v) } : x));

  const tileDefs = [
    { label: "Driver photo (face)", hint: "Rear or front camera", tag: "driver.jpg", req: true },
    { label: "ID / license photo", hint: "Recommended", tag: "id.jpg", req: false },
    { label: "Truck front (plate visible)", hint: "Plate must be readable", tag: "truck.jpg", req: true },
  ];
  const truckReady = (tk) => tk.entered && tk.shots[0] && tk.shots[2];

  return (
    <div className="op-body" style={{ display: "flex", flexDirection: "column" }}>
      <div className="op-pad" style={{ flex: 1 }}>
        <div style={{ display: "flex", justifyContent: "center", margin: "4px 0 22px" }}>
          <Stepper steps={["Capture", "Verify"]} current={0}/>
        </div>

        {/* Gate pass summary — all trucks below belong to this one pass */}
        <div className="op-card flush" style={{ maxWidth: 980, margin: "0 auto 20px" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", padding: "16px 18px", gap: 16 }}>
            {[["Gate pass", order.gpn, true], ["Linked order", order.id, true], ["Supplier", order.who, false], ["Trucks on pass", trucks.length + " trucks", false]].map(([k, v, mono], i) => (
              <div key={i}>
                <div className="op-muted" style={{ fontSize: 11.5, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.05em" }}>{k}</div>
                <div className={mono ? "op-mono" : ""} style={{ fontSize: 15, fontWeight: 600, marginTop: 3 }}>{v}</div>
              </div>
            ))}
          </div>
        </div>

        {state === "storageLow" && <div style={{ maxWidth: 980, margin: "0 auto 16px" }}><Banner tone="warning" icon={Ic.Warning} title="Device storage low (412 MB free)" desc="Photos will be compressed more aggressively. Sync soon to free space."/></div>}

        {/* One card per truck — reference layout: details + capture + own action */}
        <div style={{ maxWidth: 980, margin: "0 auto", display: "flex", flexDirection: "column", gap: 20 }}>
          {trucks.map((tk, idx) => (
            <div className="op-card flush" key={tk.id}>
              {/* Truck header */}
              <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "14px 18px", borderBottom: "1px solid var(--border)" }}>
                <span className="op-row-thumb" style={{ width: 40, height: 40, background: tk.entered ? "var(--soil-soft)" : "var(--muted)", color: tk.entered ? "var(--soil-fg)" : "var(--muted-foreground)" }}><Ic.Truck size={20}/></span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 15.5, fontWeight: 700, letterSpacing: "-0.01em" }}>Truck {idx + 1}{tk.entered && <span className="op-mono" style={{ fontWeight: 600, color: "var(--muted-foreground)" }}> · {tk.plate}</span>}</div>
                  {tk.load > 0 && <div className="op-muted" style={{ fontSize: 12.5 }}>Est. load {tk.load.toLocaleString("en-US")} kg</div>}
                </div>
                {truckReady(tk) ? <Pill tone="approved" dot>Ready to verify</Pill>
                  : !tk.entered ? <Pill tone="pending" dot>Needs details</Pill>
                  : <Pill tone="in-progress" dot>Capture photos</Pill>}
                {tk.entered && <Btn variant="outline" size="sm" icon={Ic.Edit} onClick={() => openEdit(tk)}>Edit</Btn>}
              </div>

              {/* Details — or a manual-add prompt if never entered */}
              {tk.entered ? (
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", padding: "14px 18px", gap: 16, borderBottom: "1px solid var(--border)" }}>
                  {[["Truck plate", tk.plate, true], ["Driver", tk.driver, false], ["Driver phone", tk.phone, true], ["Trailer plate", tk.trailer || "—", true]].map(([k, v, mono], i) => (
                    <div key={i}>
                      <div className="op-muted" style={{ fontSize: 11.5, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.05em" }}>{k}</div>
                      <div className={mono ? "op-mono" : ""} style={{ fontSize: 14.5, fontWeight: 600, marginTop: 3 }}>{v}</div>
                    </div>
                  ))}
                </div>
              ) : (
                <div style={{ padding: "16px 18px", borderBottom: "1px solid var(--border)" }}>
                  <Banner tone="warning" icon={Ic.Warning} title="Truck details not entered at booking"
                          desc="This truck is on the pass but its plate and driver were never captured. Add them manually to continue.">
                    <div style={{ marginTop: 10 }}><Btn variant="primary" size="sm" icon={Ic.Plus} onClick={() => openEdit(tk)}>Add truck details</Btn></div>
                  </Banner>
                </div>
              )}

              {/* Capture set (reference layout) — only once details exist */}
              {tk.entered && (
                <div style={{ padding: "16px 18px" }}>
                  <div className="op-muted" style={{ fontSize: 11.5, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 12 }}>Capture photos</div>
                  <div className="op-grid-3" style={{ gap: 16 }}>
                    {tileDefs.map((tile, i) => (
                      <div key={i}>
                        <PhotoTile filled={tk.shots[i]} label={tile.label} hint={tile.hint} tag={tile.tag} required={tile.req} aspect="4 / 5" onTap={() => toggleShot(tk.id, i)}/>
                        <div style={{ marginTop: 8, textAlign: "center", fontSize: 12.5, fontWeight: 600, color: tk.shots[i] ? "var(--success)" : tile.req ? "var(--foreground)" : "var(--muted-foreground)" }}>
                          {tk.shots[i] ? "Captured · tap to re-take" : tile.req ? "Required" : "Optional"}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Per-truck action */}
              <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "0 18px 16px" }}>
                <div className="op-muted" style={{ fontSize: 12, flex: 1 }}>
                  {truckReady(tk) ? "Driver and truck photos captured." : !tk.entered ? "Add details, then capture photos." : "Capture the driver and truck-front photos to continue."}
                </div>
                <Btn variant="primary" iconRight={Ic.ChevronRight} disabled={!truckReady(tk)} onClick={() => go("verify")}>Continue to verify</Btn>
              </div>
            </div>
          ))}
        </div>

        <div className="op-muted" style={{ fontSize: 12, marginTop: 16, textAlign: "center" }}>Photos store locally first and sync when online · EXIF stripped except timestamp · ~200 KB each.</div>
      </div>

      <div className="op-actionbar">
        <Btn variant="outline" icon={Ic.ChevronLeft} onClick={() => go("manualEntry")}>Back</Btn>
        <div className="op-ab-grow"/>
        <span className="op-muted" style={{ fontSize: 12.5, alignSelf: "center" }}>{trucks.filter(truckReady).length} of {trucks.length} trucks ready</span>
      </div>

      {/* Manual add / edit truck details */}
      <Modal open={!!editId} onClose={() => setEditId(null)}
        title={trucks.find(x => x.id === editId)?.entered ? "Edit truck details" : "Add truck details"}
        desc="Checked against the truck at the gate before it's let in."
        actions={<><Btn variant="ghost" block onClick={() => setEditId(null)}>Cancel</Btn><Btn variant="primary" block disabled={!formValid} onClick={saveDetails}>Save details</Btn></>}>
        <div className="op-field"><div className="op-label">Truck plate <span className="req">*</span></div>
          <input className="op-input" placeholder="e.g. KCB 412G" value={form.plate} onChange={(e) => fset({ plate: e.target.value.toUpperCase() })}/></div>
        <div className="op-field"><div className="op-label">Driver name <span className="req">*</span></div>
          <input className="op-input" placeholder="Full name" value={form.driver} onChange={(e) => fset({ driver: e.target.value })}/></div>
        <div className="op-field"><div className="op-label">Driver phone <span className="req">*</span></div>
          <input className="op-input" inputMode="tel" placeholder="0722 000 000" value={form.phone} onChange={(e) => fset({ phone: e.target.value })}/></div>
        <div className="op-field"><div className="op-label">Trailer / second plate</div>
          <input className="op-input" placeholder="For articulated trucks" value={form.trailer} onChange={(e) => fset({ trailer: e.target.value.toUpperCase() })}/></div>
        <div className="op-field" style={{ marginBottom: 0 }}><div className="op-label">Estimated load (kg)</div>
          <input className="op-input" inputMode="numeric" placeholder="0" value={form.load ? form.load.toLocaleString("en-US") : ""} onChange={(e) => fset({ load: Number(e.target.value.replace(/\D/g, "")) || 0 })}/></div>
      </Modal>
    </div>
  );
};

window.OptPages = Object.assign(window.OptPages || {}, {
  captureDriver: { chrome: "flow", title: "Truck details", sub: "Capture & verify each truck", back: "scanMatch", render: (ctx) => <CaptureDriverScreen {...ctx}/> },
});
