// runs.jsx — Create delivery run + Manage delivery runs
const { useState: useStateRun } = React;

function firstName(d) { return d ? d.name.split(/\s+/)[0] : ""; }
function trackUrl(code, driverName) {
  return "Fedex Track.html#t=" + encodeURIComponent(code || "") + (driverName ? "&driver=" + encodeURIComponent(driverName) : "");
}
const STOP_TONE = { "Delivered": "success", "In transit": "brand", "Pending": "neutral" };
const STOP_DOT = { "Delivered": "#22b86e", "In transit": "var(--brand)", "Pending": "var(--fg-faint)" };

/* ============== CREATE DELIVERY RUN ============== */
function CreateRun({ addressBook, onCreate, nav }) {
  const [name, setName] = useStateRun("");
  const [driverId, setDriverId] = useStateRun("");
  const [start, setStart] = useStateRun(window.FX.emptyAddr());
  const [end, setEnd] = useStateRun(window.FX.emptyAddr());
  const [sameAsStart, setSameAsStart] = useStateRun(true);
  const [stops, setStops] = useStateRun([window.FX.emptyAddr(), window.FX.emptyAddr()]);

  const setStop = (i, v) => setStops(prev => prev.map((s, idx) => idx === i ? v : s));
  const addStop = () => setStops(prev => [...prev, window.FX.emptyAddr()]);
  const removeStop = (i) => setStops(prev => prev.filter((_, idx) => idx !== i));

  const validStops = stops.filter(s => s.suburb && s.contact);
  const ready = name && start.suburb && (sameAsStart || end.suburb) && validStops.length >= 1;

  function create() {
    if (!ready) return;
    const endLoc = sameAsStart ? start : end;
    const run = {
      id: "RUN-" + Math.floor(1000 + Math.random() * 8999), name, date: window.FX.todayISO(),
      driverId: driverId || null, status: driverId ? "Active" : "Scheduled",
      start: { label: start.company || start.contact, suburb: start.suburb, line: start.line },
      end: { label: endLoc.company || endLoc.contact, suburb: endLoc.suburb, line: endLoc.line },
      stops: validStops.map((s, i) => ({
        seq: i + 1, company: s.company || s.contact, contact: s.contact, suburb: s.suburb, line: s.line,
        unit: s.unit, instructions: s.instructions, tracking: window.FX.genTracking(),
        status: "Pending", time: "—",
      })),
    };
    onCreate(run);
  }

  return (
    <div className="fade-up">
      <PageHeader eyebrow="Delivery runs" title="Create a delivery run" sub="Set a start and end location, then add the stops the driver will complete in order." />
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) 312px", gap: 24, alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {/* run basics */}
          <Card pad={22}>
            <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 14 }}>
              <Field label="Run name"><TextInput value={name} onChange={setName} placeholder="e.g. Morning CBD loop" /></Field>
              <Field label="Assign driver (optional)">
                <Select value={driverId} onChange={setDriverId} placeholder="Unassigned"
                  options={window.FX.DRIVERS.map(d => ({ value: d.id, label: d.name + " · " + d.vehicle }))} />
              </Field>
            </div>
          </Card>

          {/* start / end */}
          <Card pad={22}>
            <SecHead n="A" title="Start location" />
            <AddressField value={start} onChange={setStart} addressBook={addressBook} role="Run starts at" accent="var(--brand)" />
            <button onClick={() => setSameAsStart(s => !s)} style={{ display: "flex", alignItems: "center", gap: 10, background: "transparent", border: "none", padding: "14px 2px 4px", textAlign: "left" }}>
              <span style={{ width: 18, height: 18, borderRadius: 5, flex: "none", border: "1.5px solid " + (sameAsStart ? "var(--brand)" : "var(--border-strong)"), background: sameAsStart ? "var(--brand)" : "transparent", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>{sameAsStart && <Icon name="check" size={12} color="#fff" />}</span>
              <span style={{ fontSize: 13.5, color: "var(--fg-strong)", fontWeight: 500 }}>End location is the same as the start (return to base)</span>
            </button>
            {!sameAsStart && (
              <div style={{ marginTop: 12 }}>
                <SecHead n="Z" title="End location" />
                <AddressField value={end} onChange={setEnd} addressBook={addressBook} role="Run ends at" accent="var(--accent)" />
              </div>
            )}
          </Card>

          {/* stops */}
          <Card pad={22}>
            <SecHead n="1" title="Deliveries" hint={validStops.length ? validStops.length + " stop" + (validStops.length > 1 ? "s" : "") : null} />
            <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
              {stops.map((s, i) => (
                <AddressField key={i} value={s} onChange={v => setStop(i, v)} addressBook={addressBook}
                  role={"Stop " + (i + 1)} accent="var(--accent)" index={i}
                  onRemove={stops.length > 1 ? () => removeStop(i) : undefined} />
              ))}
            </div>
            <button onClick={addStop} style={{ marginTop: 13, display: "flex", alignItems: "center", justifyContent: "center", gap: 8, width: "100%", padding: "12px", background: "var(--surface)", border: "1px dashed var(--border-strong)", borderRadius: "var(--r-md)", color: "var(--brand)", fontSize: 14, fontWeight: 500 }}>
              <Icon name="plus" size={16} /> Add a delivery stop
            </button>
          </Card>
        </div>

        {/* summary rail */}
        <div style={{ position: "sticky", top: 16 }}>
          <Card pad={0} style={{ overflow: "hidden" }}>
            <div style={{ background: "var(--brand)", color: "#fff", padding: "16px 18px" }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "1.2px", opacity: 0.7, textTransform: "uppercase" }}>New run</div>
              <div style={{ fontSize: 19, fontWeight: 700, marginTop: 4 }}>{name || "Untitled run"}</div>
              <div style={{ fontSize: 12.5, opacity: 0.75, marginTop: 2 }}>{validStops.length} stop{validStops.length === 1 ? "" : "s"}{driverId ? " · " + firstName(window.FX.DRIVERS.find(d => d.id === driverId)) : " · unassigned"}</div>
            </div>
            <div style={{ padding: "14px 18px" }}>
              <RailRow icon="map-pin" label="Start" value={start.suburb || "Not set"} />
              <RailRow icon="navigation" label="Stops" value={validStops.length ? validStops.map(s => s.suburb).join(", ") : "None yet"} />
              <RailRow icon="map-pin" label="End" value={(sameAsStart ? start.suburb : end.suburb) || "Not set"} />
            </div>
            <div style={{ padding: "0 18px 18px" }}>
              <Button variant="primary" full size="lg" icon="check-circle" onClick={create} disabled={!ready}>Create delivery run</Button>
              {!ready && <div style={{ fontSize: 11.5, color: "var(--fg-mute)", textAlign: "center", marginTop: 10 }}>Add a run name, start location and at least one stop.</div>}
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}
function SecHead({ n, title, hint }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
      <span style={{ width: 22, height: 22, borderRadius: "50%", background: "var(--brand)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-mono)", fontSize: 12, fontWeight: 700, flex: "none" }}>{n}</span>
      <span style={{ fontSize: 15.5, fontWeight: 700, color: "var(--fg-strong)", flex: 1 }}>{title}</span>
      {hint && <Badge tone="brand">{hint}</Badge>}
    </div>
  );
}
function RailRow({ icon, label, value }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-start", gap: 11, padding: "7px 0" }}>
      <Icon name={icon} size={16} color="var(--fg-faint)" style={{ marginTop: 1 }} />
      <span style={{ fontSize: 13, color: "var(--fg-mute)", flex: "none", width: 46 }}>{label}</span>
      <span style={{ fontSize: 13, fontWeight: 500, color: "var(--fg-strong)", textAlign: "right", flex: 1 }}>{value}</span>
    </div>
  );
}

