// Repair shops — truck + reefer mechanical work, OSM-pinned. Same
// pattern as the weigh-stations page: paginated load (PostgREST 1000-
// row default), search + state filter + kind filter (truck / reefer /
// both), Leaflet+markercluster map, popup with directions + phone +
// hours when known.

const { useState: useStateRP, useEffect: useEffectRP, useRef: useRefRP, useMemo: useMemoRP } = React;

function RepairShopsPage({ onNav }) {
  const [shops, setShops] = useStateRP([]);
  const [loading, setLoading] = useStateRP(true);
  const [filter, setFilter] = useStateRP({ state: null, kind: "all", q: "" });
  const mapRef = useRefRP(null);
  const elRef = useRefRP(null);
  const layerRef = useRefRP(null);

  useEffectRP(() => {
    let alive = true;
    if (!window.SI_DB || !window.SI_DB.raw) { setLoading(false); return; }
    (async () => {
      try {
        const all = [];
        let offset = 0;
        const PAGE = 1000;
        while (alive) {
          const rows = await window.SI_DB.raw.select(
            "repair_shops",
            `select=id,name,state,lat,lng,address,phone,website,hours,kind,brands&order=state.asc,name.asc&limit=${PAGE}&offset=${offset}`
          );
          if (!Array.isArray(rows) || rows.length === 0) break;
          all.push(...rows);
          if (rows.length < PAGE) break;
          offset += PAGE;
        }
        if (!alive) return;
        setShops(all);
      } catch {} finally { if (alive) setLoading(false); }
    })();
    return () => { alive = false; };
  }, []);

  useEffectRP(() => {
    if (!elRef.current || !window.L || mapRef.current) return;
    const map = window.L.map(elRef.current, {
      zoomControl: true, scrollWheelZoom: false, attributionControl: true,
      worldCopyJump: false, minZoom: 3, maxZoom: 13, fadeAnimation: false,
    }).setView([39.5, -98.5], 4);
    window.L.tileLayer(
      "https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png",
      { attribution: "OSM repair-shop data · © OpenStreetMap · © CARTO",
        subdomains: "abcd", maxZoom: 13, noWrap: true }
    ).addTo(map);
    mapRef.current = map;
    setTimeout(() => map.invalidateSize(), 80);
    return () => { map.remove(); mapRef.current = null; };
  }, []);

  const KIND_COLOR = {
    truck:  "#0F4DA8",  // blue
    reefer: "#16a34a",  // green
    both:   "#7c3aed",  // violet
  };
  const KIND_LABEL = { truck: "Truck", reefer: "Reefer", both: "Truck + reefer" };

  const filtered = useMemoRP(() => {
    return shops.filter(s => {
      if (filter.state && s.state !== filter.state) return false;
      if (filter.kind !== "all" && s.kind !== filter.kind) {
        // "Reefer" filter should also match "both" since those handle reefer.
        if (filter.kind === "reefer" && s.kind === "both") {} else
        if (filter.kind === "truck"  && s.kind === "both") {} else return false;
      }
      if (filter.q.trim()) {
        const q = filter.q.toLowerCase();
        if (!(s.name || "").toLowerCase().includes(q) &&
            !(s.address || "").toLowerCase().includes(q) &&
            !((s.brands || []).join(" ").toLowerCase().includes(q))) return false;
      }
      return s.lat != null && s.lng != null;
    });
  }, [shops, filter]);

  useEffectRP(() => {
    const map = mapRef.current;
    if (!map || !window.L) return;
    if (layerRef.current && map.hasLayer(layerRef.current)) map.removeLayer(layerRef.current);
    const cluster = window.L.markerClusterGroup
      ? window.L.markerClusterGroup({ chunkedLoading: true, maxClusterRadius: 50 })
      : window.L.layerGroup();
    filtered.forEach(s => {
      const color = KIND_COLOR[s.kind] || "#444";
      const html = `<span style="display:block;width:12px;height:12px;border-radius:50%;background:${color};border:1.5px solid #fff;box-shadow:0 0 0 1px rgba(0,0,0,0.25)"></span>`;
      const icon = window.L.divIcon({
        className: "rs-pin", html,
        iconSize: [15, 15], iconAnchor: [7.5, 7.5],
      });
      const m = window.L.marker([s.lat, s.lng], { icon, riseOnHover: true });
      const dirUrl = `https://www.google.com/maps/dir/?api=1&destination=${s.lat},${s.lng}&travelmode=driving`;
      const phoneLine = s.phone ? `<div style="font-size:12px;margin-top:4px"><a href="tel:${s.phone.replace(/[^+0-9]/g,'')}" style="color:#0F4DA8;text-decoration:none">📞 ${s.phone}</a></div>` : "";
      const hoursLine = s.hours ? `<div style="font-family:monospace;font-size:11px;color:#666;margin-top:4px">${s.hours}</div>` : "";
      const webLine = s.website ? `<div style="font-size:11px;margin-top:4px"><a href="${s.website}" target="_blank" rel="noopener noreferrer" style="color:#666">${s.website.replace(/^https?:\/\//,'').replace(/\/$/,'')}</a></div>` : "";
      const brandsLine = (s.brands && s.brands.length)
        ? `<div style="font-family:Helvetica;font-size:11px;color:#16a34a;margin-top:6px;font-weight:600">${s.brands.join(" · ")}</div>` : "";
      m.bindPopup(`
        <div style="font-family:system-ui;font-size:12px;line-height:1.4;min-width:200px">
          <div style="font-family:Helvetica;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;font-size:10px;color:${color};margin-bottom:4px">
            ${KIND_LABEL[s.kind] || "Repair"} · ${s.state || ""}
          </div>
          <div style="font-weight:600;font-size:14px">${(s.name || "Repair shop").replace(/'/g,"&#39;")}</div>
          ${s.address ? `<div style="font-size:12px;color:#666;margin-top:4px">${s.address}</div>` : ""}
          ${phoneLine}${hoursLine}${webLine}${brandsLine}
          <div style="margin-top:8px"><a href="${dirUrl}" target="_blank" rel="noopener noreferrer"
            style="display:inline-block;padding:4px 10px;border:1px solid ${color};border-radius:3px;color:${color};text-decoration:none;font-family:Helvetica;font-size:11px;font-weight:600;letter-spacing:0.04em;text-transform:uppercase">Directions →</a></div>
        </div>
      `);
      cluster.addLayer(m);
    });
    cluster.addTo(map);
    layerRef.current = cluster;
    if (filtered.length >= 2) {
      try {
        map.fitBounds(window.L.latLngBounds(filtered.map(f => [f.lat, f.lng])).pad(0.08));
      } catch {}
    }
  }, [filtered]);

  const stateOptions = useMemoRP(() => {
    const s = new Set();
    shops.forEach(r => r.state && s.add(r.state));
    return Array.from(s).sort();
  }, [shops]);

  const counts = useMemoRP(() => {
    const c = { all: shops.length, truck: 0, reefer: 0, both: 0 };
    shops.forEach(s => { c[s.kind] = (c[s.kind] || 0) + 1; });
    return c;
  }, [shops]);

  return (
    <div className="rs-page">
      <style>{`
        .rs-page { background: var(--paper); padding-bottom: 96px; min-height: 100vh; }
        .rs-hero { max-width: 1200px; margin: 0 auto; padding: 56px 24px 24px; }
        .rs-back {
          display: inline-flex; gap: 6px; font-family: var(--font-mono); font-size: 11px;
          letter-spacing: 0.16em; text-transform: uppercase; color: var(--ink-soft);
          background: transparent; border: 0; cursor: pointer; padding: 0 0 16px;
        }
        .rs-back:hover { color: var(--ink); }
        .rs-mark {
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.32em;
          text-transform: uppercase; color: var(--ink-soft); margin-bottom: 14px;
          display: inline-flex; align-items: center; gap: 10px;
        }
        .rs-mark .dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%;
          background: oklch(0.55 0.18 145); }
        .rs-title { font-family: var(--font-serif); font-size: 56px; line-height: 1.04;
          letter-spacing: -0.028em; margin: 0 0 16px; }
        .rs-title em { font-style: italic; color: oklch(0.50 0.18 145); }
        .rs-dek { font-size: 16px; line-height: 1.55; color: var(--ink-soft); margin: 0; max-width: 760px; }
        @media (max-width: 700px) { .rs-title { font-size: 38px; } }

        .rs-controls {
          max-width: 1200px; margin: 24px auto 0; padding: 0 24px;
          display: flex; gap: 12px; flex-wrap: wrap; align-items: center;
        }
        .rs-search {
          flex: 1; min-width: 240px;
          padding: 10px 14px; border: 1px solid var(--rule); border-radius: 6px;
          background: #fff; font-family: inherit; font-size: 14px; color: var(--ink);
          outline: none;
        }
        .rs-search:focus { border-color: var(--ink); }
        .rs-pill-row { display: flex; gap: 6px; flex-wrap: wrap; }
        .rs-pill {
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.08em;
          padding: 6px 12px; border: 1px solid var(--rule); border-radius: 4px;
          background: #fff; cursor: pointer; color: var(--ink-soft);
          text-transform: uppercase;
        }
        .rs-pill:hover { color: var(--ink); border-color: var(--ink-soft); }
        .rs-pill.is-active {
          background: var(--ink); color: #fff; border-color: var(--ink);
        }
        .rs-pill.is-active.tone-reefer { background: #16a34a; border-color: #16a34a; }
        .rs-pill.is-active.tone-both { background: #7c3aed; border-color: #7c3aed; }
        .rs-state-row { display: flex; gap: 6px; flex-wrap: wrap; }

        .rs-counts {
          max-width: 1200px; margin: 12px auto; padding: 0 24px;
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.06em;
          color: var(--ink-soft);
          display: flex; justify-content: space-between; align-items: baseline;
        }

        .rs-map-wrap { max-width: 1200px; margin: 0 auto; padding: 0 24px; }
        .rs-map {
          width: 100%; height: 600px; border-radius: 8px;
          border: 1px solid var(--rule); overflow: hidden;
          background: var(--paper-2);
        }
        @media (max-width: 700px) { .rs-map { height: 480px; } }

        .rs-foot {
          max-width: 800px; margin: 28px auto 0; padding: 0 24px;
          font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.04em;
          color: var(--ink-soft); line-height: 1.7; font-style: italic;
        }
      `}</style>

      <section className="rs-hero">
        <button className="rs-back" onClick={() => onNav("drivers")}>← Back to The Yard</button>
        <div className="rs-mark"><span className="dot" /> Repair shops</div>
        <h1 className="rs-title">Truck + reefer <em>repair</em> on your route.</h1>
        <p className="rs-dek">
          Truck and reefer mechanical service across the lower 48. Filter by
          truck-only, reefer-only, or shops that handle both — Thermo King and
          Carrier Transicold service points are picked up by name. Phone,
          hours, and website where we have them. Live status (open now / parts
          in stock) is the next layer.
        </p>
      </section>

      <div className="rs-controls">
        <input className="rs-search" type="search"
          placeholder="Search by name, address, or brand…"
          value={filter.q} onChange={e => setFilter(f => ({ ...f, q: e.target.value }))} />
        <div className="rs-pill-row">
          <button className={`rs-pill ${filter.kind === "all" ? "is-active" : ""}`}
            onClick={() => setFilter(f => ({ ...f, kind: "all" }))}>
            All ({counts.all})
          </button>
          <button className={`rs-pill ${filter.kind === "truck" ? "is-active" : ""}`}
            onClick={() => setFilter(f => ({ ...f, kind: "truck" }))}>
            Truck ({counts.truck + counts.both})
          </button>
          <button className={`rs-pill tone-reefer ${filter.kind === "reefer" ? "is-active" : ""}`}
            onClick={() => setFilter(f => ({ ...f, kind: "reefer" }))}>
            Reefer ({counts.reefer + counts.both})
          </button>
          <button className={`rs-pill tone-both ${filter.kind === "both" ? "is-active" : ""}`}
            onClick={() => setFilter(f => ({ ...f, kind: "both" }))}>
            Both ({counts.both})
          </button>
        </div>
      </div>

      <div className="rs-controls">
        <button className={`rs-pill ${filter.state == null ? "is-active" : ""}`}
          onClick={() => setFilter(f => ({ ...f, state: null }))}>All states</button>
        <div className="rs-state-row">
          {stateOptions.map(s => (
            <button key={s}
              className={`rs-pill ${filter.state === s ? "is-active" : ""}`}
              onClick={() => setFilter(f => ({ ...f, state: f.state === s ? null : s }))}
            >{s}</button>
          ))}
        </div>
      </div>

      <div className="rs-counts">
        <span>
          {loading ? "Loading…" : <>{filtered.length.toLocaleString()} shop{filtered.length === 1 ? "" : "s"}
            {filter.state || filter.q || filter.kind !== "all" ? <> · of {shops.length.toLocaleString()} total</> : null}</>}
        </span>
        <span>
          <span style={{ display: "inline-block", width: 10, height: 10, borderRadius: "50%", background: "#0F4DA8", marginRight: 5, verticalAlign: "middle" }} />Truck
          {" · "}
          <span style={{ display: "inline-block", width: 10, height: 10, borderRadius: "50%", background: "#16a34a", marginRight: 5, verticalAlign: "middle" }} />Reefer
          {" · "}
          <span style={{ display: "inline-block", width: 10, height: 10, borderRadius: "50%", background: "#7c3aed", marginRight: 5, verticalAlign: "middle" }} />Both
        </span>
      </div>

      <div className="rs-map-wrap">
        <div className="rs-map" ref={elRef} />
      </div>

      <p className="rs-foot">
        Coverage is partial — small independent shops may not appear yet. If
        a shop you trust isn't on the map, drop a tip on the terminal page
        and we'll add it manually.
      </p>
    </div>
  );
}

window.RepairShopsPage = RepairShopsPage;
