// OPT-GATE-15 · Truck movement log
const MovementLogScreen = ({ t, go }) => {
  const { Btn, Banner, Pill } = window.Op;
  const Ic = window.Icons, FD = window.OD;
  const state = t.movementLog; // inProgress | completed | disputes | loading
  const [tab, setTab] = useState("Timeline");
  const loading = state === "loading";
  const completed = state === "completed";

  let events = FD.EVENTS.slice();
  if (completed) events = events.filter(e => e.type !== "pending").concat([
    { type: "tare", icon: "Gauge", time: "10:12", actor: "Ann Mwangi", title: "Tare captured · net 4,200 kg", sub: "Within tolerance · slip attached", tone: "" },
    { type: "qc", icon: "QC", time: "10:30", actor: "QC Bay", title: "QC decision: Passed", sub: "Grade 1 · Export", tone: "" },
    { type: "exit", icon: "ArrowUp", time: "10:48", actor: "Joseph Kariuki", title: "Exit authorized", sub: "Dwell 2h 30m · GPN completed", tone: "" },
  ]);
  if (state === "disputes") events = events.map(e => e.type === "gross" ? { ...e, tone: "danger", title: "Gross weight captured — DISPUTED", sub: "Slip flagged for review by F. Otieno" } : e);

  const docs = [["Gate pass (GPN)", Ic.QR], ["Gross weight slip", Ic.FileText], ["Tare weight slip", Ic.FileText], ["QC report", Ic.QC], ["GRN document", Ic.Box], ["Exit slip", Ic.FileText]];
  const photos = ["Driver", "ID", "Truck front", "Gross slip", "Tare slip"];

  return (
    <div className="op-body" style={{ display: "flex", flexDirection: "column" }}>
      <div className="op-pad">
        {/* Header */}
        <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 14 }}>
          <span className="op-row-thumb" style={{ width: 48, height: 48 }}><Ic.Truck size={22}/></span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: "-0.01em" }}><span className="op-gpn">GPN-20260516-0042</span> · KCB 412G</div>
            <div className="op-muted" style={{ fontSize: 13 }}>Mary Wairimu · Hass avocado · Inbound</div>
          </div>
          {state === "disputes" ? <Pill tone="pending" dot>Held / Disputed</Pill> : completed ? <Pill tone="closed">Completed</Pill> : <Pill tone="in-progress" dot>Awaiting tare</Pill>}
        </div>

        {state === "disputes" && <div style={{ marginBottom: 14 }}><Banner tone="danger" icon={Ic.Flag} title="This GPN has a disputed event" desc="A weight slip is under review. Downstream operations on this truck are blocked until resolved."/></div>}

        {/* Summary strip */}
        <div className="op-card flush" style={{ marginBottom: 16 }}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 1, background: "var(--border)" }}>
            {[["Direction", "Inbound"], ["Product", "Hass avocado"], ["Expected", "4,200 kg"], ["Net captured", completed ? "4,200 kg" : "—"], ["Entered", "08:18"], ["Exited", completed ? "10:48" : "—"]].map(([k, v], i) => (
              <div key={i} style={{ background: "var(--card)", padding: "12px 14px" }}>
                <div className="op-muted" style={{ fontSize: 10.5, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.05em" }}>{k}</div>
                <div style={{ fontSize: 14.5, fontWeight: 600, marginTop: 3, fontVariantNumeric: "tabular-nums" }}>{v}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Tabs */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
          <div className="op-tabs">
            {["Timeline", "Documents", "Photos"].map(x => <button key={x} className={tab === x ? "on" : ""} onClick={() => setTab(x)}>{x}</button>)}
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <Btn variant="ghost" size="sm" icon={Ic.Flag}>Flag for review</Btn>
            <Btn variant="outline" size="sm" icon={Ic.Download}>Export PDF</Btn>
          </div>
        </div>

        {/* Content */}
        {loading ? (
          <div className="op-card op-card-pad">{Array.from({ length: 4 }).map((_, i) => <div key={i} style={{ display: "flex", gap: 12, marginBottom: 16 }}><div className="op-skel" style={{ width: 34, height: 34, borderRadius: "50%" }}/><div style={{ flex: 1 }}><div className="op-skel" style={{ height: 13, width: "40%" }}/><div className="op-skel" style={{ height: 11, width: "65%", marginTop: 7 }}/></div></div>)}</div>
        ) : tab === "Timeline" ? (
          <div className="op-card op-card-pad">
            <div className="op-timeline">
              {events.map((e, i) => {
                const I2 = Ic[e.icon] || Ic.Info;
                return (
                  <div key={i} className="op-tl-item">
                    <div className="op-tl-rail"><span className={`op-tl-dot ${e.tone}`}><I2 size={16}/></span>{i < events.length - 1 && <span className="op-tl-line"/>}</div>
                    <div className="op-tl-body" onClick={() => e.type === "gross" || e.type === "tare" ? go("slipViewer") : null} style={{ cursor: (e.type === "gross" || e.type === "tare") ? "pointer" : "default" }}>
                      <div className="op-tl-time">{e.time}{e.actor !== "—" && <> · {e.actor}</>}</div>
                      <div className="op-tl-title">{e.title}</div>
                      <div className="op-tl-sub">{e.sub}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        ) : tab === "Documents" ? (
          <div className="op-card flush">
            {docs.map(([l, I2], i) => (
              <button key={i} className="op-row" style={{ cursor: "pointer" }} onClick={() => go("slipViewer")}>
                <span className="op-row-thumb" style={{ width: 38, height: 38, background: "var(--muted)", color: "var(--muted-foreground)" }}>{React.createElement(I2, { size: 18 })}</span>
                <div className="op-row-body"><div className="op-row-title">{l}</div></div>
                <Ic.ChevronRight size={18} style={{ color: "var(--muted-foreground)" }}/>
              </button>
            ))}
          </div>
        ) : (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 12 }}>
            {photos.map((p, i) => (
              <button key={i} onClick={() => go("slipViewer")} style={{ border: "none", padding: 0, cursor: "pointer", borderRadius: "var(--radius-lg)", overflow: "hidden" }}>
                <div style={{ aspectRatio: "4/5", background: "repeating-linear-gradient(135deg, oklch(0.30 0.01 130) 0 10px, oklch(0.26 0.01 130) 10px 20px)", borderRadius: "var(--radius-lg)", position: "relative" }}>
                  <span className="op-pt-tag" style={{ position: "absolute", left: 8, bottom: 8 }}>{p}</span>
                </div>
              </button>
            ))}
          </div>
        )}
        <div className="op-muted" style={{ fontSize: 11.5, marginTop: 14, lineHeight: 1.5 }}>Events are append-only — once logged, never edited (only annotated). All events include actor + device. Export PDF is signable for compliance.</div>
      </div>
    </div>
  );
};

window.OptPages = Object.assign(window.OptPages || {}, {
  movementLog: { chrome: "flow", title: "Truck movement log", sub: "Full traceability", back: "activeTrucks", render: (ctx) => <MovementLogScreen {...ctx}/> },
});
