/* ============================================================
   Shared bits: icons, helpers, flow map, status pill
   Exposes to window for other babel scripts.
   ============================================================ */
const { useState, useEffect, useRef, useMemo } = React;

/* ---- tiny icon set (stroke) ---- */
const Icon = ({ name, ...p }) => {
  const paths = {
    dispatch: "M3 12h4l2-7 4 14 2-7h6",
    schedule: "M4 5h16v15H4zM4 9h16M8 3v4M16 3v4",
    fleet: "M3 13l2-6h11l3 6M5 13h14v4H5zM7 17v2M17 17v2",
    messages: "M4 5h16v11H8l-4 4z",
    guests: "M16 19c0-2.8-1.8-4-4-4s-4 1.2-4 4M12 11a3 3 0 100-6 3 3 0 000 6M19 8v4M21 10h-4",
    map: "M9 4L3 6v14l6-2 6 2 6-2V4l-6 2-6-2zM9 4v14M15 6v14",
    bell: "M6 9a6 6 0 1112 0c0 5 2 6 2 6H4s2-1 2-6M10 19a2 2 0 004 0",
    send: "M4 12l16-7-7 16-2-6-7-3z",
    home: "M4 11l8-7 8 7M6 10v9h12v-9",
    car2: "M5 13l1.5-5h11L19 13M6 13h12v4H6zM8 17v2M16 17v2",
    chat: "M4 5h16v11H8l-4 4z",
    user: "M16 19c0-2.8-1.8-4-4-4s-4 1.2-4 4M12 11a3 3 0 100-6 3 3 0 000 6",
    pin: "M12 21s7-6.5 7-12a7 7 0 10-14 0c0 5.5 7 12 7 12zM12 11a2 2 0 100-4 2 2 0 000 4",
    clock: "M12 7v5l3 2M12 21a9 9 0 100-18 9 9 0 000 18",
    plane: "M21 15l-8-3V5a1.5 1.5 0 00-3 0v7l-8 3v2l8-2v3l-2 1.5V21l3.5-1 3.5 1v-1.5L13 18v-3l8 2z",
    plus: "M12 5v14M5 12h14",
    check: "M5 12l4 4 10-10",
    arrow: "M5 12h14M13 6l6 6-6 6",
    refresh: "M4 12a8 8 0 0114-5l2 2M20 12a8 8 0 01-14 5l-2-2M18 4v5h-5M6 20v-5h5",
    phone: "M5 4h4l2 5-3 2a11 11 0 005 5l2-3 5 2v4a2 2 0 01-2 2A16 16 0 013 6a2 2 0 012-2z",
    star: "M12 4l2.4 5 5.6.6-4 4 1 5.4L12 16l-5 3 1-5.4-4-4 5.6-.6z",
    settings: "M12 9a3 3 0 100 6 3 3 0 000-6M19.4 13.5a1.7 1.7 0 00.3 1.9l.1.1a2 2 0 11-2.8 2.8l-.1-.1a1.7 1.7 0 00-2.9 1.2V21a2 2 0 11-4 0v-.1a1.7 1.7 0 00-2.9-1.2l-.1.1a2 2 0 11-2.8-2.8l.1-.1a1.7 1.7 0 00-1.2-2.9H4a2 2 0 110-4h.1a1.7 1.7 0 001.2-2.9l-.1-.1a2 2 0 112.8-2.8l.1.1a1.7 1.7 0 002.9-1.2V4a2 2 0 114 0v.1a1.7 1.7 0 002.9 1.2l.1-.1a2 2 0 112.8 2.8l-.1.1a1.7 1.7 0 001.2 2.9H21a2 2 0 110 4h-.1a1.7 1.7 0 00-1.5 1.2z",
    edit: "M4 20h4L18.5 9.5a2.1 2.1 0 00-3-3L5 17v3zM13.5 6.5l3 3",
    trash: "M5 7h14M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3",
    id: "M3 6h18v12H3zM7 10a2 2 0 104 0 2 2 0 00-4 0M5 16c.5-1.6 2-2.5 4-2.5s3.5.9 4 2.5M14 10h5M14 13h5",
    seat: "M7 4h7l1 8H7zM7 12v5M15 12v5M6 17h11M9 4V3h3v1",
    upload: "M12 16V4M7 9l5-5 5 5M5 20h14",
    camera: "M4 8h3l1.5-2h7L17 8h3v11H4zM12 16a3 3 0 100-6 3 3 0 000 6",
    pen: "M4 20h4L19 9a2 2 0 00-3-3L5 17v3zM14 7l3 3",
    doc: "M7 3h7l5 5v13H7zM14 3v5h5M9 13h7M9 17h7",
    shield: "M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z",
  };
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"
      strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d={paths[name] || ""} />
    </svg>
  );
};

