/* global React, HP, L */
const { Tag, Spark, RiskRing, AppBar, Icon, BUILDING } = HP;

// ── Leaflet mini-map for preview ─────────────────────────────
const PREV_MAP_LAT = 40.596783;
const PREV_MAP_LNG = -73.998787;
const PREV_MAP_BIN = String(BUILDING.bin);
const PREV_BLUE    = "#0B4FA6";

const prevCentroid = (ring) => {
  const n = ring.length;
  return [ring.reduce((s, p) => s + p[0], 0) / n, ring.reduce((s, p) => s + p[1], 0) / n];
};

// Point-in-polygon (ray casting) — ring = [[lat,lng],...]
const prevPip = (lat, lng, ring) => {
  let inside = false;
  for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
    const [latI, lngI] = ring[i], [latJ, lngJ] = ring[j];
    if ((lngI > lng) !== (lngJ > lng) &&
        lat < (latJ - latI) * (lng - lngI) / (lngJ - lngI) + latI)
      inside = !inside;
  }
  return inside;
};

const prevPickTarget = (ways, lat, lng, bin) => {
  const byBin = ways.find(w => w.tags?.["nycdoitt:bin"] === bin);
  if (byBin) return byBin;
  const byPip = ways.find(w => prevPip(lat, lng, w.geometry.map(n => [n.lat, n.lon])));
  if (byPip) return byPip;
  let best = null, bestD = Infinity;
  for (const w of ways) {
    const [clat, clng] = prevCentroid(w.geometry.map(n => [n.lat, n.lon]));
    const d = (clat - lat) ** 2 + (clng - lng) ** 2;
    if (d < bestD) { bestD = d; best = w; }
  }
  return best;
};