/* ============== MANAGE DELIVERY RUNS ============== */
function ManageRuns({ runs, onNew }) {
  const [open, setOpen] = useStateRun(null);
  const [filter, setFilter] = useStateRun("active");
  const [q, setQ] = useStateRun("");
  const [loc, setLoc] = useStateRun("");
  const [from, setFrom] = useStateRun("");
  const [to, setTo] = useStateRun("");

  const ql = q.trim().toLowerCase();
  const locl = loc.trim().toLowerCase();
  const list = runs.filter(r => {
    if (filter === "active" && r.status === "Completed") return false;
    if (filter === "completed" && r.status !== "Completed") return false;
    if (ql && !(r.name.toLowerCase().includes(ql) || r.id.toLowerCase().includes(ql))) return false;
    if (locl) {
      const hay = (r.start.suburb + " " + r.end.suburb + " " + r.stops.map(s => s.suburb).join(" ")).toLowerCase();
      if (!hay.includes(locl)) return false;
    }
    if (from && r.date < from) return false;
    if (to && r.date > to) return false;
    return true;
  });
  const hasSearch = ql || locl || from || to;
  function clearSearch() { setQ(""); setLoc(""); setFrom(""); setTo(""); }
  const counts = {
    active: runs.filter(r => r.status !== "Completed").length,
    completed: runs.filter(r => r.status === "Completed").length,
    all: runs.length,
  };
  const statusTone = s => s === "Active" ? "brand" : s === "Scheduled" ? "warn" : "success";
  const statusDot = s => s === "Active" ? "var(--brand)" : s === "Scheduled" ? "var(--warn)" : "#22b86e";

  return (
    <div className="fade-up">
      <PageHeader eyebrow="Delivery runs" title="Manage delivery runs"
        sub="Track each run's progress, the assigned driver and the status of every individual delivery."
        actions={<Button variant="primary" icon="plus" onClick={onNew}>Create run</Button>} />

      <div style={{ display: "flex", gap: 12, alignItems: "center", marginBottom: 16, flexWrap: "wrap" }}>
        <div style={{ display: "flex", gap: 6, background: "var(--bg-mist)", padding: 4, borderRadius: "var(--r-pill)", width: "fit-content" }}>
          {[["active", "Active"], ["all", "All"], ["completed", "Completed"]].map(([k, lbl]) => (
            <button key={k} onClick={() => setFilter(k)} style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "8px 16px", borderRadius: "var(--r-pill)", border: "none", fontSize: 13.5, fontWeight: 500, background: filter === k ? "var(--surface)" : "transparent", color: filter === k ? "var(--fg-strong)" : "var(--fg-mute)", boxShadow: filter === k ? "var(--shadow-xs)" : "none" }}>{lbl} <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-faint)" }}>{counts[k]}</span></button>
          ))}
        </div>
      </div>

      {/* search row */}
      <Card pad={14} style={{ marginBottom: 16 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1.1fr auto", gap: 12, alignItems: "end", flexWrap: "wrap" }}>
          <Field label="Run name">
            <div style={{ position: "relative" }}>
              <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--fg-mute)" }}><Icon name="search" size={15} /></span>
              <TextInput value={q} onChange={setQ} placeholder="Search by run name or ID…" style={{ paddingLeft: 36 }} />
            </div>
          </Field>
          <Field label="Location">
            <div style={{ position: "relative" }}>
              <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--fg-mute)" }}><Icon name="map-pin" size={15} /></span>
              <TextInput value={loc} onChange={setLoc} placeholder="Any suburb on the run…" style={{ paddingLeft: 36 }} />
            </div>
          </Field>
          <div style={{ display: "flex", gap: 8, alignItems: "end" }}>
            <Field label="From"><TextInput type="date" value={from} onChange={setFrom} style={{ width: 150 }} /></Field>
            <Field label="To"><TextInput type="date" value={to} onChange={setTo} style={{ width: 150 }} /></Field>
            {hasSearch && <Button variant="ghost" icon="x" onClick={clearSearch} style={{ marginBottom: 1 }}>Clear</Button>}
          </div>
        </div>
        {hasSearch && <div style={{ marginTop: 10, fontSize: 12.5, color: "var(--fg-mute)" }}>{list.length} run{list.length === 1 ? "" : "s"} match your search.</div>}
      </Card>

      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {list.map(run => {
          const driver = window.FX.DRIVERS.find(d => d.id === run.driverId);
          const pr = window.FX.runProgress(run);
          return (
            <Card key={run.id} pad={20} hover onClick={() => setOpen(run)}>
              <div style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
                {/* identity */}
                <div style={{ minWidth: 180, flex: "1 1 200px" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
                    <span style={{ fontWeight: 700, fontSize: 16, color: "var(--fg-strong)" }}>{run.name}</span>
                    <Badge tone={statusTone(run.status)}><StatusDot color={statusDot(run.status)} pulse={run.status === "Active"} /> {run.status}</Badge>
                  </div>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-mute)", marginTop: 3 }}>{run.id} · {window.FX.fmtDate(run.date)} · {run.start.suburb} → {run.end.suburb}</div>
                </div>
                {/* driver */}
                <div style={{ display: "flex", alignItems: "center", gap: 10, minWidth: 150 }}>
                  {driver ? (
                    <>
                      <span style={{ width: 36, height: 36, borderRadius: "50%", background: "var(--brand)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 12.5, flex: "none" }}>{driver.initials}</span>
                      <div>
                        <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--fg-strong)" }}>{firstName(driver)}</div>
                        <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-mute)" }}>{driver.vehicle}</div>
                      </div>
                    </>
                  ) : <span style={{ fontSize: 13, color: "var(--fg-faint)", fontStyle: "italic" }}>Unassigned</span>}
                </div>
                {/* progress */}
                <div style={{ flex: "1 1 200px", minWidth: 180 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                    <span style={{ fontSize: 12.5, color: "var(--fg-mute)" }}>{pr.current ? "At: " + pr.current.suburb : run.status === "Completed" ? "All delivered" : "Not started"}</span>
                    <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--fg-strong)", fontFamily: "var(--font-mono)" }}>{pr.done}/{pr.total}</span>
                  </div>
                  <div style={{ height: 7, background: "var(--bg-mist-2)", borderRadius: 999, overflow: "hidden" }}>
                    <div style={{ height: "100%", width: (pr.pct * 100) + "%", background: run.status === "Completed" ? "var(--success)" : "var(--accent)", borderRadius: 999, transition: "width 300ms ease" }} />
                  </div>
                </div>
                {/* actions */}
                <div style={{ display: "flex", alignItems: "center", gap: 8 }} onClick={e => e.stopPropagation()}>
                  {driver && run.status !== "Completed" && (
                    <a href={trackUrl(run.id, driver.name)} target="_blank" rel="noopener" style={{ textDecoration: "none" }}>
                      <Button variant="secondary" size="sm" icon="navigation">Track {firstName(driver)}</Button>
                    </a>
                  )}
                  <button onClick={() => setOpen(run)} style={{ background: "var(--bg-mist)", border: "none", borderRadius: 9, width: 38, height: 38, display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--fg-body)" }}><Icon name="chevron-right" size={18} /></button>
                </div>
              </div>
            </Card>
          );
        })}
        {list.length === 0 && (
          <Card pad={48} style={{ textAlign: "center" }}>
            <div style={{ width: 52, height: 52, borderRadius: "50%", background: "var(--bg-mist)", display: "inline-flex", alignItems: "center", justifyContent: "center", margin: "0 auto 12px", color: "var(--fg-faint)" }}><Icon name="navigation" size={24} /></div>
            <div style={{ fontSize: 14.5, fontWeight: 600, color: "var(--fg-strong)" }}>No runs here</div>
            <div style={{ fontSize: 13, color: "var(--fg-mute)", marginTop: 4 }}>Create a delivery run to plan a driver's stops.</div>
          </Card>
        )}
      </div>

      <RunDetail run={open} onClose={() => setOpen(null)} />
    </div>
  );
}

/* ============== RUN DETAIL ============== */
function RunDetail({ run, onClose }) {
  if (!run) return null;
  const driver = window.FX.DRIVERS.find(d => d.id === run.driverId);
  const pr = window.FX.runProgress(run);
  // full ordered itinerary: start, stops, end
  const items = [
    { kind: "start", label: "Start", company: run.start.label, suburb: run.start.suburb, line: run.start.line },
    ...run.stops.map(s => ({ kind: "stop", ...s })),
    { kind: "end", label: "End", company: run.end.label, suburb: run.end.suburb, line: run.end.line },
  ];
  return (
    <Modal open={!!run} onClose={onClose} title={run.name} width={680}>
      {/* header */}
      <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 18, flexWrap: "wrap" }}>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 14, fontWeight: 700, color: "var(--brand)" }}>{run.id}</span>
        <Badge tone={run.status === "Active" ? "brand" : run.status === "Scheduled" ? "warn" : "success"}><StatusDot color={run.status === "Active" ? "var(--brand)" : run.status === "Scheduled" ? "var(--warn)" : "#22b86e"} pulse={run.status === "Active"} /> {run.status}</Badge>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--fg-strong)", fontWeight: 600, marginLeft: "auto" }}>{pr.done}/{pr.total} delivered</span>
      </div>

      {/* driver + track */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: 14, background: "var(--bg-mist)", borderRadius: "var(--r-md)", marginBottom: 18 }}>
        {driver ? (
          <>
            <span style={{ width: 42, height: 42, borderRadius: "50%", background: "var(--brand)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 14, flex: "none" }}>{driver.initials}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14.5, fontWeight: 600, color: "var(--fg-strong)" }}>{firstName(driver)} <span style={{ color: "var(--fg-mute)", fontWeight: 400 }}>· {driver.name.split(/\s+/).slice(1).join(" ")}</span></div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-mute)" }}>{driver.vehicle} · {driver.rego}</div>
            </div>
            {run.status !== "Completed" && (
              <a href={trackUrl(run.id, driver.name)} target="_blank" rel="noopener" style={{ textDecoration: "none" }}>
                <Button variant="primary" size="sm" icon="navigation">Track driver</Button>
              </a>
            )}
          </>
        ) : <div style={{ fontSize: 13.5, color: "var(--fg-mute)", fontStyle: "italic" }}>No driver assigned yet.</div>}
      </div>

      {/* itinerary */}
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)", marginBottom: 12 }}>Itinerary · {run.stops.length} deliveries</div>
      <div style={{ position: "relative" }}>
        {items.map((it, i) => {
          const isStop = it.kind === "stop";
          const endpoint = !isStop;
          const tone = isStop ? STOP_TONE[it.status] : "neutral";
          const dot = isStop ? STOP_DOT[it.status] : "var(--brand)";
          return (
            <div key={i} style={{ display: "flex", gap: 14, paddingBottom: i < items.length - 1 ? 18 : 0, position: "relative" }}>
              {i < items.length - 1 && <span style={{ position: "absolute", left: 15, top: 30, bottom: 0, width: 2, background: "var(--border)" }} />}
              <span style={{ width: 32, height: 32, borderRadius: endpoint ? 9 : "50%", flex: "none", zIndex: 1, display: "inline-flex", alignItems: "center", justifyContent: "center",
                background: endpoint ? "var(--brand-soft)" : it.status === "Delivered" ? "var(--success)" : it.status === "In transit" ? "var(--accent)" : "var(--bg-mist-2)",
                color: endpoint ? "var(--brand)" : (it.status === "Pending" ? "var(--fg-mute)" : "#fff") }}>
                {endpoint ? <Icon name="map-pin" size={16} /> : it.status === "Delivered" ? <Icon name="check" size={16} /> : it.status === "In transit" ? <StatusDot color="#fff" pulse /> : <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, fontWeight: 700 }}>{it.seq}</span>}
              </span>
              <div style={{ flex: 1, minWidth: 0, paddingTop: 2 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                  <span style={{ fontSize: 14, fontWeight: 600, color: "var(--fg-strong)" }}>{it.company}</span>
                  {endpoint && <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.6px", textTransform: "uppercase", color: "var(--fg-mute)", background: "var(--bg-mist)", padding: "2px 7px", borderRadius: 5 }}>{it.label}</span>}
                  {isStop && <Badge tone={tone}>{it.status}</Badge>}
                </div>
                <div style={{ fontSize: 12.5, color: "var(--fg-mute)", marginTop: 2 }}>{it.line ? it.line + ", " : ""}{it.suburb}{isStop && it.contact ? " · " + it.contact : ""}</div>
                {isStop && (
                  <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 5 }}>
                    {it.status === "Delivered" && <span style={{ fontSize: 12, color: "#108a52", display: "inline-flex", alignItems: "center", gap: 4 }}><Icon name="check-circle" size={13} /> Completed {it.time}</span>}
                    {it.status === "In transit" && <span style={{ fontSize: 12, color: "var(--brand)", fontWeight: 500 }}>Driver en route</span>}
                    {it.status === "Pending" && <span style={{ fontSize: 12, color: "var(--fg-faint)" }}>Awaiting</span>}
                    <a href={trackUrl(it.tracking, driver ? driver.name : "")} target="_blank" rel="noopener" style={{ fontSize: 12, color: "var(--accent-700)", fontWeight: 500, textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 4 }}>
                      <Icon name="external-link" size={12} /> Tracking link
                    </a>
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </Modal>
  );
}

Object.assign(window, { CreateRun, ManageRuns });
