// LocationFinder.jsx — two-column page: location list (left) + map (right)
// Selecting a card highlights its pin and opens an info card on the map.
// Clicking a pin does the same. Clicking the map background closes the info card.

const LOCATIONS = [
  {
    id: "langley",
    name: "Langley - Preston Collision",
    distance: "4.2 KM",
    addr1: "20091 Logan Avenue",
    addr2: "Langley City, BC V3A 4L5",
    status: "open",
    statusText: "OPEN UNTIL 5:00 PM",
    rating: 4.7, reviews: 182, drive: "32M AWAY",
    services: ["Full Collision Repair", "Glass Repair", "Scratch Repair & Paint"],
    pin: { x: "82%", y: "78%" },
  },
  {
    id: "north-van",
    name: "North Vancouver",
    distance: "0.8 KM",
    addr1: "North Vancouver - Coache Collision Ltd.",
    addr2: "1172 West 3rd St.",
    addr3: "North Vancouver, BC V7P 1E6",
    status: "open",
    statusText: "OPEN UNTIL 5:00 PM",
    preferred: true,
    rating: 4.9, reviews: 240, drive: "15M AWAY",
    services: ["Full Collision Repair", "Glass Repair", "Scratch Repair & Paint"],
    pin: { x: "62%", y: "33%" },
  },
  {
    id: "coquitlam",
    name: "Coquitlam - Mountain Hwy",
    distance: "12.5 KM",
    addr1: "2760 Aberdeen Ave #1",
    addr2: "Coquitlam, BC V3B 1A3",
    status: "closed",
    statusText: "CLOSED UNTIL 8:00 AM",
    rating: 4.6, reviews: 96, drive: "24M AWAY",
    services: ["Full Collision Repair", "Wheel Alignment", "Auto Detailing"],
    pin: { x: "88%", y: "42%" },
  },
  {
    id: "mission",
    name: "CARSTAR Mission",
    distance: "30.1 KM",
    addr1: "7077 Mershon Street",
    addr2: "Mission, BC V2V 2X9",
    status: "open",
    statusText: "OPEN UNTIL 6:00 PM",
    rating: 4.5, reviews: 64, drive: "48M AWAY",
    services: ["Full Collision Repair", "Glass Repair"],
    pin: { x: "95%", y: "62%" },
  },
  {
    id: "burnaby",
    name: "Burnaby - Lougheed",
    distance: "8.9 KM",
    addr1: "4180 Lougheed Highway",
    addr2: "Burnaby, BC V5C 6A7",
    status: "open",
    statusText: "OPEN UNTIL 5:30 PM",
    rating: 4.8, reviews: 311, drive: "21M AWAY",
    services: ["Full Collision Repair", "Scratch Repair & Paint", "Auto Detailing"],
    pin: { x: "74%", y: "55%" },
  },
  {
    id: "richmond",
    name: "Richmond - No. 5 Road",
    distance: "15.3 KM",
    addr1: "12320 No. 5 Road",
    addr2: "Richmond, BC V7A 4E9",
    status: "open",
    statusText: "OPEN UNTIL 5:00 PM",
    rating: 4.7, reviews: 148, drive: "28M AWAY",
    services: ["Full Collision Repair", "Glass Repair", "Wheel Alignment"],
    pin: { x: "52%", y: "76%" },
  },
];

function StatusDot({ status }) {
  return <span className={"rd-loc__dot rd-loc__dot--" + status} />;
}

function PhoneIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.79 19.79 0 0 1 2.12 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.72 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0 1 22 16.92Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function BookIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <rect x="3" y="4" width="18" height="18" rx="2" stroke="currentColor" strokeWidth="2" />
      <path d="M16 2v4M8 2v4M3 10h18" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
    </svg>
  );
}

function PinIcon() {
  return (
    <svg width="14" height="16" viewBox="0 0 14 16" fill="none" aria-hidden="true">
      <path d="M7 1C4 1 1.5 3.4 1.5 6.4c0 4 5.5 8.6 5.5 8.6s5.5-4.6 5.5-8.6C12.5 3.4 10 1 7 1Z" stroke="currentColor" strokeWidth="1.5" />
      <circle cx="7" cy="6.4" r="1.8" fill="currentColor" />
    </svg>
  );
}

function StarIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path d="M12 2l3.09 6.26L22 9.27l-5 4.87L18.18 22 12 18.56 5.82 22 7 14.14 2 9.27l6.91-1.01L12 2z" />
    </svg>
  );
}

function LocationCard({ loc, selected, onSelect }) {
  return (
    <button
      type="button"
      className={"rd-loc" + (selected ? " is-selected" : "")}
      onClick={onSelect}
    >
      <div className="rd-loc__head">
        <h3 className="rd-loc__name">{loc.name}</h3>
        <span className="rd-loc__distance">{loc.distance}</span>
      </div>
      <div className={"rd-loc__addr" + (selected ? " is-accent" : "")}>
        {loc.addr1 && <div>{loc.addr1}</div>}
        {loc.addr2 && <div>{loc.addr2}</div>}
        {loc.addr3 && <div>{loc.addr3}</div>}
      </div>
      <div className="rd-loc__status">
        <StatusDot status={loc.status} />
        <span>{loc.statusText}</span>
      </div>
      <div className="rd-loc__actions" onClick={(e) => e.stopPropagation()}>
        <a href="tel:+1" className="rd-loc__btn rd-loc__btn--dark">
          <PhoneIcon /> CALL
        </a>
        <a href="#" className="rd-loc__btn rd-loc__btn--red">
          <BookIcon /> BOOK
        </a>
      </div>
    </button>
  );
}

function MapInfoCard({ loc, anchor }) {
  // Decide which side of the pin the info card sits on so it doesn't run
  // off the edge of the map. Pin in the right half → card to the left of pin.
  const xPct = parseFloat(anchor.x);
  const fromRight = xPct >= 55;
  const pos = fromRight
    ? { right: `calc(100% - ${anchor.x} + 24px)`, top: `calc(${anchor.y} - 80px)` }
    : { left:  `calc(${anchor.x} + 32px)`,        top: `calc(${anchor.y} - 80px)` };
  return (
    <div className="rd-map__info" style={pos} onClick={(e) => e.stopPropagation()}>
      {loc.preferred && <div className="rd-map__info-tag">PREFERRED CENTER</div>}
      <h3 className="rd-map__info-name">{loc.name}</h3>
      <div className="rd-map__info-meta">
        <span className="rd-map__info-rating">
          <StarIcon /> {loc.rating.toFixed(1)}
        </span>
        <span className="rd-map__info-dim">({loc.reviews} REVIEWS)</span>
        <span className="rd-map__info-dot">·</span>
        <span className="rd-map__info-dim">{loc.drive}</span>
      </div>
      <ul className="rd-map__info-list">
        {loc.services.map((s) => <li key={s}>{s}</li>)}
      </ul>
      <a href="#" className="rd-map__info-cta">GET DIRECTIONS</a>
    </div>
  );
}

