// DetailModal + MapView (Leaflet)

const { useState: _useState, useEffect: _useEffect, useRef: _useRef, useMemo: _useMemo } = React;

// --------------------------------------------------------------
// DETAIL MODAL
// --------------------------------------------------------------
function DetailModal({ listing, onClose }) {
  const [idx, setIdx] = _useState(0);
  const history = _useMemo(() => parsePriceHistory(listing.price_history), [listing.price_history]);

  _useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowLeft") setIdx((i) => (i - 1 + listing.photos.length) % listing.photos.length);
      if (e.key === "ArrowRight") setIdx((i) => (i + 1) % listing.photos.length);
    };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [listing.photos.length, onClose]);

  // mini-map render on listing change
  const hasGeo = listing.latitude != null && listing.longitude != null;
  const mapRef = _useRef(null);
  _useEffect(() => {
    if (!mapRef.current || !window.L || !hasGeo) return;
    const map = window.L.map(mapRef.current, {
      zoomControl: false, attributionControl: false,
      scrollWheelZoom: false, dragging: false
    }).setView([listing.latitude, listing.longitude], 13);
    window.L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
      maxZoom: 19, crossOrigin: true,
    }).addTo(map);
    // divIcon dot (no marker-image asset dependency)
    window.L.marker([listing.latitude, listing.longitude], {
      icon: window.L.divIcon({ className: "geo-dot", html: "<span></span>", iconSize: [18, 18] })
    }).addTo(map);
    return () => map.remove();
  }, [listing.id, hasGeo]);

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal__hd">
          <div className="modal__ref">
            <span>REF</span><b>{listing.ref_id}</b>
            <span>·</span>
            <span>ID {listing.id}</span>
          </div>
          <button className="modal__close" onClick={onClose} aria-label="Close">
            <I.Close/>
          </button>
        </div>

        <div className="modal__body">
          <div className="modal__left">
            <div className="carousel">
              <img src={listing.photos[idx]} alt={listing.title}/>
              {listing.photos.length > 1 && (
                <>
                  <button className="carousel__nav carousel__nav--prev"
                    onClick={() => setIdx((i) => (i - 1 + listing.photos.length) % listing.photos.length)}>
                    <I.ChevronLeft/>
                  </button>
                  <button className="carousel__nav carousel__nav--next"
                    onClick={() => setIdx((i) => (i + 1) % listing.photos.length)}>
                    <I.ChevronRight/>
                  </button>
                  <div className="carousel__dots">
                    {listing.photos.map((_, i) => (
                      <span key={i} className={i === idx ? "on" : ""} onClick={() => setIdx(i)}/>
                    ))}
                  </div>
                </>
              )}
            </div>
            <div className="thumbs">
              {listing.photos.map((p, i) => (
                <button key={i} className={i === idx ? "on" : ""} onClick={() => setIdx(i)}>
                  <img src={p} alt=""/>
                </button>
              ))}
            </div>

            <h2 className="modal__title">{listing.title}</h2>
            <div className="modal__loc"><I.Pin/> {listing.location}</div>

            <p className="modal__desc">{listing.description}</p>

            <div className="modal__amen-h">Amenities</div>
            <div className="amenitygrid">
              {listing.amenities.map((a) => (
                <div key={a} className="amenity">
                  <span className="amenity__dot"/>{a}
                </div>
              ))}
            </div>
          </div>

          <div className="modal__right">
            <div className="priceblock">
              <div className="priceblock__big tnum">
                {fmtPrice(listing.price)}<em>/yr</em>
              </div>
              <div className="priceblock__sub">
                {(listing.price / 12).toLocaleString("en-US", { maximumFractionDigits: 0 })} AED/month ·
                {" "}{(listing.price / listing.size_sqft).toFixed(1)} AED/sqft
              </div>
            </div>

            <div className="specgrid">
              <div>
                <span className="spec__k">Bedrooms</span>
                <span className="spec__v">{listing.bedrooms}</span>
              </div>
              <div>
                <span className="spec__k">Bathrooms</span>
                <span className="spec__v">{listing.bathrooms}</span>
              </div>
              <div>
                <span className="spec__k">Size</span>
                <span className="spec__v">{listing.size_sqft.toLocaleString()} sqft</span>
              </div>
              <div>
                <span className="spec__k">Type</span>
                <span className="spec__v">{listing.property_type}</span>
              </div>
              <div>
                <span className="spec__k">Furnishing</span>
                <span className="spec__v">{listing.furnished}</span>
              </div>
              <div>
                <span className="spec__k">Balcony</span>
                <span className="spec__v">{listing.balcony}</span>
              </div>
              <div>
                <span className="spec__k">Water view</span>
                <span className="spec__v">{listing.water_view}</span>
              </div>
              <div>
                <span className="spec__k">Status</span>
                <span className="spec__v" style={{
                  color: listing.status === "delisted" ? "var(--danger)" : "var(--success)"
                }}>{listing.status}</span>
              </div>
            </div>

            {history.length > 0 ? (
              <div className="pricehist">
                <div className="pricehist__h">Price history</div>
                {history.map((h, i) => {
                  const up = h.to > h.from;
                  return (
                    <div key={i} className="pricehist__step">
                      <span className="pricehist__date">{fmtDate(h.date)}</span>
                      <span className="pricehist__from tnum">{fmtPriceShort(h.from)}</span>
                      <span className="pricehist__arrow">→</span>
                      <span className="pricehist__to tnum">{fmtPriceShort(h.to)}</span>
                      <span className={`delta delta--${up ? "up" : "down"}`}
                            style={{marginLeft:"auto"}}>
                        {up ? <I.ArrowUp/> : <I.ArrowDown/>}
                        {Math.round(Math.abs((h.to - h.from) / h.from) * 100)}%
                      </span>
                    </div>
                  );
                })}
              </div>
            ) : (
              <div className="pricehist">
                <div className="pricehist__h">Price history</div>
                <div style={{fontSize: 13, color: "var(--text-3)"}}>
                  No price changes since {fmtDate(listing.first_seen)}.
                </div>
              </div>
            )}

            <div className="modal__amen-h" style={{marginTop: 22}}>Location</div>
            {hasGeo ? (
              <>
                <div className="minimap" ref={mapRef}/>
                <div style={{fontSize: 12, color: "var(--text-3)"}}>
                  {listing.latitude.toFixed(4)}, {listing.longitude.toFixed(4)}
                </div>
              </>
            ) : (
              <div style={{fontSize: 13, color: "var(--text-3)"}}>
                No map coordinates for this listing.
              </div>
            )}
          </div>
        </div>

        <div className="modal__ft">
          <button className="btn btn--ghost" onClick={onClose}>Close</button>
          <a className="btn btn--primary" href={listing.url} target="_blank" rel="noopener noreferrer">
            View on Dubizzle <I.Ext/>
          </a>
        </div>
      </div>
    </div>
  );
}

