// ============================================================
// HausMatch App · Screen 4 — Results Grid
// 6 matches. Grid / List / Map view. Filter slideover. Save + share.
// ============================================================

function ScreenResults({ onOpenListing, onRefine }) {
  const [view, setView] = React.useState("grid");
  const [filterOpen, setFilterOpen] = React.useState(false);
  const [toast, setToast] = React.useState(null);

  const flashToast = (msg) => {
    setToast(msg);
    window.clearTimeout(flashToast._t);
    flashToast._t = window.setTimeout(() => setToast(null), 2400);
  };

  return (
    <div className="screen results-screen">
      <AppBar current="matches" />
      <main className="results-main">
        <div className="results-head">
          <div className="results-head-left">
            <Eyebrow>Your matches</Eyebrow>
            <h1 className="results-title">
              <span className="hm-italic-accent">6 homes</span> that feel like yours.
            </h1>
            <div className="results-sub">
              <span>Matched on</span>
              <Chip variant="sage">Desert Modern</Chip>
              <Chip variant="sage">Organic Minimal</Chip>
              <span className="results-sub-dot">·</span>
              <span>across <strong>Paradise Valley</strong> and <strong>Scottsdale</strong></span>
              <span className="results-sub-dot">·</span>
              <a className="results-refine" onClick={onRefine}>Refine</a>
            </div>
          </div>
          <div className="results-reference">
            <div className="results-reference-label">
              <Eyebrow muted>Your reference</Eyebrow>
            </div>
            <img src={window.UPLOADED_HOME.img} alt="Your reference" />
          </div>
        </div>

        <div className="results-toolbar">
          <div className="results-toolbar-left">
            <button className={`results-view-btn ${view === "grid" ? "is-active" : ""}`} onClick={() => setView("grid")}>
              <Icon name="grid" size={14} /> Grid
            </button>
            <button className={`results-view-btn ${view === "list" ? "is-active" : ""}`} onClick={() => setView("list")}>
              <Icon name="list" size={14} /> List
            </button>
            <button className={`results-view-btn ${view === "map" ? "is-active" : ""}`} onClick={() => setView("map")}>
              <Icon name="map" size={14} /> Map
            </button>
          </div>
          <div className="results-toolbar-right">
            <span className="hm-mono" style={{ fontSize: 11, color: "var(--fg-4)", letterSpacing: "0.12em" }}>
              SORTED BY AESTHETIC FIT
            </span>
            <button className="results-filter-btn" onClick={() => setFilterOpen(true)}>
              <Icon name="sliders" size={14} />
              Filter
            </button>
          </div>
        </div>

        {view === "grid" && (
          <div className="results-grid">
            {window.MATCHES.map((m) => (
              <ListingCard
                key={m.id}
                listing={m}
                onClick={() => onOpenListing && onOpenListing(m)}
              />
            ))}
          </div>
        )}

        {view === "list" && (
          <div className="results-list">
            {window.MATCHES.map((m) => (
              <article key={m.id} className="results-list-row" onClick={() => onOpenListing && onOpenListing(m)}>
                <div className="results-list-photo">
                  <img src={m.photos[0]} alt={m.address} />
                  <div className="results-list-match">
                    <MatchBadge pct={m.sim} size={40} />
                  </div>
                </div>
                <div className="results-list-body">
                  <div className="results-list-row-top">
                    <h3 className="results-list-price">{m.price}</h3>
                    <div className="results-list-specs hm-mono">
                      {m.beds} bd · {m.baths} ba · {m.sqft.toLocaleString()} sq ft
                    </div>
                  </div>
                  <div className="results-list-loc">{m.address} <span style={{ color: "var(--fg-3)" }}>· {m.neighborhood}</span></div>
                  {m.rationale && (
                    <div className="results-list-rationale">
                      <span className="results-list-rationale-label">Matched on</span>
                      <span className="results-list-rationale-text">{m.rationale}</span>
                    </div>
                  )}
                  {m.styleTags && m.styleTags.length > 0 && (
                    <div className="results-list-tags">
                      {m.styleTags.slice(0, 3).map((t) => <Chip key={t} variant="sage">{t}</Chip>)}
                    </div>
                  )}
                </div>
                <div className="results-list-cta">
                  <Icon name="arrow" size={18} />
                </div>
              </article>
            ))}
          </div>
        )}

        {view === "map" && (
          <div className="results-map">
            <LeafletMatchMap listings={window.MATCHES} onOpenListing={onOpenListing} />
            <div className="results-map-legend hm-mono">
              <span className="results-map-dot" /> Match score · click a pin to open · Paradise Valley + Scottsdale
            </div>
          </div>
        )}

        <div className="results-nextbeat">
          <div className="results-nextbeat-copy">
            <Eyebrow>Keep refining</Eyebrow>
            <h2 className="results-nextbeat-title">
              Want <span className="hm-italic-accent">more like</span> one of these?
            </h2>
            <p className="results-nextbeat-sub">
              Tap any home above — we'll generate a fresh set matched to that one specifically.
            </p>
          </div>
          <div className="results-nextbeat-actions">
            <Button variant="secondary" icon="sparkle" onClick={() => flashToast("Search saved to your shortlist.")}>Save this search</Button>
            <Button variant="secondary" icon="share" onClick={() => flashToast("Sent to your agent.")}>Send to my agent</Button>
          </div>
        </div>
      </main>

      {filterOpen && (
        <FilterPanel
          onClose={() => setFilterOpen(false)}
          onApply={() => { setFilterOpen(false); flashToast("Filters applied."); }}
        />
      )}

      {toast && (
        <div className="results-toast">
          <Icon name="check" size={14} />
          {toast}
        </div>
      )}
    </div>
  );
}