function FauxMap() {
  // Stylized top-down Vancouver-ish map. Water on north/west, green parks,
  // a few labeled roads/regions. Pure SVG so it scales with the container.
  return (
    <svg className="rd-map__svg" viewBox="0 0 1000 700" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
      <defs>
        <pattern id="rd-map-grid" width="80" height="80" patternUnits="userSpaceOnUse">
          <path d="M80 0H0v80" fill="none" stroke="#E6E2D9" strokeWidth="1" />
        </pattern>
      </defs>
      {/* land base */}
      <rect width="1000" height="700" fill="#EFEAE0" />
      <rect width="1000" height="700" fill="url(#rd-map-grid)" />
      {/* Burrard Inlet — water across the top */}
      <path d="M0 0 H1000 V200 C 880 230, 760 180, 620 215 C 480 250, 360 200, 220 230 C 120 250, 60 220, 0 240 Z" fill="#CBE3EE" />
      {/* Pacific — water on the west */}
      <path d="M0 240 V700 H140 C 120 600, 160 500, 130 400 C 110 320, 90 280, 0 240 Z" fill="#CBE3EE" />
      {/* Stanley Park */}
      <ellipse cx="300" cy="280" rx="90" ry="60" fill="#D6E6C8" />
      <text x="300" y="285" textAnchor="middle" fill="#8AA37A" fontSize="11" fontFamily="system-ui" letterSpacing="1">STANLEY PARK</text>
      {/* North Van blob */}
      <path d="M380 130 C 520 90, 700 110, 880 100 L 900 200 C 760 220, 600 195, 440 215 C 410 200, 390 175, 380 130 Z" fill="#E5E0D4" />
      <text x="640" y="160" textAnchor="middle" fill="#6F6650" fontSize="12" fontFamily="system-ui" letterSpacing="2">NORTH VANCOUVER</text>
      {/* Capilano Park */}
      <path d="M510 60 C 560 50, 600 70, 590 110 C 580 140, 540 140, 510 120 Z" fill="#D6E6C8" />
      <text x="555" y="95" textAnchor="middle" fill="#8AA37A" fontSize="10" fontFamily="system-ui">CAPILANO</text>
      {/* Vancouver label */}
      <text x="500" y="490" textAnchor="middle" fill="#3F3A2E" fontSize="34" fontFamily="system-ui" fontWeight="600" letterSpacing="2">Vancouver</text>
      {/* Granville Island */}
      <ellipse cx="380" cy="430" rx="36" ry="14" fill="#D6E6C8" />
      <text x="380" y="455" textAnchor="middle" fill="#6F6650" fontSize="9" fontFamily="system-ui">GRANVILLE ISLAND</text>
      {/* Park splotches scattered */}
      <ellipse cx="700" cy="380" rx="36" ry="28" fill="#D6E6C8" />
      <ellipse cx="820" cy="540" rx="50" ry="30" fill="#D6E6C8" />
      <ellipse cx="180" cy="560" rx="48" ry="32" fill="#D6E6C8" />
      <ellipse cx="560" cy="610" rx="44" ry="26" fill="#D6E6C8" />
      <ellipse cx="900" cy="320" rx="34" ry="22" fill="#D6E6C8" />
      {/* Highways */}
      <path d="M0 360 L 1000 380" stroke="#E8B57A" strokeWidth="6" fill="none" />
      <path d="M0 360 L 1000 380" stroke="#fff" strokeWidth="2" fill="none" strokeDasharray="4 6" />
      <path d="M520 200 L 530 700" stroke="#E8B57A" strokeWidth="5" fill="none" />
      <path d="M520 200 L 530 700" stroke="#fff" strokeWidth="1.5" fill="none" strokeDasharray="4 6" />
      {/* Streets */}
      <g stroke="#D8D2C1" strokeWidth="1.5" fill="none">
        <path d="M0 300 H1000" />
        <path d="M0 440 H1000" />
        <path d="M0 520 H1000" />
        <path d="M0 600 H1000" />
        <path d="M200 200 V700" />
        <path d="M340 200 V700" />
        <path d="M680 200 V700" />
        <path d="M820 200 V700" />
      </g>
      {/* Region labels */}
      <text x="160" y="420" fill="#6F6650" fontSize="10" fontFamily="system-ui" letterSpacing="1">KITSILANO</text>
      <text x="660" y="500" fill="#6F6650" fontSize="10" fontFamily="system-ui" letterSpacing="1">MOUNT PLEASANT</text>
      <text x="860" y="450" fill="#6F6650" fontSize="10" fontFamily="system-ui" letterSpacing="1">BURNABY</text>
      <text x="160" y="660" fill="#6F6650" fontSize="10" fontFamily="system-ui" letterSpacing="1">MARPOLE</text>
    </svg>
  );
}

function MapPin({ loc, selected, onClick }) {
  return (
    <button
      type="button"
      className={"rd-map__pin" + (selected ? " is-selected" : "")}
      style={{ left: loc.pin.x, top: loc.pin.y }}
      onClick={onClick}
      aria-label={loc.name}
    >
      <span className="rd-map__pin-diamond">
        <span className="rd-map__pin-glyph" />
      </span>
    </button>
  );
}