// --------------------------------------------------------------
// MAP VIEW
// --------------------------------------------------------------
function MapView({ listings, onOpen, activeId, setActiveId }) {
  const ref = _useRef(null);
  const mapRef = _useRef(null);
  const markersRef = _useRef({});

  // init map once
  _useEffect(() => {
    if (!ref.current || !window.L) return;
    const map = window.L.map(ref.current, {
      zoomControl: true, attributionControl: true
    }).setView([24.466, 54.49], 11);
    window.L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
      maxZoom: 19,
      attribution: '© OpenStreetMap'
    }).addTo(map);
    mapRef.current = map;
    return () => { map.remove(); mapRef.current = null; };
  }, []);

  // rebuild markers when listings change
  _useEffect(() => {
    const map = mapRef.current;
    if (!map || !window.L) return;
    Object.values(markersRef.current).forEach((m) => map.removeLayer(m));
    markersRef.current = {};
    const geoListings = listings.filter((l) => l.latitude != null && l.longitude != null);
    if (!geoListings.length) return;
    const bounds = window.L.latLngBounds([]);
    geoListings.forEach((l) => {
      const isDelisted = l.status === "delisted";
      const isActive = l.id === activeId;
      const icon = window.L.divIcon({
        className: "price-marker-wrap",
        html: `<div class="price-marker ${isActive ? "is-active" : ""} ${isDelisted ? "is-delisted" : ""}">${fmtPriceShort(l.price)}</div>`,
        iconSize: [0, 0],
        iconAnchor: [0, 0]
      });
      const m = window.L.marker([l.latitude, l.longitude], { icon, riseOnHover: true });
      m.on("click", () => setActiveId(l.id));
      m.bindPopup(buildPopupHtml(l), { offset: [0, -8], closeButton: false, autoClose: true });
      m.on("popupopen", () => {
        const node = m.getPopup().getElement();
        node?.querySelector(".minicard__cta")?.addEventListener("click", () => onOpen(l));
        node?.querySelector(".minicard")?.addEventListener("click", () => onOpen(l));
      });
      m.addTo(map);
      markersRef.current[l.id] = m;
      bounds.extend([l.latitude, l.longitude]);
    });
    if (bounds.isValid()) {
      map.fitBounds(bounds, { padding: [60, 60], maxZoom: 13 });
    }
  }, [listings]);

  // open popup of active marker
  _useEffect(() => {
    if (!activeId) return;
    const m = markersRef.current[activeId];
    if (m) m.openPopup();
  }, [activeId, listings]);

  function buildPopupHtml(l) {
    return `
      <div class="minicard">
        <img src="${l.photos[0]}" alt=""/>
        <div class="minicard__body">
          <div class="minicard__price">${fmtPrice(l.price)}<span style="font-size:11px;color:var(--text-3);"> /yr</span></div>
          <div class="minicard__title">${l.title}</div>
          <div style="font-size:12px;color:var(--text-2);margin-top:4px;">${l.bedrooms} bd · ${l.bathrooms} ba · ${l.size_sqft.toLocaleString()} sqft</div>
          <div class="minicard__cta">Open details →</div>
        </div>
      </div>
    `;
  }

  return <div className="mapwrap" ref={ref}/>;
}

Object.assign(window, { DetailModal, MapView });