const PreviewMap = () => {
  const containerRef = React.useRef(null);
  const mapRef       = React.useRef(null);

  React.useEffect(() => {
    if (!containerRef.current || !window.L) return;
    if (mapRef.current) return;

    const map = L.map(containerRef.current, {
      center: [PREV_MAP_LAT, PREV_MAP_LNG],
      zoom: 18,
      zoomControl: false,
      scrollWheelZoom: false,
      dragging: false,
      doubleClickZoom: false,
      touchZoom: false,
    });
    mapRef.current = map;

    L.tileLayer("https://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}{r}.png",
      { subdomains: "abcd", maxZoom: 21, attribution: "© OpenStreetMap © CartoDB" }).addTo(map);
    L.tileLayer("https://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}{r}.png",
      { subdomains: "abcd", maxZoom: 21, pane: "shadowPane" }).addTo(map);

    // Tighter radius (80m) + point-in-polygon selection
    const q = `[out:json];way(around:80,${PREV_MAP_LAT},${PREV_MAP_LNG})["building"];out geom tags;`;
    fetch("https://overpass-api.de/api/interpreter?data=" + encodeURIComponent(q))
      .then(r => r.json())
      .then(data => {
        const ways = (data.elements || []).filter(w => w.geometry?.length > 2);
        if (!ways.length) return;

        const target = prevPickTarget(ways, PREV_MAP_LAT, PREV_MAP_LNG, PREV_MAP_BIN);

        ways.forEach(w => {
          const ring  = w.geometry.map(n => [n.lat, n.lon]);
          const isSel = w === target;
          L.polygon(ring, {
            color:       isSel ? PREV_BLUE : "#7A9BBF",
            weight:      isSel ? 2.5       : 1,
            fillColor:   isSel ? PREV_BLUE : "#7A9BBF",
            fillOpacity: isSel ? 0.18      : 0.06,
          }).addTo(map);
        });

        if (target) {
          const ring = target.geometry.map(n => [n.lat, n.lon]);
          try { map.fitBounds(L.polygon(ring).getBounds(), { maxZoom: 19, padding: [30, 30] }); } catch {}
          const [clat, clng] = prevCentroid(ring);
          L.marker([clat, clng], {
            icon: L.divIcon({
              className: "",
              html: `<div style="position:relative;width:20px;height:20px">
                <div style="position:absolute;inset:0;border-radius:50%;background:${PREV_BLUE};opacity:0.3"></div>
                <div style="position:absolute;inset:4px;border-radius:50%;background:${PREV_BLUE};border:2px solid #fff;box-shadow:0 2px 6px rgba(0,0,0,0.3)"></div>
              </div>`,
              iconSize: [20, 20], iconAnchor: [10, 10],
            }),
          }).addTo(map);
        }
      })
      .catch(() => {
        const w = 0.000165, h = 0.00033;
        L.polygon([
          [PREV_MAP_LAT + h * 0.8, PREV_MAP_LNG - w * 0.5],
          [PREV_MAP_LAT + h * 0.8, PREV_MAP_LNG + w * 0.5],
          [PREV_MAP_LAT + h * 0.2, PREV_MAP_LNG + w * 0.5],
          [PREV_MAP_LAT + h * 0.2, PREV_MAP_LNG - w * 0.5],
        ], { color: PREV_BLUE, weight: 2.5, fillColor: PREV_BLUE, fillOpacity: 0.18 }).addTo(map);
      });

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

  return (
    <div style={{
      background: "#FAF5EB", borderRadius: 12,
      border: "1px solid rgba(42,31,20,0.1)",
      overflow: "hidden", marginBottom: 16,
    }}>
      <div style={{
        padding: "10px 16px",
        borderBottom: "1px solid rgba(42,31,20,0.08)",
        display: "flex", justifyContent: "space-between", alignItems: "center",
      }}>
        <span style={{ fontSize: 14, fontWeight: 700, color: "#2A1F14" }}>Location</span>
        <a href="https://www.openstreetmap.org/?mlat=40.6081&mlon=-74.0023#map=18/40.6081/-74.0023"
          target="_blank" rel="noopener noreferrer"
          style={{ fontSize: 11, fontWeight: 600, color: "#C8952A", textDecoration: "none" }}>
          Open map ↗
        </a>
      </div>
      <div ref={containerRef} style={{ height: 180 }}/>
      <div style={{ padding: "8px 16px", fontSize: 11, color: "#9B7A52" }}>
        Bay Pkwy &amp; 86th St · Bensonhurst, Brooklyn NY 11214
      </div>
    </div>
  );
};

// ── iOS-style info row ────────────────────────────────────────
const InfoRow = ({ label, value, accent, mono, last }) => (
  <div style={{
    display: "flex", justifyContent: "space-between", alignItems: "center",
    padding: "11px 0",
    borderBottom: last ? "none" : "1px solid rgba(42,31,20,0.08)",
    gap: 12,
  }}>
    <span style={{ fontSize: 14, color: "#6B5B45", flexShrink: 0 }}>{label}</span>
    <span style={{
      fontSize: 14, fontWeight: 600, color: accent ? "#C8952A" : "#2A1F14",
      fontFamily: mono ? "JetBrains Mono, monospace" : "inherit",
      textAlign: "right",
    }}>{value}</span>
  </div>
);

// ── Risk badge — mirrors backend crs scoring ─────────────────
// Backend: score = clamp(100 - crs_score, 0, 100)
// Thresholds on displayed score: >=81 critical, >=61 high, >=31 medium, else low
const RiskBadge = ({ score }) => {
  const tone = score >= 81 ? { lbl: "CRITICAL", bg: "rgba(110,19,19,0.12)",  fg: "#6E1313" }
             : score >= 61 ? { lbl: "HIGH",     bg: "rgba(181,38,27,0.12)",  fg: "#B5261B" }
             : score >= 31 ? { lbl: "MEDIUM",   bg: "rgba(156,116,0,0.12)",  fg: "#9C7400" }
             :                { lbl: "LOW",      bg: "rgba(31,138,76,0.12)",  fg: "#1F8A4C" };
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 5,
      padding: "4px 10px", borderRadius: 999,
      background: tone.bg, color: tone.fg,
      fontSize: 11, fontWeight: 800, letterSpacing: "0.07em",
    }}>
      <span style={{ width: 6, height: 6, borderRadius: "50%", background: tone.fg }}/>
      {tone.lbl}
    </span>
  );
};

// ── KPI chip (iOS-style, no chart) ──────────────────────────
const KpiChip = ({ label, value, sub, color }) => (
  <div style={{
    background: "#FAF5EB", borderRadius: 12,
    border: "1px solid rgba(42,31,20,0.1)",
    padding: "14px 16px",
    display: "flex", flexDirection: "column", gap: 6,
  }}>
    <span style={{
      fontSize: 10, color: "#6B5B45", fontWeight: 700,
      letterSpacing: "0.07em", textTransform: "uppercase",
      fontFamily: "JetBrains Mono, monospace",
    }}>{label}</span>
    <div style={{
      fontSize: 28, fontWeight: 800, color: color || "#2A1F14",
      letterSpacing: "-0.02em", lineHeight: 1,
    }}>{value}</div>
    {sub && <span style={{ fontSize: 12, color: "#9B7A52" }}>{sub}</span>}
  </div>
);

