// history.jsx — delivery history + proof of delivery
const { useState: useStateH } = React;

function MiniMap({ lat, lng, height = 150 }) {
  return (
    <div style={{ position: "relative", height, borderRadius: "var(--r-md)", overflow: "hidden", background: "#0E2A47" }}>
      <svg width="100%" height="100%" style={{ position: "absolute", inset: 0, opacity: 0.22 }}>
        <defs><pattern id="pmg" width="28" height="28" patternUnits="userSpaceOnUse"><path d="M28 0 L0 0 0 28" fill="none" stroke="rgba(120,160,220,0.6)" strokeWidth="0.5" /></pattern></defs>
        <rect width="100%" height="100%" fill="url(#pmg)" />
      </svg>
      <svg width="100%" height="100%" viewBox="0 0 300 150" preserveAspectRatio="none" style={{ position: "absolute", inset: 0 }}>
        <path d="M 20 120 C 90 90 150 80 200 50 C 230 32 250 30 280 26" stroke="#FF6600" strokeWidth="3" fill="none" strokeLinecap="round" />
      </svg>
      <div style={{ position: "absolute", left: "92%", top: "20%", transform: "translate(-50%,-50%)" }}>
        <span style={{ width: 16, height: 16, borderRadius: "50%", background: "var(--success)", border: "3px solid #fff", display: "block", boxShadow: "0 3px 8px rgba(0,0,0,0.4)" }} />
      </div>
      <div style={{ position: "absolute", left: 10, bottom: 10, fontFamily: "var(--font-mono)", fontSize: 10, color: "rgba(255,255,255,0.7)", background: "rgba(1,16,31,0.5)", padding: "3px 8px", borderRadius: 6 }}>
        {lat.toFixed(4)}, {lng.toFixed(4)}
      </div>
    </div>
  );
}