function FilterPanel({ onClose, onApply }) {
  const [price, setPrice] = React.useState([2, 6]); // $M
  const [beds, setBeds] = React.useState(4);
  const [styles, setStyles] = React.useState(["Desert Modern", "Organic Minimal"]);
  const toggleStyle = (s) =>
    setStyles((prev) => prev.includes(s) ? prev.filter((x) => x !== s) : [...prev, s]);

  const styleOptions = ["Desert Modern", "Organic Minimal", "Warm Minimal", "Japandi", "Coastal Mediterranean", "Tuscan", "Modern Hacienda", "Soft Brutalist"];

  return (
    <>
      <div className="filter-scrim" onClick={onClose} />
      <aside className="filter-panel" role="dialog" aria-label="Filter matches">
        <header className="filter-panel-head">
          <div>
            <Eyebrow>Refine</Eyebrow>
            <h2 className="filter-panel-title">Filter matches</h2>
          </div>
          <button className="filter-panel-close" onClick={onClose} aria-label="Close">
            <Icon name="close" size={16} />
          </button>
        </header>

        <section className="filter-section">
          <div className="filter-label">Price</div>
          <div className="filter-range">
            <div className="filter-range-bar">
              <span className="filter-range-fill" style={{ left: `${(price[0] / 10) * 100}%`, right: `${100 - (price[1] / 10) * 100}%` }} />
            </div>
            <div className="filter-range-vals">
              <input
                type="number"
                value={price[0]}
                step="0.1"
                min="0"
                max={price[1]}
                onChange={(e) => setPrice([Math.min(+e.target.value, price[1]), price[1]])}
              />
              <span>to</span>
              <input
                type="number"
                value={price[1]}
                step="0.1"
                min={price[0]}
                max="20"
                onChange={(e) => setPrice([price[0], Math.max(+e.target.value, price[0])])}
              />
              <span className="hm-mono">$M</span>
            </div>
          </div>
        </section>

        <section className="filter-section">
          <div className="filter-label">Bedrooms (minimum)</div>
          <div className="filter-beds">
            {[2, 3, 4, 5, 6].map((n) => (
              <button
                key={n}
                className={`filter-bed-btn ${beds === n ? "is-active" : ""}`}
                onClick={() => setBeds(n)}
              >
                {n}+
              </button>
            ))}
          </div>
        </section>

        <section className="filter-section">
          <div className="filter-label">Style</div>
          <div className="filter-styles">
            {styleOptions.map((s) => (
              <button
                key={s}
                className={`filter-style-chip ${styles.includes(s) ? "is-active" : ""}`}
                onClick={() => toggleStyle(s)}
              >
                {s}
              </button>
            ))}
          </div>
        </section>

        <footer className="filter-panel-foot">
          <button className="filter-clear" onClick={() => { setPrice([0, 20]); setBeds(2); setStyles([]); }}>
            Clear all
          </button>
          <Button onClick={onApply}>Apply filters</Button>
        </footer>
      </aside>
    </>
  );
}

