// Villa Mesochori — local guide with real photos (Wikimedia Commons) and a map of the area.
const guideNS = window.VillaMesochoriDesignSystem_9e1a21;
const { Card: GCard, Tag: GTag, Badge: GBadge, LucideIcon: GIcon } = guideNS;

const commons = (file, w) =>
  `https://commons.wikimedia.org/wiki/Special:FilePath/${encodeURIComponent(file)}?width=${w || 800}`;

// Places now come from the content store — fully editable in the owners' area.
const HOUSE = { lat: 36.5359, lng: 23.0799 };

// Guide-card image with a graceful branded fallback if the photo can't load
function GImg({ src, alt }) {
  const [failed, setFailed] = React.useState(false);
  if (failed || !src) {
    return (
      <div style={{ width: "100%", height: "100%", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 8, background: "var(--surface-sunken)", border: "1px solid var(--border-soft)", color: "var(--text-muted)" }}>
        <GIcon name="image" size={22} />
        <span style={{ font: "var(--type-small)" }}>{alt}</span>
      </div>
    );
  }
  return <img src={src} alt={alt} loading="lazy" onError={() => setFailed(true)} style={{ width: "100%", height: "100%", objectFit: "cover", display: "block", background: "var(--surface-sunken)" }} />;
}

const guideCommonsBase = commons; // alias

function GuideMap({ places, onPick }) {
  const ref = React.useRef(null);
  const mapRef = React.useRef(null);
  const layerRef = React.useRef(null);

  React.useEffect(() => {
    if (!window.L || !ref.current || mapRef.current) return;
    const map = L.map(ref.current, { scrollWheelZoom: false });
    L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
    }).addTo(map);
    mapRef.current = map;
    layerRef.current = L.layerGroup().addTo(map);
    return () => { map.remove(); mapRef.current = null; };
  }, []);

  React.useEffect(() => {
    const map = mapRef.current, layer = layerRef.current;
    if (!map || !layer) return;
    layer.clearLayers();
    const house = L.circleMarker([HOUSE.lat, HOUSE.lng], {
      radius: 10, color: "#FAF6EF", weight: 2, fillColor: "#C05E37", fillOpacity: 1,
    }).addTo(layer).bindPopup("<b>Villa Mesochori</b><br>The house — Mesochori village");
    const pts = [house.getLatLng()];
    places.forEach((p) => {
      if (!p.lat || !p.lng) return;
      const m = L.circleMarker([p.lat, p.lng], {
        radius: 7, color: "#FAF6EF", weight: 2, fillColor: "#4E7A5A", fillOpacity: 1,
      }).addTo(layer).bindPopup(`<b>${p.name}</b><br>${p.dist} from the house`);
      m.on("click", () => onPick && onPick(p.id));
      pts.push(m.getLatLng());
    });
    map.fitBounds(L.latLngBounds(pts).pad(0.18));
  }, [places]);

  return <div ref={ref} style={{ height: 420, borderRadius: "var(--radius-lg)", border: "1px solid var(--border-soft)", overflow: "hidden", zIndex: 0 }}></div>;
}

function Guide() {
  const [cat, setCat] = React.useState("All");
  const c = window.VMContent.get();
  const guidePlaces = (c.places || []).map((p, i) => Object.assign({ id: `p${i}` }, p));
  const guideCats = ["All"].concat([...new Set(guidePlaces.map((p) => p.cat).filter(Boolean))]);
  const shown = guidePlaces.filter((p) => cat === "All" || p.cat === cat);
  return (
    <div data-screen-label="Places to go" style={{ maxWidth: "var(--container-max)", margin: "0 auto", padding: "56px var(--container-pad) 0" }}>
      <span style={{ font: "var(--type-eyebrow)", letterSpacing: "var(--tracking-wide)", textTransform: "uppercase", color: "var(--secondary)" }}>Places to go</span>
      <h1 style={{ font: "var(--type-h1)", margin: "10px 0 12px" }}>{c.guideTitle}</h1>
      <p style={{ font: "var(--type-body-lg)", color: "var(--text-body)", maxWidth: 560, margin: "0 0 28px" }}>{c.guideIntro}</p>

      <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 32 }}>
        {guideCats.map((t) => <GTag key={t} selected={cat === t} onClick={() => setCat(t)}>{t}</GTag>)}
      </div>

      <div className="vm-stagger" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 24 }}>
        {shown.map((p) => (
          <div key={p.id} id={`guide-card-${p.id}`}>
            <GCard
              interactive
              media={
                <div style={{ height: 170 }}>
                  <GImg src={p.img} alt={p.name} />
                </div>
              }
              eyebrow={p.cat}
              title={p.name}
              footer={
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6, font: "var(--type-small)", color: "var(--text-muted)" }}>
                  <GIcon name="map-pin" size={14} /> {p.dist} from the house
                </span>
              }
            >
              <span style={{ font: "var(--type-hand)", fontSize: 20, color: "var(--limewash-600)" }}>"{p.tip}"</span>
            </GCard>
          </div>
        ))}
      </div>

      <div style={{ margin: "64px 0 0" }}>
        <span style={{ font: "var(--type-eyebrow)", letterSpacing: "var(--tracking-wide)", textTransform: "uppercase", color: "var(--accent)" }}>The map</span>
        <h2 style={{ font: "var(--type-h2)", margin: "10px 0 20px" }}>Everything within an hour of the house</h2>
        <GuideMap places={shown} />
        <p style={{ font: "var(--type-small)", color: "var(--text-muted)", margin: "12px 0 0" }}>
          The terracotta dot is the house. Photos: Wikimedia Commons (CC) — we'll swap in our own as we take them.
        </p>
      </div>

      <div style={{ marginTop: 40, display: "flex", justifyContent: "center" }}>
        <GBadge tone="accent">More places in the printed guide at the house</GBadge>
      </div>
    </div>
  );
}

window.VMGuide = Guide;
