/* ============================================================
   HQ — Live area map (real map view)
   All locations except the airport sit within one map view.
   Vans are placed at their driver-reported location/status.
   ============================================================ */

/* Preset coordinates (percent of map) for known seed locations.
   Unknown / user-added locations fall back to a ring layout. */
const MAP_COORDS = {
  venue:  { x: 50, y: 49 },
  grand:  { x: 23, y: 34 },
  harbor: { x: 80, y: 31 },
  summit: { x: 64, y: 71 },
};
function coordsFor(loc, idx, total) {
  if (MAP_COORDS[loc.id]) return MAP_COORDS[loc.id];
  const ang = (idx / Math.max(1, total)) * Math.PI * 2 - Math.PI / 2;
  return { x: 50 + 28 * Math.cos(ang), y: 50 + 26 * Math.sin(ang) };
}

function MapBackdrop() {
  // Stylized street map: land, water, park, blocks, roads.
  return (
    <svg className="map-svg" viewBox="0 0 1000 640" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
      <rect x="0" y="0" width="1000" height="640" className="mp-land" />
      {/* water (harbor side, top-right) */}
      <path d="M1000 0 L1000 250 Q860 230 820 150 Q800 70 720 0 Z" className="mp-water" />
      <path d="M640 0 Q700 80 760 120 Q840 170 1000 195" className="mp-shore" />
      {/* park / green */}
      <rect x="60" y="430" width="250" height="150" rx="22" className="mp-park" />
      <rect x="690" y="470" width="240" height="120" rx="20" className="mp-park" />
      {/* city blocks */}
      <g className="mp-block">
        <rect x="120" y="120" width="150" height="110" rx="10" />
        <rect x="300" y="90" width="130" height="120" rx="10" />
        <rect x="560" y="120" width="120" height="100" rx="10" />
        <rect x="120" y="270" width="130" height="120" rx="10" />
        <rect x="300" y="250" width="160" height="150" rx="10" />
        <rect x="520" y="270" width="150" height="140" rx="10" />
        <rect x="430" y="450" width="170" height="130" rx="10" />
        <rect x="730" y="250" width="150" height="120" rx="10" />
      </g>
      {/* roads */}
      <g className="mp-road">
        <path d="M0 240 H1000" />
        <path d="M0 420 H660" />
        <path d="M500 0 V640" />
        <path d="M270 0 V640" />
        <path d="M700 200 V640" />
        <path d="M0 100 L270 240" />
        <path d="M500 420 L700 470" />
      </g>
      <g className="mp-road-minor">
        <path d="M0 330 H1000" />
        <path d="M385 0 V640" />
        <path d="M600 240 V640" />
        <path d="M270 540 H1000" />
      </g>
    </svg>
  );
}

function MapBoard({ state }) {
  const mapLocs = state.locations.filter((l) => l.kind !== "airport");
  const airportLocIds = state.locations.filter((l) => l.kind === "airport").map((l) => l.id);

  const byLoc = {};
  state.locations.forEach((l) => (byLoc[l.id] = []));
  state.drivers.forEach((d) => { if (byLoc[d.at]) byLoc[d.at].push(d); });
  const airportDrivers = state.drivers.filter((d) => airportLocIds.includes(d.at));
  const veh = (id) => state.vehicles.find((v) => v.id === id) || {};
  const activeCount = state.drivers.filter((d) => d.status !== "offline").length;

  return (
    <div className="map-canvas">
      <MapBackdrop />

      {/* off-map airport strip */}
      <div className="map-airport">
        <span className="ma-ic"><Icon name="plane" /></span>
        <div>
          <div className="ma-title">Airport <span className="faint">· off map</span></div>
          <div className="ma-vans">
            {airportDrivers.length === 0
              ? <span className="faint" style={{ fontSize: 11.5 }}>No vans at airport</span>
              : airportDrivers.map((d) => {
                  const st = Store.STATUSES[d.status];
                  return <span key={d.id} className={"ma-chip tone-" + st.tone} title={d.name + " · " + st.label}><span className="pdot" />{veh(d.vehicleId).name}</span>;
                })}
          </div>
        </div>
      </div>

      {/* legend */}
      <div className="map-legend">
        <span className="ml-row"><span className="pdot" style={{ background: "var(--green)" }} />Available</span>
        <span className="ml-row"><span className="pdot" style={{ background: "var(--amber)" }} />En route</span>
        <span className="ml-row"><span className="pdot" style={{ background: "var(--violet)" }} />At pickup</span>
        <span className="ml-row"><span className="pdot" style={{ background: "var(--blue)" }} />Aboard</span>
        <span className="ml-row"><span className="pdot" style={{ background: "var(--slate)" }} />Resting</span>
      </div>

      {/* location markers */}
      {mapLocs.map((loc, i) => {
        const c = coordsFor(loc, i, mapLocs.length);
        const drivers = byLoc[loc.id] || [];
        const icon = loc.kind === "venue" ? "star" : "home";
        return (
          <div key={loc.id} className={"map-marker kind-" + loc.kind} style={{ left: c.x + "%", top: c.y + "%" }}>
            <div className="mm-pin">
              <Icon name={icon} />
              {drivers.length > 0 && <span className="mm-badge mono">{drivers.length}</span>}
            </div>
            <div className="mm-card">
              <div className="mm-name">{loc.name}</div>
              <div className="mm-vans">
                {drivers.length === 0
                  ? <span className="faint" style={{ fontSize: 11 }}>No vans here</span>
                  : drivers.slice(0, 6).map((d) => {
                      const st = Store.STATUSES[d.status];
                      return (
                        <span key={d.id} className={"mm-chip tone-" + st.tone} title={d.name + " · " + st.label}>
                          <span className="pdot" />
                          <span className="mono">{veh(d.vehicleId).name}</span>
                        </span>
                      );
                    })}
                {drivers.length > 6 && <span className="mm-chip" style={{ color: "var(--ink-dim)" }}>+{drivers.length - 6}</span>}
              </div>
            </div>
          </div>
        );
      })}

      <div className="map-foot">{activeCount} active · position reflects each driver’s reported status</div>
    </div>
  );
}

Object.assign(window, { MapBoard });