function LocationFinder() {
  const [selectedId, setSelectedId] = React.useState("north-van");
  const [query, setQuery] = React.useState("");
  const [zoom, setZoom] = React.useState(1);
  const cardRefs = React.useRef({});
  const mapRef = React.useRef(null);

  const ZOOM_MIN = 0.8;
  const ZOOM_MAX = 2.8;
  const clampZoom = (z) => Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, z));

  // Capture wheel events on the map so the page never scrolls past the
  // two columns. Up = zoom in, down = zoom out.
  React.useEffect(() => {
    const el = mapRef.current;
    if (!el) return;
    const onWheel = (e) => {
      e.preventDefault();
      const delta = -e.deltaY * 0.0015;
      setZoom((z) => clampZoom(z * (1 + delta)));
    };
    el.addEventListener("wheel", onWheel, { passive: false });
    return () => el.removeEventListener("wheel", onWheel);
  }, []);

  // When sidebar selection changes via clicking a pin, scroll its card
  // into view in the sidebar list.
  React.useEffect(() => {
    const el = cardRefs.current[selectedId];
    if (el && el.parentElement) {
      const parent = el.parentElement;
      const top = el.offsetTop - parent.offsetTop;
      parent.scrollTo({ top, behavior: "smooth" });
    }
  }, [selectedId]);

  const selected = LOCATIONS.find((l) => l.id === selectedId);

  return (
    <main className="rd-finder" data-screen-label="02 Location Finder">
      <aside className="rd-finder__sidebar">
        <h1 className="rd-finder__title">Find Your Local RAYDAR</h1>
        <form
          className="rd-finder__search"
          onSubmit={(e) => { e.preventDefault(); }}
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true">
            <circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="2" />
            <path d="m20 20-3.5-3.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
          </svg>
          <input
            type="text"
            placeholder="City, Province or Postal"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
        </form>
        <button type="button" className="rd-finder__use-loc">
          <PinIcon /> USE MY LOCATION
        </button>
        <div className="rd-finder__list">
          {LOCATIONS.map((loc) => (
            <div key={loc.id} ref={(el) => (cardRefs.current[loc.id] = el)}>
              <LocationCard
                loc={loc}
                selected={loc.id === selectedId}
                onSelect={() => setSelectedId(loc.id)}
              />
            </div>
          ))}
        </div>
      </aside>

      <div
        className="rd-finder__map"
        ref={mapRef}
        onClick={(e) => {
          // Clicking the map background (not a pin / info card) deselects.
          if (e.target === e.currentTarget || e.target.tagName === "svg" || e.target.closest(".rd-map__svg")) {
            setSelectedId(null);
          }
        }}
      >
        <div className="rd-map__viewport" style={{ transform: `scale(${zoom})` }}>
          <FauxMap />
          {LOCATIONS.map((loc) => (
            <MapPin
              key={loc.id}
              loc={loc}
              selected={loc.id === selectedId}
              onClick={(e) => { e.stopPropagation(); setSelectedId(loc.id); }}
            />
          ))}
          {selected && <MapInfoCard loc={selected} anchor={selected.pin} />}
        </div>

        <div className="rd-map__zoom">
          <button type="button" aria-label="Zoom in" onClick={() => setZoom((z) => clampZoom(z * 1.2))}>+</button>
          <button type="button" aria-label="Zoom out" onClick={() => setZoom((z) => clampZoom(z / 1.2))}>−</button>
        </div>
        <button type="button" className="rd-map__layers" aria-label="Map layers">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
            <path d="M12 2 2 7l10 5 10-5-10-5Z" stroke="currentColor" strokeWidth="2" strokeLinejoin="round" />
            <path d="m2 17 10 5 10-5M2 12l10 5 10-5" stroke="currentColor" strokeWidth="2" strokeLinejoin="round" />
          </svg>
        </button>
        <div className="rd-map__attrib">Map data ©2026 Google</div>
      </div>
    </main>
  );
}

window.LocationFinder = LocationFinder;