// ── Blurred locked section ghost ──────────────────────────────
const LockedGhost = () => (
  <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
    {[
      { label: "Ownership & Liens",    rows: ["Entity: 8855 Bay Pkwy LLC", "Owned since 2017-04-12", "Last sale $2.4M", "Liens $22,460"] },
      { label: "Violation Timeline",   rows: ["V-2025-04812 · Heat/Hot water · Open", "V-2025-04741 · Fire alarm · Open", "V-2025-04683 · Roof leak · Open", "V-2024-04612 · Handrail · Closed"] },
      { label: "Permits & Activity",   rows: ["ALT1-123456 · Interior renovation · Active", "ALT2-234567 · HVAC replacement · Closed", "NB-345678 · Fire suppression · Filed", "Inspection 2025-01-14 · Passed"] },
    ].map(({ label, rows }) => (
      <div key={label} style={{
        background: "#FAF5EB", borderRadius: 12,
        border: "1px solid rgba(42,31,20,0.1)", overflow: "hidden",
      }}>
        <div style={{ padding: "10px 16px", borderBottom: "1px solid rgba(42,31,20,0.08)",
          fontSize: 11, fontWeight: 700, color: "#6B5B45", letterSpacing: "0.05em", textTransform: "uppercase" }}>
          {label}
        </div>
        <div style={{ padding: "0 16px" }}>
          {rows.map((r, i) => (
            <div key={i} style={{
              padding: "10px 0",
              borderBottom: i < rows.length - 1 ? "1px solid rgba(42,31,20,0.06)" : "none",
              fontSize: 13, color: "#4A3520",
            }}>{r}</div>
          ))}
        </div>
      </div>
    ))}
  </div>
);