function PodModal({ item, onClose, currency }) {
  if (!item) return null;
  const v = window.FX.VEHICLES.find(x => x.id === item.vehicleId);
  const s = window.FX.SERVICES.find(x => x.id === item.serviceId);
  return (
    <Modal open={!!item} onClose={onClose} title="Proof of delivery" width={620}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 18 }}>
        <span style={{ width: 44, height: 44, borderRadius: "50%", background: "var(--success-soft)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
          <Icon name="check-circle" size={24} color="#108a52" />
        </span>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 700, fontSize: 16, color: "var(--fg-strong)" }}>Delivered to {item.pod.recipient}</div>
          <div style={{ fontSize: 13, color: "var(--fg-mute)" }}>{window.FX.fmtDate(item.date)} at {item.pod.signedAt} · <span className="mono">{item.id}</span></div>
        </div>
        <Badge tone="success"><StatusDot color="#22b86e" /> Delivered</Badge>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 14 }}>
        {/* Photo POD */}
        <div style={{ border: "1px solid var(--border)", borderRadius: "var(--r-md)", overflow: "hidden" }}>
          <div style={{ padding: "9px 12px", borderBottom: "1px solid var(--border)", fontSize: 12, fontWeight: 600, color: "var(--fg-strong)", display: "flex", alignItems: "center", gap: 7 }}><Icon name="camera" size={14} color="var(--brand)" /> Delivery photo</div>
          {item.pod.photo ? (
            <div style={{ height: 140, background: "linear-gradient(135deg,#cdd6e2,#aeb9cb)", position: "relative", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name="package" size={42} color="rgba(255,255,255,0.85)" />
              <div style={{ position: "absolute", left: 8, bottom: 8, fontFamily: "var(--font-mono)", fontSize: 9, background: "rgba(0,0,0,0.45)", color: "#fff", padding: "2px 6px", borderRadius: 4 }}>{item.date} {item.pod.signedAt}</div>
            </div>
          ) : <div style={{ height: 140, background: "var(--bg-mist)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12.5, color: "var(--fg-faint)" }}>No photo captured</div>}
        </div>
        {/* Signature */}
        <div style={{ border: "1px solid var(--border)", borderRadius: "var(--r-md)", overflow: "hidden" }}>
          <div style={{ padding: "9px 12px", borderBottom: "1px solid var(--border)", fontSize: 12, fontWeight: 600, color: "var(--fg-strong)", display: "flex", alignItems: "center", gap: 7 }}><Icon name="pen-tool" size={14} color="var(--brand)" /> Signature</div>
          {item.pod.sig ? (
            <div style={{ height: 140, background: "var(--surface)", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <svg width="180" height="70" viewBox="0 0 180 70"><path d="M10 50 C 30 10 45 60 60 40 C 72 24 80 52 95 44 C 110 36 118 16 135 38 C 145 50 160 30 172 36" stroke="#1E1633" strokeWidth="2.2" fill="none" strokeLinecap="round" /></svg>
            </div>
          ) : <div style={{ height: 140, background: "var(--bg-mist)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12.5, color: "var(--fg-faint)" }}>No signature required</div>}
        </div>
      </div>

      <MiniMap lat={item.pod.lat} lng={item.pod.lng} />

      <div style={{ marginTop: 14, padding: 14, background: "var(--bg-mist)", borderRadius: "var(--r-md)" }}>
        <div style={{ fontSize: 12, fontFamily: "var(--font-mono)", letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)", marginBottom: 6 }}>Driver note</div>
        <div style={{ fontSize: 14, color: "var(--fg-body)" }}>{item.pod.note}</div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 12, marginTop: 14 }}>
        <PodStat label="Service" value={(s && v) ? window.FX.serviceCode(s.id, v.id) : "—"} />
        <PodStat label="Size" value={v ? v.name : "—"} />
        <PodStat label="Charged" value={window.FX.money(item.price, currency)} />
      </div>

      <div style={{ display: "flex", gap: 10, marginTop: 18 }}>
        <Button variant="secondary" full icon="download" onClick={() => window.print()}>Download POD</Button>
        <Button variant="ghost" icon="printer" onClick={() => window.print()}>Print</Button>
      </div>
    </Modal>
  );
}
function PodStat({ label, value }) {
  return (
    <div style={{ border: "1px solid var(--border)", borderRadius: "var(--r-md)", padding: "11px 13px" }}>
      <div style={{ fontSize: 11, color: "var(--fg-mute)", fontFamily: "var(--font-mono)", letterSpacing: "0.6px", textTransform: "uppercase" }}>{label}</div>
      <div style={{ fontSize: 15, fontWeight: 700, color: "var(--fg-strong)", marginTop: 4 }}>{value}</div>
    </div>
  );
}

function History({ bookings, currency, nav, onLodgeInquiry }) {
  const [pod, setPod] = useStateH(null);
  const [q, setQ] = useStateH("");
  const [lodgeShip, setLodgeShip] = useStateH(null);
  const [lodged, setLodged] = useStateH(null);

  // user bookings (in transit) first, then delivered seed history
  const live = (bookings || []).map(b => ({
    id: b.tracking, date: b.date, time: b.time, vehicleId: b.vehicleId, serviceId: b.serviceId,
    from: b.pickup.suburb, to: b.dropoff.suburb, price: b.total, status: "In transit", booking: b, pod: null,
  }));
  const all = [...live, ...window.FX.HISTORY];
  const filtered = all.filter(d => (d.id + d.from + d.to).toLowerCase().includes(q.toLowerCase()));

  const statusTone = (s) => s === "Delivered" ? "success" : s === "In transit" ? "brand" : "warn";
  const statusDot = (s) => s === "Delivered" ? "#22b86e" : s === "In transit" ? "var(--brand)" : "var(--warn)";

  return (
    <div className="fade-up">
      <PageHeader eyebrow="Delivery history" title="Delivery history" sub="Every booking with status, pricing and proof of delivery."
        actions={<Button variant="primary" icon="plus" onClick={() => nav("book")}>New booking</Button>} />

      <div style={{ position: "relative", marginBottom: 16, maxWidth: 360 }}>
        <span style={{ position: "absolute", left: 13, top: "50%", transform: "translateY(-50%)", color: "var(--fg-mute)" }}><Icon name="search" size={16} /></span>
        <TextInput value={q} onChange={setQ} placeholder="Search tracking number or suburb…" style={{ paddingLeft: 38 }} />
      </div>

      <Card pad={0} style={{ overflow: "hidden" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1.4fr 1fr 0.9fr 0.9fr 150px", gap: 12, padding: "13px 22px", background: "var(--bg-mist)", borderBottom: "1px solid var(--border)", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)" }}>
          <span>Tracking</span><span>Route</span><span>Date</span><span>Size</span><span>Status</span><span style={{ textAlign: "right" }}>Price</span>
        </div>
        {filtered.map((d, i) => {
          const v = window.FX.VEHICLES.find(x => x.id === d.vehicleId);
          const clickable = d.status === "Delivered" || d.status === "In transit";
          return (
            <div key={d.id + i} onClick={() => { if (d.pod) setPod(d); else if (d.booking) window.open("Fedex Track.html#t=" + encodeURIComponent(d.id), "_blank"); }}
              style={{ display: "grid", gridTemplateColumns: "1.3fr 1.4fr 1fr 0.9fr 0.9fr 150px", gap: 12, padding: "15px 22px", borderTop: i ? "1px solid var(--border)" : "none", alignItems: "center", cursor: clickable ? "pointer" : "default", transition: "background 120ms ease" }}
              onMouseEnter={e => clickable && (e.currentTarget.style.background = "var(--bg-mist)")}
              onMouseLeave={e => (e.currentTarget.style.background = "transparent")}>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, fontWeight: 600, color: "var(--brand)" }}>{d.id}</span>
              <span style={{ fontSize: 13.5, color: "var(--fg-body)" }}>{d.from} <Icon name="arrow-right" size={12} color="var(--fg-faint)" style={{ verticalAlign: "middle", margin: "0 2px" }} /> {d.to}</span>
              <span style={{ fontSize: 13, color: "var(--fg-mute)" }}>{window.FX.fmtDate(d.date)}</span>
              <span style={{ fontSize: 13, color: "var(--fg-body)", display: "flex", alignItems: "center", gap: 7 }}><Icon name={v ? v.icon : "package"} size={15} color="var(--fg-mute)" /> {v ? v.name : "—"}</span>
              <span><Badge tone={statusTone(d.status)}><StatusDot color={statusDot(d.status)} pulse={d.status === "In transit"} /> {d.status}</Badge></span>
              <span style={{ textAlign: "right", display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 6 }}>
                <span style={{ fontWeight: 700, fontSize: 14, color: "var(--fg-strong)" }}>{window.FX.money(d.price, currency)}</span>
                <button onClick={(e) => { e.stopPropagation(); setLodgeShip(d); }} style={{ display: "inline-flex", alignItems: "center", gap: 6, background: "var(--surface)", border: "1px solid var(--border-strong)", borderRadius: "var(--r-pill)", padding: "5px 11px", color: "var(--brand)", fontSize: 12, fontWeight: 600, cursor: "pointer", whiteSpace: "nowrap" }}><Icon name="message-square" size={13} /> Lodge inquiry</button>
              </span>
            </div>
          );
        })}
        {filtered.length === 0 && <div style={{ padding: 40, textAlign: "center", color: "var(--fg-mute)" }}>No deliveries match your search.</div>}
      </Card>

      <PodModal item={pod} onClose={() => setPod(null)} currency={currency} />
      <LodgeInquiryModal open={!!lodgeShip} onClose={() => setLodgeShip(null)} shipment={lodgeShip} onLodge={(p) => { const inq = onLodgeInquiry && onLodgeInquiry(p); setLodgeShip(null); setLodged(inq); }} />
      <Modal open={!!lodged} onClose={() => setLodged(null)} title="Inquiry lodged" width={420}>
        {lodged && (
          <div style={{ textAlign: "center" }}>
            <div style={{ width: 52, height: 52, borderRadius: "50%", background: "var(--success-soft, #e7f6ee)", display: "inline-flex", alignItems: "center", justifyContent: "center", margin: "0 auto 12px" }}><Icon name="check-circle" size={26} color="var(--success, #1f8a5b)" /></div>
            <div style={{ fontSize: 16, fontWeight: 700, color: "var(--fg-strong)" }}>Thanks — we're on it</div>
            <div style={{ fontSize: 13.5, color: "var(--fg-mute)", marginTop: 6, lineHeight: 1.5 }}>Your inquiry reference is <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, color: "var(--brand)" }}>{lodged.ref}</span>. Customer Service has been emailed and we'll email you each update.</div>
            <div style={{ display: "flex", gap: 10, justifyContent: "center", marginTop: 18 }}>
              <Button variant="secondary" onClick={() => setLodged(null)}>Close</Button>
              <Button variant="primary" icon="message-square" onClick={() => { setLodged(null); nav("inquiries"); }}>View my inquiries</Button>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}

Object.assign(window, { History, MiniMap });
