// Interactive Riyadh map page — the centerpiece
const MapPage = ({ t, lang, selectedParcel, setSelectedParcel, setPage, setPreselectedServices }) => {
  const data = window.DAOOB_DATA;
  const [tool, setTool] = React.useState("pin"); // pin | draw | upload | clear
  const [basemap, setBasemap] = React.useState("street");
  const [search, setSearch] = React.useState("");
  const [filterZones, setFilterZones] = React.useState([]);
  const [heatmap, setHeatmap] = React.useState(true);
  const [layers, setLayers] = React.useState({ zoning: true, traffic: false, amenities: false, planning: false });

  const toggleZone = (key) => {
    setFilterZones(prev => prev.includes(key) ? prev.filter(z => z !== key) : [...prev, key]);
  };
  const toggleLayer = (key) => setLayers(l => ({ ...l, [key]: !l[key] }));

  const sel = data.parcels.find(p => p.id === selectedParcel);
  const visible = filterZones.length ? data.parcels.filter(p => filterZones.includes(p.zone)) : data.parcels;

  return (
    <div className="map-page">
      {/* Left: tools */}
      <aside className="map-side">
        <div className="map-side-h">
          <h3>{t.map.title}</h3>
          <p>{t.map.results_count.replace("{n}", visible.length)}</p>
        </div>

        <div className="map-search">
          <Icon name="search" size={14}/>
          <input
            placeholder={t.map.search_ph}
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
        </div>

        <div style={{ padding: "0 20px 8px", fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--ink-400)", fontWeight: 500 }}>
          {lang === "ar" ? "أدوات الاختيار" : "Selection tools"}
        </div>
        <div className="map-tools">
          {[
            { id: "pin",    icon: "pin",    lbl: t.map.tools.pin },
            { id: "draw",   icon: "draw",   lbl: t.map.tools.draw },
            { id: "upload", icon: "upload", lbl: t.map.tools.upload },
            { id: "clear",  icon: "clear",  lbl: t.map.tools.clear },
          ].map(x => (
            <div
              key={x.id}
              className={"map-tool" + (tool === x.id ? " active" : "")}
              onClick={() => {
                setTool(x.id);
                if (x.id === "clear") setSelectedParcel(null);
              }}
            >
              <Icon name={x.icon} size={14}/> {x.lbl}
            </div>
          ))}
        </div>

        <hr className="hr"/>

        <div style={{ padding: "16px 20px 8px", fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--ink-400)", fontWeight: 500 }}>
          {t.map.basemap}
        </div>
        <div className="basemap-pills">
          {["dark","street","satellite"].map(b => (
            <div key={b} className={"basemap-pill" + (basemap === b ? " active" : "")} onClick={() => setBasemap(b)}>
              {b === "dark" ? (lang === "ar" ? "داكن" : "Dark") : t.map[`basemap_${b}`]}
            </div>
          ))}
        </div>

        <div style={{ padding: "8px 20px 8px", fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--ink-400)", fontWeight: 500 }}>
          {t.map.layers}
        </div>
        <div className="map-toggles">
          {[
            { k: "zoning",     lbl: t.map.layer_zoning },
            { k: "traffic",    lbl: t.map.layer_traffic },
            { k: "amenities",  lbl: t.map.layer_amenities },
            { k: "planning",   lbl: t.map.layer_planning },
          ].map(x => (
            <div className="map-toggle" key={x.k}>
              <span>{x.lbl}</span>
              <span className={"sw" + (layers[x.k] ? " on" : "")} onClick={() => toggleLayer(x.k)}/>
            </div>
          ))}
        </div>

        <hr className="hr"/>

        <div style={{ padding: "16px 20px 8px", fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--ink-400)", fontWeight: 500 }}>
          {t.map.filter_h}
        </div>
        <div style={{ padding: "0 20px 24px", display: "flex", flexDirection: "column", gap: 8 }}>
          {Object.entries(data.zoningTypes).map(([k, z]) => (
            <label key={k} style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 13, cursor: "pointer", color: "var(--ink-700)" }}>
              <span style={{ width: 14, height: 14, borderRadius: 3, background: z.color, opacity: filterZones.length === 0 || filterZones.includes(k) ? 1 : 0.25 }}/>
              <input
                type="checkbox"
                checked={filterZones.length === 0 || filterZones.includes(k)}
                onChange={() => {
                  if (filterZones.length === 0) setFilterZones(Object.keys(data.zoningTypes).filter(x => x !== k));
                  else toggleZone(k);
                }}
                style={{ accentColor: "var(--green-700)" }}
              />
              {t.map[`legend_${k === "industrial" ? "industrial" : k === "govt" ? "govt" : k}`] || z[lang]}
            </label>
          ))}
        </div>
      </aside>

      {/* Center: map */}
      <div style={{ position: "relative", height: "100%", minHeight: 0 }}>
        <LeafletMap
          parcels={data.parcels}
          zoning={data.zoningTypes}
          districts={data.districts}
          selectedId={selectedParcel}
          onSelect={setSelectedParcel}
          basemap={basemap}
          filterZones={filterZones.length ? filterZones : null}
          lang={lang}
          heatmap={heatmap}
          onMapClick={(latlng, nearestId) => {
            // Drop a pin anywhere → snap to nearest parcel within range
            if (nearestId) setSelectedParcel(nearestId);
          }}
        />
        {/* Heatmap toggle */}
        <button
          className={"heatmap-toggle" + (heatmap ? " on" : "")}
          onClick={() => setHeatmap(h => !h)}
        >
          <Icon name="layers" size={12}/> {lang === "ar" ? "خريطة الأسعار" : "Price heatmap"}
        </button>

        {/* Legend overlay */}
        <div className="map-legend">
          <h6>{t.map.legend}</h6>
          <ul>
            {[
              { k: "mixed", lbl: t.map.legend_mixed },
              { k: "commercial", lbl: t.map.legend_commercial },
              { k: "residential", lbl: t.map.legend_residential },
              { k: "industrial", lbl: t.map.legend_industrial },
              { k: "govt", lbl: t.map.legend_govt },
            ].map(x => (
              <li key={x.k}>
                <span className="legend-swatch" style={{ background: data.zoningTypes[x.k].color }}/>
                {x.lbl}
              </li>
            ))}
          </ul>
        </div>
      </div>

      {/* Right: detail panel */}
      <aside className="map-side right">
        {sel ? <ParcelDetail sel={sel} t={t} lang={lang} data={data} setPage={setPage} setPreselectedServices={setPreselectedServices}/> : <ParcelEmpty t={t}/>}
      </aside>
    </div>
  );
};

const ParcelEmpty = ({ t }) => (
  <div className="parcel-empty">
    <Icon name="pin" size={36} stroke={1.2}/>
    <h4>{t.map.no_select_t}</h4>
    <p>{t.map.no_select_d}</p>
  </div>
);

const ParcelDetail = ({ sel, t, lang, data, setPage, setPreselectedServices }) => {
  const zone = data.zoningTypes[sel.zone];
  const district = data.districts[sel.district];
  const askPrice = sel.price ? `${(sel.price * sel.area / 1000).toFixed(1)}M ${t.map.sar}` : "—";

  // 12-month price trend percentage change
  const trend = sel.priceTrend;
  const trendPct = trend ? Math.round(((trend[trend.length - 1] - trend[0]) / trend[0]) * 100) : null;

  // Format last transaction date
  const fmtDate = (d) => {
    if (!d) return null;
    const dt = new Date(d);
    return dt.toLocaleDateString(lang === "ar" ? "ar-SA" : "en-GB", { day: "numeric", month: "short", year: "numeric" });
  };

  return (
    <div className="parcel-detail">
      {/* Header */}
      <div className="pd-header">
        <div className="ref">{t.map.parcel} · {sel.id}</div>
        <h3>{district[lang]}</h3>
        <div className="dist">{zone[lang]} · {(lang === "ar" ? "ملكية " : "Ownership: ") + (sel.owner === "Govt." ? (lang === "ar" ? "حكومية" : "Govt.") : (lang === "ar" ? "خاصة" : "Private"))}</div>
      </div>

      {/* Price headline */}
      {sel.price && (
        <div className="pd-price-headline">
          <div className="pd-ph-main">
            <span className="pd-ph-val t-num">{askPrice}</span>
            <span className="pd-ph-per t-num">{sel.price.toLocaleString()} {lang === "ar" ? "ر.س/م²" : "SAR/m²"}</span>
          </div>
          {trendPct !== null && (
            <div className={"pd-ph-trend " + (trendPct >= 0 ? "up" : "down")}>
              <span>{trendPct >= 0 ? "↑" : "↓"} {Math.abs(trendPct)}%</span>
              <span className="pd-ph-trend-l">{lang === "ar" ? "آخر 12 شهر" : "12 mo."}</span>
            </div>
          )}
        </div>
      )}

      {/* 12-month price trend sparkline */}
      {trend && <PriceSpark trend={trend} lang={lang}/>}

      {/* Quick facts grid */}
      <div className="pd-grid">
        <div><div className="k">{t.map.area}</div><div className="v t-num">{sel.area.toLocaleString()}<small> {t.map.sqm}</small></div></div>
        <div><div className="k">{lang === "ar" ? "التصنيف" : "Zoning"}</div><div className="v">{zone[lang]}</div></div>
        {sel.frontages && <div><div className="k">{lang === "ar" ? "الواجهات" : "Frontages"}</div><div className="v t-num">{sel.frontages}</div></div>}
        {sel.width && <div><div className="k">{lang === "ar" ? "العرض × العمق" : "W × D"}</div><div className="v t-num">{sel.width} × {sel.depth} m</div></div>}
        {sel.metro && <div style={{ gridColumn: "span 2" }}><div className="k">{lang === "ar" ? "أقرب محطة مترو" : "Nearest metro"}</div><div className="v">{sel.metro.station} ({sel.metro.line}) · <span className="t-num">{sel.metro.distance_m}m</span></div></div>}
      </div>

      {/* Building regulations */}
      {sel.restrictions && (
        <div className="pd-block">
          <div className="pd-block-h">{lang === "ar" ? "اشتراطات البناء" : "Building regulations"}</div>
          <div className="pd-regs">
            <div><span className="rk">FAR</span><span className="rv t-num">{sel.restrictions.far}</span></div>
            <div><span className="rk">{lang === "ar" ? "نسبة البناء" : "Coverage"}</span><span className="rv t-num">{Math.round(sel.restrictions.coverage * 100)}%</span></div>
            <div><span className="rk">{lang === "ar" ? "ارتفاع أقصى" : "Max height"}</span><span className="rv t-num">{sel.restrictions.height}m</span></div>
            <div><span className="rk">{lang === "ar" ? "الارتداد" : "Setback"}</span><span className="rv t-num">{sel.restrictions.setback}m</span></div>
          </div>
        </div>
      )}

      {/* Utilities */}
      {sel.utilities && (
        <div className="pd-block">
          <div className="pd-block-h">{lang === "ar" ? "البنية التحتية" : "Utilities"}</div>
          <div className="pd-utils">
            {Object.entries({
              water:       lang === "ar" ? "ماء" : "Water",
              sewage:      lang === "ar" ? "صرف" : "Sewage",
              electricity: lang === "ar" ? "كهرباء" : "Electricity",
              gas:         lang === "ar" ? "غاز" : "Gas",
              fiber:       lang === "ar" ? "ألياف" : "Fiber",
            }).map(([k, lbl]) => (
              <div key={k} className={"pd-util " + (sel.utilities[k] ? "on" : "off")}>
                <span className="pd-util-d">{sel.utilities[k] ? "✓" : "—"}</span>
                <span>{lbl}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Last transaction */}
      {sel.lastTx && (
        <div className="pd-block">
          <div className="pd-block-h">{lang === "ar" ? "آخر معاملة" : "Last transaction"}</div>
          <div className="pd-lastx">
            <div className="pd-lastx-row">
              <span className="k">{lang === "ar" ? "القيمة" : "Value"}</span>
              <span className="v t-num">{(sel.lastTx.price / 1_000_000).toFixed(1)}M <small>{lang === "ar" ? "ر.س" : "SAR"}</small></span>
            </div>
            <div className="pd-lastx-row">
              <span className="k">{lang === "ar" ? "التاريخ" : "Date"}</span>
              <span className="v">{fmtDate(sel.lastTx.date)}</span>
            </div>
            {sel.compsCount > 0 && (
              <div className="pd-lastx-row">
                <span className="k">{lang === "ar" ? "معاملات مشابهة" : "Comparable txns"}</span>
                <span className="v t-num">{sel.compsCount} <small>{lang === "ar" ? "آخر 12 شهر" : "last 12mo"}</small></span>
              </div>
            )}
          </div>
        </div>
      )}

      {/* AI Score */}
      {sel.score && (
        <div className="parcel-score">
          <div className="score-ring" style={{ "--p": sel.score }}>
            <div className="score-ring-inner t-num">{sel.score}</div>
          </div>
          <div>
            <div className="t">{t.map.ai_score}</div>
            <div className="v">{sel.score >= 75 ? (lang === "ar" ? "ممتاز" : "Excellent") : sel.score >= 60 ? (lang === "ar" ? "جيد" : "Strong") : (lang === "ar" ? "متوسط" : "Moderate")}</div>
          </div>
        </div>
      )}

      <div className="ai-summary">
        <span className="lbl">{t.map.ai_summary}</span>
        {t.map.ai_summary_body}
      </div>

      {/* Services — pick one to request */}
      <div className="parcel-services">
        <div className="parcel-services-h">
          <span className="lbl">{lang === "ar" ? "اختر دراسة لهذه القطعة" : "Choose a study for this parcel"}</span>
          <span className="cnt">{t.services.list.length} {lang === "ar" ? "خدمات" : "services"}</span>
        </div>
        <div className="service-rows">
          {t.services.list.map((s, i) => (
            <button
              key={i}
              className="service-row"
              onClick={() => { setPreselectedServices([i]); setPage("request"); }}
            >
              <div className="num t-mono">{String(i + 1).padStart(2, "0")}</div>
              <div className="body">
                <div className="t">{s.t}</div>
                <div className="service-row-prices">
                  <span className="srp-ai">{(s.daoob || 500).toLocaleString()} {lang === "ar" ? "ر.س" : "SAR"} · {t.services.compare.ai_lead}</span>
                  <span className="srp-office">{s.price}</span>
                </div>
              </div>
              <div className="chev"><Icon name="arrow-right" size={14}/></div>
            </button>
          ))}
        </div>
      </div>

      <div className="parcel-actions">
        <button
          className="btn btn-primary"
          onClick={() => { setPreselectedServices(null); setPage("request"); }}
        >
          {lang === "ar" ? "اطلب باقة كاملة" : "Request bundled study"} <Icon name="arrow-right" size={14}/>
        </button>
        <button className="btn btn-outline">{t.map.add_to_compare}</button>
      </div>
    </div>
  );
};

// 12-month price trend sparkline
const PriceSpark = ({ trend, lang }) => {
  const W = 280, H = 50, pad = 4;
  const min = Math.min(...trend);
  const max = Math.max(...trend);
  const sx = (i) => pad + (i / (trend.length - 1)) * (W - pad * 2);
  const sy = (v) => H - pad - ((v - min) / (max - min || 1)) * (H - pad * 2);
  const d = trend.map((v, i) => `${i === 0 ? "M" : "L"} ${sx(i)} ${sy(v)}`).join(" ");
  const area = d + ` L ${sx(trend.length - 1)} ${H} L ${sx(0)} ${H} Z`;
  return (
    <div className="pd-spark">
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} preserveAspectRatio="none">
        <defs>
          <linearGradient id="spark-grad" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%"  stopColor="var(--green-700)" stopOpacity="0.25"/>
            <stop offset="100%" stopColor="var(--green-700)" stopOpacity="0"/>
          </linearGradient>
        </defs>
        <path d={area} fill="url(#spark-grad)"/>
        <path d={d} fill="none" stroke="var(--green-700)" strokeWidth="1.6"/>
        <circle cx={sx(trend.length - 1)} cy={sy(trend[trend.length - 1])} r="3" fill="var(--gold-500)" stroke="#fff" strokeWidth="1.5"/>
      </svg>
      <div className="pd-spark-ticks">
        <span>{lang === "ar" ? "قبل 12 شهر" : "12 mo. ago"}</span>
        <span className="t-num">{trend[0]} → {trend[trend.length - 1]} <small>{lang === "ar" ? "ر.س/م²" : "SAR/m²"}</small></span>
      </div>
    </div>
  );
};

Object.assign(window, { MapPage });