// ── Preview screen (iOS-parity) ───────────────────────────────
const Preview = ({ query, onQuery, onSearch, onUnlock, onHome, onMap, onDashboard, onSaved, loading }) => {
  const kpis = [
    {
      label: "Open Violations",
      value: BUILDING.violationsOpen,
      sub: BUILDING.violationsOpen === 0 ? "No open violations" : "active",
      color: BUILDING.violationsOpen > 0 ? "#B5261B" : "#2A1F14",
    },
    {
      label: "Zoning FAR",
      value: BUILDING.far || "—",
      sub: BUILDING.farMax ? `Max ${BUILDING.farMax}` : "",
      color: "#0B4FA6",
    },
    {
      label: "Lot Area",
      value: BUILDING.lotArea ? BUILDING.lotArea.toLocaleString() : "—",
      sub: "sq ft",
      color: "#2A1F14",
    },
    {
      label: "Building Area",
      value: BUILDING.buildingArea ? BUILDING.buildingArea.toLocaleString() : "—",
      sub: "sq ft",
      color: "#2A1F14",
    },
  ];

  return (
    <div style={{ minHeight: "100vh", background: "#EDE4D0" }} className="screen-enter">
      <AppBar query={query} onQuery={onQuery} onSearch={onSearch} onHome={onHome}
              onMap={onMap} onDashboard={onDashboard} onSaved={onSaved}/>

      {/* ── Art hero — building asset ─── */}
      <div style={{
        position: "relative", paddingTop: 72, overflow: "hidden",
        background: "#2A1F14", minHeight: 220,
        display: "flex", alignItems: "flex-end",
      }}>
        <div style={{
          position: "absolute", inset: 0,
          backgroundImage: "url(assets/building.jpeg)",
          backgroundSize: "cover", backgroundPosition: "center 40%",
          opacity: 0.32,
        }}/>
        <div style={{
          position: "absolute", inset: 0,
          background: "linear-gradient(180deg, rgba(42,31,20,0.3) 0%, rgba(42,31,20,0.75) 70%, #EDE4D0 100%)",
        }}/>
        <div style={{ position: "relative", zIndex: 1, padding: "0 32px 28px", maxWidth: 760, margin: "0 auto", width: "100%" }}>
          <div style={{
            fontFamily: "var(--hp-font-mono)", fontSize: 12, fontWeight: 600,
            letterSpacing: "0.1em", textTransform: "uppercase",
            color: "rgba(200,149,42,0.9)", marginBottom: 10,
          }}>
            BIN {BUILDING.bin} · BBL {BUILDING.bbl}
          </div>
          {loading
            ? <div className="skel" style={{ width: 280, height: 40, marginBottom: 8 }}/>
            : <h1 style={{
                fontFamily: "var(--hp-font-serif)",
                fontSize: "clamp(32px, 5vw, 60px)", fontWeight: 400, fontStyle: "italic",
                letterSpacing: "-0.02em", lineHeight: 0.95,
                color: "#FAF5EB", margin: "0 0 10px",
              }}>
                {query || BUILDING.address} {BUILDING.subline}
              </h1>}
          <div style={{ fontSize: 14, color: "rgba(237,228,208,0.7)" }}>
            {BUILDING.stories ? `${BUILDING.stories}-story · ` : ""}{BUILDING.units} units · Built {BUILDING.year}
          </div>
        </div>
      </div>

      <div style={{ maxWidth: 760, margin: "0 auto", padding: "24px 16px 120px" }}>

        {/* ── Composite Risk + Zoning ─── */}
        <div style={{
          background: "#FAF5EB", borderRadius: 14,
          border: "1px solid rgba(42,31,20,0.1)",
          padding: "16px",
          display: "flex", alignItems: "center", gap: 12,
          marginBottom: 12,
        }}>
          {/* Ring + score */}
          <div style={{ display: "flex", alignItems: "center", gap: 12, flex: 1 }}>
            <RiskRing score={100 - BUILDING.riskScore} size={56}
              color={BUILDING.riskScore >= 81 ? "#6E1313" : BUILDING.riskScore >= 61 ? "#B5261B" : BUILDING.riskScore >= 31 ? "#9C7400" : "#1F8A4C"}/>
            <div>
              <div style={{
                fontSize: 10, fontWeight: 700, color: "#6B5B45",
                letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 4,
                fontFamily: "JetBrains Mono, monospace",
              }}>Composite Risk</div>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{
                  fontSize: 24, fontWeight: 800, color: "#2A1F14",
                  letterSpacing: "-0.02em", lineHeight: 1,
                }}>{100 - BUILDING.riskScore}/100</span>
                <RiskBadge score={BUILDING.riskScore}/>
              </div>
            </div>
          </div>
          {/* Zoning badge */}
          <div style={{
            background: "rgba(200,149,42,0.08)", border: "1px solid rgba(200,149,42,0.25)",
            borderRadius: 10, padding: "10px 14px", textAlign: "center", flexShrink: 0,
          }}>
            <div style={{
              fontSize: 22, fontWeight: 800, color: "#C8952A",
              letterSpacing: "-0.01em", lineHeight: 1, marginBottom: 2,
            }}>{BUILDING.zoning || "R6"}</div>
            <div style={{ fontSize: 11, color: "#7A5C3A", whiteSpace: "nowrap" }}>
              {BUILDING.zoningDesc || "Mid-density residential"}
            </div>
          </div>
        </div>

        {/* ── KPI grid 2×2 (no charts) ─── */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 12 }}>
          {kpis.map((k) => (
            <KpiChip key={k.label} {...k}/>
          ))}
        </div>

        {/* ── Zoning info list ─── */}
        <div style={{
          background: "#FAF5EB", borderRadius: 12,
          border: "1px solid rgba(42,31,20,0.1)",
          overflow: "hidden", marginBottom: 16,
        }}>
          <div style={{
            padding: "10px 16px",
            borderBottom: "1px solid rgba(42,31,20,0.08)",
            display: "flex", justifyContent: "space-between", alignItems: "center",
          }}>
            <span style={{ fontSize: 14, fontWeight: 700, color: "#2A1F14" }}>Zoning District</span>
            <span style={{
              fontSize: 10, fontWeight: 700, color: "#9B7A52",
              letterSpacing: "0.07em", textTransform: "uppercase",
              fontFamily: "JetBrains Mono, monospace",
            }}>MAPPLUTO</span>
          </div>
          <div style={{ padding: "0 16px" }}>
            <InfoRow label="District"    value={`${BUILDING.zoning || "R6"} – ${BUILDING.zoningDesc || "Mid-density residential"}`} mono/>
            <InfoRow label="FAR (built)" value={String(BUILDING.far || "—")} mono last/>
          </div>
        </div>

        {/* ── Location map ─── */}
        <PreviewMap/>

        {/* ── Locked zone ─── */}
        <div style={{ position: "relative" }}>
          {/* Blurred ghost content */}
          <div style={{ filter: "blur(5px) saturate(0.7)", pointerEvents: "none",
            userSelect: "none", opacity: 0.6 }}>
            <LockedGhost/>
          </div>

          {/* Fade overlay */}
          <div style={{
            position: "absolute", top: 0, left: 0, right: 0, height: 80,
            background: "linear-gradient(180deg, #EDE4D0 0%, transparent 100%)",
            pointerEvents: "none",
          }}/>

          {/* Gold unlock CTA (iOS-style) */}
          <div style={{
            position: "absolute", left: "50%", top: 40,
            transform: "translateX(-50%)",
            width: "min(440px, calc(100% - 32px))",
            display: "flex", flexDirection: "column", alignItems: "stretch", gap: 8,
          }}>
            <button onClick={onUnlock} style={{
              width: "100%", padding: "15px 20px",
              background: "#C8952A", color: "#FFFFFF",
              border: "none", borderRadius: 12,
              fontSize: 15, fontWeight: 700,
              cursor: "pointer", letterSpacing: "0.01em",
              display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
              boxShadow: "0 4px 20px rgba(200,149,42,0.4)",
            }}>
              Unlock full report →
            </button>
            <div style={{ textAlign: "center", fontSize: 12, color: "#9B7A52" }}>
              3-day free trial · $4.99/mo after · Cancel anytime
            </div>
          </div>
        </div>

      </div>
    </div>
  );
};

window.Preview = Preview;
