// Citizen — Marketplace / Browse + Unit Detail + Reserve

function CitizenBrowse({ t, decision, selectedUnit, setSelectedUnit, setScreen, saved, setSaved, citizen }) {
  const [filters, setFilters] = React.useState({
    governorate: "all", type: "all", priceMax: 150000, bedsMin: 0,
  });
  const [view, setView] = React.useState("grid"); // grid | map | list
  const [detailOpen, setDetailOpen] = React.useState(false);

  const units = window.OHB_DATA.units.filter((u) => {
    if (filters.governorate !== "all" && u.governorate !== filters.governorate) return false;
    if (filters.type !== "all" && u.type !== filters.type) return false;
    if (u.priceOmr > filters.priceMax) return false;
    if (u.beds < filters.bedsMin) return false;
    return true;
  });

  const unit = window.OHB_DATA.units.find((u) => u.id === selectedUnit) || units[0];

  function selectUnit(id) {
    setSelectedUnit(id);
    setDetailOpen(true);
  }

  function toggleSave(id) {
    setSaved((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  }

  return (
    <div className="browse-screen">
      {/* Header row */}
      <div className="browse-header">
        <div>
          <div className="label-eyebrow">{t("Find a home","ابحث عن منزل")}</div>
          <h2 className="h2" style={{marginTop:4}}>{t("Homes you can finance.","منازل يمكنك تمويلها.")}</h2>
        </div>
        <div className="view-toggle">
          <button className={view === "grid" ? "active" : ""} onClick={() => setView("grid")}><Icon name="grid" size={14}/></button>
          <button className={view === "list" ? "active" : ""} onClick={() => setView("list")}><Icon name="list" size={14}/></button>
          <button className={view === "map" ? "active" : ""} onClick={() => setView("map")}><Icon name="map" size={14}/></button>
        </div>
      </div>

      {/* Single-row filter bar */}
      <div className="browse-filters-bar card card-pad-sm">
        <div className="filter-search">
          <Icon name="search" size={15} style={{color:"var(--muted)"}}/>
          <input className="filter-input" placeholder={t("Search projects, areas, developers…","ابحث")}/>
        </div>
        <div className="filter-chips-inline">
          {["all","Muscat","Al Batinah North","Dhofar"].map(g => (
            <button key={g} className={`chip ${filters.governorate === g ? "active" : ""}`}
              onClick={() => setFilters({...filters, governorate:g})}>
              {g === "all" ? t("All Oman","كل عُمان") : g}
            </button>
          ))}
          <div className="filter-divider"/>
          {["all","Apartment","Townhouse","Villa"].map(ty => (
            <button key={ty} className={`chip ${filters.type === ty ? "active" : ""}`}
              onClick={() => setFilters({...filters, type:ty})}>
              {ty === "all" ? t("Any type","أي نوع") : ty}
            </button>
          ))}
          <div className="filter-divider"/>
          <div className="filter-budget-inline">
            <span className="text-12 muted">{t("Budget","الميزانية")}</span>
            <span className="text-13" style={{fontWeight:600,whiteSpace:"nowrap"}}>OMR {filters.priceMax.toLocaleString()}</span>
            <input type="range" min="30000" max="200000" step="5000" value={filters.priceMax}
              onChange={(e) => setFilters({...filters, priceMax:+e.target.value})}
              style={{width:80}}/>
          </div>
          <span className="pill copper" style={{whiteSpace:"nowrap",marginLeft:"auto"}}>
            <Icon name="zap" size={11}/> {units.length} {t("match","تطابق")}
          </span>
        </div>
      </div>

      <div className={`browse-main ${detailOpen ? "panel-open" : ""}`}>
        {view === "map"
          ? <LeafletMap units={units} selectedUnit={selectedUnit} onSelect={selectUnit} panelOpen={detailOpen}/>
          : (
            <div className={`browse-${view}`}>
              {units.map((u) => (
                <UnitCard
                  key={u.id} unit={u} t={t}
                  saved={saved.has(u.id)} onSave={() => toggleSave(u.id)}
                  selected={selectedUnit === u.id} onSelect={() => selectUnit(u.id)}
                  view={view}
                />
              ))}
            </div>
          )
        }
      </div>

      {/* Slide-in detail panel */}
      <div className={`unit-detail-overlay ${detailOpen ? "open" : ""}`}>
        <div className="unit-detail-panel">
          {unit && detailOpen && (
            <UnitDetail
              unit={unit} t={t} setScreen={setScreen} citizen={citizen}
              saved={saved.has(unit.id)} onSave={() => toggleSave(unit.id)}
              onClose={() => setDetailOpen(false)}
            />
          )}
        </div>
      </div>
      {detailOpen && <div className="unit-detail-backdrop" onClick={() => setDetailOpen(false)}/>}
    </div>
  );
}

function UnitCard({ unit, t, saved, onSave, selected, onSelect, view }) {
  return (
    <div className={`unit-card view-${view} ${selected ? "selected" : ""}`} onClick={onSelect} role="button">
      <div className="unit-card-img" style={!unit.image ? {background:`linear-gradient(135deg, ${unit.tone}, ${unit.tone}dd)`} : {}}>
        {unit.image
          ? <img src={unit.image} alt={unit.project}/>
          : <Icon name="building" size={60} style={{color:"rgba(255,255,255,0.4)", position:"relative"}}/>
        }
        <button className="unit-fav" onClick={(e) => { e.stopPropagation(); onSave(); }}>
          <Icon name="heart" size={14} stroke={2} style={{fill: saved ? "var(--brand-copper)" : "none", color: saved ? "var(--brand-copper)" : "#fff"}}/>
        </button>
        <div className="unit-pills">
          {unit.status === "available"
            ? <span className="pill ok">{t("Available","متاح")}</span>
            : <span className="pill warn">{t("Reserved","محجوز")}</span>
          }
        </div>
      </div>
      <div className="unit-card-body">
        <div className="text-12 muted">{unit.project} · {unit.developer}</div>
        <div className="unit-card-title">{unit.type} {unit.unit}</div>
        <div className="unit-card-facts">
          <span><Icon name="pin" size={12}/> {unit.wilayat}</span>
          <span><Icon name="bed" size={12}/> {unit.beds}</span>
          <span><Icon name="ruler" size={12}/> {unit.area} m²</span>
        </div>
        <div className="unit-card-foot">
          <div>
            <div className="muted text-12">{t("Price","السعر")}</div>
            <div className="unit-card-price">OMR {unit.priceOmr.toLocaleString()}</div>
          </div>
          <div className="unit-progs">
            {unit.eligible.slice(0,2).map((p) => <span key={p} className="prog-chip">{p === "iskan" ? "ISKAN" : p === "ohb-loan" ? "OHB" : "MIC"}</span>)}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Leaflet Map ─────────────────────────────────────────────────────────────
function LeafletMap({ units, selectedUnit, onSelect, panelOpen }) {
  const mapRef = React.useRef(null);
  const leafletRef = React.useRef(null);
  const markersRef = React.useRef({});

  React.useEffect(() => {
    if (!mapRef.current || leafletRef.current) return;
    const map = L.map(mapRef.current, {
      center: [23.6, 57.8],
      zoom: 7,
      zoomControl: true,
      attributionControl: true,
    });
    L.tileLayer("https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png", {
      attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> © <a href="https://carto.com/">CARTO</a>',
      subdomains: "abcd",
      maxZoom: 19,
    }).addTo(map);
    leafletRef.current = map;
    setTimeout(() => map.invalidateSize(), 100);
  }, []);

  // Resize map when panel opens/closes (after CSS transition settles)
  React.useEffect(() => {
    if (!leafletRef.current) return;
    setTimeout(() => leafletRef.current.invalidateSize(), 360);
  }, [panelOpen]);

  React.useEffect(() => {
    const map = leafletRef.current;
    if (!map) return;

    // Clear old markers
    Object.values(markersRef.current).forEach(m => m.remove());
    markersRef.current = {};

    units.forEach(u => {
      if (!u.lat || !u.lng) return;
      const sel = u.id === selectedUnit;
      const color = sel ? "#c8703a" : "#1b4149";
      const icon = L.divIcon({
        className: "",
        html: `<div style="
          width:${sel?14:10}px;height:${sel?14:10}px;
          border-radius:50%;
          background:${color};
          border:2px solid #fff;
          box-shadow:0 2px 6px rgba(0,0,0,0.3);
          cursor:pointer;
          transition:all .2s;
        "></div>`,
        iconSize: [sel?14:10, sel?14:10],
        iconAnchor: [sel?7:5, sel?7:5],
      });
      const marker = L.marker([u.lat, u.lng], { icon })
        .addTo(map)
        .bindPopup(`<strong>${u.project}</strong><br/>OMR ${u.priceOmr.toLocaleString()} · ${u.unit}`, {
          closeButton: false, maxWidth: 200,
        })
        .on("click", () => { onSelect(u.id); marker.openPopup(); });
      if (sel) marker.openPopup();
      markersRef.current[u.id] = marker;
    });
  }, [units, selectedUnit]);

  // Fly to selected unit
  React.useEffect(() => {
    const map = leafletRef.current;
    const u = units.find(u => u.id === selectedUnit);
    if (map && u?.lat && u?.lng) {
      map.flyTo([u.lat, u.lng], 12, { duration: 1 });
    }
  }, [selectedUnit]);

  return (
    <div style={{position:"relative"}}>
      <div ref={mapRef} style={{height:"calc(100vh - 280px)", minHeight:480, width:"100%", borderRadius:12, overflow:"hidden"}}/>
      <div className="map-overlay-info">
        <div className="label-eyebrow">{units.filter(u=>u.lat).length} homes on map</div>
        <div className="text-13" style={{color:"var(--muted)"}}>across 3 governorates</div>
      </div>
    </div>
  );
}

function UnitDetail({ unit, t, setScreen, citizen, saved, onSave, onClose }) {
  const [step, setStep] = React.useState("view");
  const calc = window.calculateLoan(citizen, unit.priceOmr, unit.project.includes("Irfan") ? "integrated" : "normal");

  return (
    <div className="unit-detail-inner">
      {/* Header */}
      <div className="unit-detail-topbar">
        <button className="btn ghost sm" onClick={onClose}>
          <Icon name="x" size={14}/> {t("Close","إغلاق")}
        </button>
        <div className="unit-pills" style={{position:"static"}}>
          <span className={`pill ${unit.status === "available" ? "ok" : "warn"}`}>
            {unit.status === "available" ? t("Available","متاح") : t("Reserved","محجوز")}
          </span>
          <span className="pill" style={{background:"var(--paper-warm)"}}>{unit.type}</span>
        </div>
        <button className="unit-fav" style={{position:"static", background:"var(--paper-warm)"}} onClick={onSave}>
          <Icon name="heart" size={15} stroke={2} style={{fill: saved ? "var(--brand-copper)" : "none", color: saved ? "var(--brand-copper)" : "var(--ink)"}}/>
        </button>
      </div>

      {/* Image */}
      <div className="unit-detail-img" style={!unit.image ? {background:`linear-gradient(135deg, ${unit.tone}, ${unit.tone}cc)`} : {}}>
        {unit.image
          ? <img src={unit.image} alt={unit.project}/>
          : <div className="unit-detail-img-inner"><Icon name="building" size={80} style={{color:"rgba(255,255,255,0.5)"}}/></div>
        }
      </div>

      {/* Body */}
      <div className="unit-detail-body">
        <div>
          <div className="text-12 muted">{unit.developer}</div>
          <div className="h3" style={{marginTop:4}}>{unit.project} · {unit.unit}</div>
          <div className="muted text-13" style={{marginTop:2}}>
            <Icon name="pin" size={12}/> {unit.wilayat}, {unit.governorate}
          </div>
        </div>

        <div className="grid-2" style={{gap:8}}>
          <FactCell icon="bed"      label={t("Bedrooms","غرف نوم")}        value={unit.beds}/>
          <FactCell icon="ruler"    label={t("Area","المساحة")}             value={`${unit.area} m²`}/>
          <FactCell icon="wallet"   label={t("Price","السعر")}              value={`OMR ${unit.priceOmr.toLocaleString()}`}/>
          <FactCell icon="building" label={t("Type","النوع")}               value={unit.type}/>
          {unit.landArea && <FactCell icon="map"    label={t("Plot","قطعة")}   value={`${unit.landArea} m²`}/>}
          {unit.baths    && <FactCell icon="shield" label={t("Baths","حمامات")} value={unit.baths}/>}
        </div>

        {step === "view" && (
          <div className="affordability card card-pad-sm">
            <div className="label-eyebrow">{t("Your monthly payment","دفعتك الشهرية")}</div>
            <div className="title" style={{marginTop:4, fontSize:18}}>
              {t("OMR","ر.ع.")} {calc.emi.toFixed(0)}/<span className="muted text-13">{t("mo","شهر")}</span>
            </div>
            <div className="afford-bar" style={{marginTop:8}}>
              <div className="afford-fill" style={{width:`${Math.min(calc.dbr,100)}%`, background: calc.dbr>50?"var(--warn)":"var(--brand-teal)"}}/>
              <span className="afford-mark" style={{left:"60%"}}/>
            </div>
            <div className="row text-12 muted" style={{justifyContent:"space-between",marginTop:4}}>
              <span>DBR {calc.dbr}%</span><span>{t("Limit","الحد")} 60%</span>
            </div>
          </div>
        )}

        {step === "view" && (
          <button className="btn copper lg" disabled={unit.status !== "available"}
            onClick={() => setStep("reserving")}>
            <Icon name="key" size={15}/>
            {unit.status === "available" ? t("Reserve for 7 days","احجز لمدة 7 أيام") : t("Currently reserved","محجوز")}
          </button>
        )}

        {step === "reserving" && (
          <div className="reserving">
            <div className="reserving-anim">
              <div className="r-ring r1"/><div className="r-ring r2"/><div className="r-ring r3"/>
              <Icon name="key" size={28} style={{color:"var(--brand-copper)"}}/>
            </div>
            <div className="title">{t("Locking your reservation…","جاري تأكيد الحجز…")}</div>
            <div className="muted text-13">{t("Notifying developer, OHB and your preferred bank.","إعلام المطور والبنك")}</div>
            <button className="btn copper" onClick={() => setStep("reserved")}>{t("Confirm","تأكيد")}</button>
          </div>
        )}

        {step === "reserved" && (
          <div className="reserved">
            <div className="reserved-icon"><Icon name="check_circle" size={36}/></div>
            <div className="h3">{t("Reserved.","تم الحجز.")}</div>
            <div className="muted text-13" style={{textAlign:"center"}}>
              {t("Held until","محجوز حتى")} <strong>26 May 2026, 17:00</strong>
            </div>
            <button className="btn teal" style={{width:"100%"}} onClick={() => setScreen("finance")}>
              {t("Continue to financing","متابعة للتمويل")} <Icon name="arrow_right" size={14} className="arrow-flip"/>
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

function FactCell({ icon, label, value }) {
  return (
    <div className="fact-cell">
      <Icon name={icon} size={14} style={{color:"var(--muted)"}}/>
      <div>
        <div className="tiny muted">{label}</div>
        <div className="text-13" style={{fontWeight:600}}>{value}</div>
      </div>
    </div>
  );
}

window.CitizenBrowse = CitizenBrowse;