// --- Leaflet map (adapted from cult-ops LeafletRouteMap) ---
// Uses the same lifecycle pattern: ref-based instance, divIcon markers,
// fitBounds to the listings. CartoDB Positron tiles match the pearl system.
function LeafletMatchMap({ listings, onOpenListing }) {
  const containerRef = React.useRef(null);
  const mapRef = React.useRef(null);
  const markersRef = React.useRef([]);
  const openRef = React.useRef(onOpenListing);

  // Keep the click handler fresh without re-initializing the map.
  React.useEffect(() => {
    openRef.current = onOpenListing;
  }, [onOpenListing]);

  // Map instance lifecycle.
  React.useEffect(() => {
    if (!window.L || !containerRef.current || mapRef.current) return;
    const L = window.L;

    const map = L.map(containerRef.current, {
      zoomControl: true,
      attributionControl: true,
      scrollWheelZoom: false,
      preferCanvas: true,
    });
    mapRef.current = map;

    // CartoDB Voyager — warm neutrals, visible roads + park greens + water blue.
    // Closer match to Compass / Google Maps aesthetic than pure Positron.
    L.tileLayer("https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png", {
      attribution: '© <a href="https://openstreetmap.org">OpenStreetMap</a> · © <a href="https://carto.com">CARTO</a>',
      maxZoom: 19,
      subdomains: "abcd",
    }).addTo(map);

    return () => {
      map.remove();
      mapRef.current = null;
      markersRef.current = [];
    };
  }, []);

  // Markers + fit-to-bounds.
  React.useEffect(() => {
    const map = mapRef.current;
    if (!map || !window.L) return;
    const L = window.L;

    markersRef.current.forEach((m) => m.remove());
    markersRef.current = [];

    // Parse a price string like "$4,850,000" -> "$4.85M"
    const compactPrice = (raw) => {
      const num = Number(String(raw).replace(/[^\d.]/g, ""));
      if (!isFinite(num) || num === 0) return raw;
      if (num >= 1e6) {
        const m = num / 1e6;
        return "$" + (m >= 10 ? m.toFixed(1) : m.toFixed(2)) + "M";
      }
      if (num >= 1e3) return "$" + Math.round(num / 1e3) + "K";
      return "$" + num;
    };

    const points = [];
    listings.forEach((listing) => {
      if (typeof listing.lat !== "number" || typeof listing.lng !== "number") return;
      const pct = Math.round((listing.sim || 0) * 100);
      const label = compactPrice(listing.price);

      // Approximate pill width by character count so anchor lands on the tail.
      const width = Math.max(56, 14 + label.length * 8);

      const icon = L.divIcon({
        html: `<div class="hm-map-pill" style="--pill-w:${width}px"><span class="hm-map-pill-label">${label}</span><span class="hm-map-pill-match">${pct}</span></div>`,
        className: "hm-map-pill-icon",
        iconSize: [width, 34],
        iconAnchor: [width / 2, 34],
      });

      const marker = L.marker([listing.lat, listing.lng], { icon, riseOnHover: true });
      marker.bindTooltip(
        `<strong>${listing.price}</strong><br>${listing.address}<br><span class="hm-map-tooltip-hood">${listing.neighborhood} · ${pct}% match</span>`,
        { direction: "top", offset: [0, -34], className: "hm-map-tooltip", opacity: 1 }
      );
      marker.on("click", () => openRef.current && openRef.current(listing));
      marker.addTo(map);
      markersRef.current.push(marker);
      points.push([listing.lat, listing.lng]);
    });

    if (points.length > 0) {
      map.fitBounds(points, { padding: [60, 60], maxZoom: 13 });
    }
  }, [listings]);

  return <div ref={containerRef} className="results-map-canvas" />;
}

Object.assign(window, { ScreenResults });