const RIDE_TYPES = {
  airport_pickup: { label: "Airport Pickup", icon: "plane" },
  hotel_venue:    { label: "Hotel → Venue", icon: "arrow" },
  venue_hotel:    { label: "Venue → Hotel", icon: "arrow" },
  hotel_airport:  { label: "Airport Drop", icon: "plane" },
};

const RIDE_STATUS = {
  requested: { label: "Requested", tone: "amber" },
  assigned:  { label: "Assigned",  tone: "violet" },
  enroute:   { label: "En route",  tone: "sky" },
  completed: { label: "Completed", tone: "green" },
};

function fmtTime(t) {
  const d = new Date(t);
  return d.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
}
function relTime(t) {
  const diffMin = Math.round((t - Date.now()) / 60000);
  const absMin = Math.abs(diffMin);
  if (absMin < 1) return "now";
  // within the day: relative minutes/hours; further out: show the day + time
  if (absMin < 16 * 60) {
    if (absMin < 90) return diffMin > 0 ? `in ${diffMin}m` : `${absMin}m ago`;
    const h = Math.round(absMin / 60);
    return diffMin > 0 ? `in ${h}h` : `${h}h ago`;
  }
  const d = new Date(t);
  return d.toLocaleDateString([], { weekday: "short" }) + " " + d.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
}
function locName(s, id) { const l = s.LOCATIONS ? s.LOCATIONS : Store.LOCATIONS; const o = l.find((x) => x.id === id); return o ? o.name : id; }

const Pill = ({ tone, children }) => (
  <span className={"pill tone-" + tone}><span className="pdot" />{children}</span>
);

const Avatar = ({ initials, tone = "sky", size = 34 }) => (
  <div style={{
    width: size, height: size, borderRadius: size * 0.32, flex: "none",
    display: "grid", placeItems: "center", fontFamily: "var(--font-display)",
    fontWeight: 700, fontSize: size * 0.4, color: "#fff",
    background: `linear-gradient(150deg, var(--${tone}), color-mix(in oklab, var(--${tone}) 70%, #000))`,
  }}>{initials}</div>
);

/* ---- Flow map: location nodes with vehicle chips by status ---- */
function FlowMap({ state, onDriver }) {
  const order = state.locations.map((l) => l.id);
  const byLoc = {};
  order.forEach((id) => (byLoc[id] = []));
  state.drivers.forEach((d) => { if (byLoc[d.at]) byLoc[d.at].push(d); });
  const veh = (id) => state.vehicles.find((v) => v.id === id) || {};

  return (
    <div className="flowmap" style={{ gridTemplateColumns: `repeat(${Math.max(1, order.length)}, 1fr)` }}>
      {order.map((id) => {
        const loc = state.locations.find((l) => l.id === id);
        const drivers = byLoc[id];
        return (
          <div key={id} className={"flow-node kind-" + loc.kind}>
            <div className="flow-node-h">
              <span className="flow-ic">
                <Icon name={loc.kind === "airport" ? "plane" : loc.kind === "venue" ? "star" : "home"} />
              </span>
              <div>
                <div className="flow-name">{loc.name}</div>
                <div className="flow-sub mono">{drivers.length} vehicle{drivers.length === 1 ? "" : "s"}</div>
              </div>
            </div>
            <div className="flow-chips">
              {drivers.length === 0 && <div className="flow-empty">—</div>}
              {drivers.map((d) => {
                const st = Store.STATUSES[d.status];
                return (
                  <button key={d.id} className={"flow-chip tone-" + st.tone} onClick={() => onDriver && onDriver(d)} title={d.name + " · " + st.label}>
                    <span className="pdot" />
                    <span className="fc-txt">
                      <span className="fc-veh mono">{veh(d.vehicleId).name}</span>
                      <span className="fc-st">{st.label}</span>
                    </span>
                  </button>
                );
              })}
            </div>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { Icon, Pill, Avatar, FlowMap, RIDE_TYPES, RIDE_STATUS, fmtTime, relTime, locName,
  useState, useEffect, useRef, useMemo });
