// KSANET — Promociones (listado v2)
// Editorial: portada índice, atlas de la Comunidad de Madrid, fichas archivadas.

const { useState, useMemo, useRef, useEffect } = React;

function cFmt(n) {
  return new Intl.NumberFormat('es-ES', { maximumFractionDigits: 0 }).format(n) + ' €';
}
function pad2(n) { return String(n).padStart(2, '0'); }

/* ─────────────────────────────────────────────────────────────
   HERO · Portada índice
   ───────────────────────────────────────────────────────────── */
function PromosHero() {
  const total = PROMOS.length;
  const units = PROMOS.reduce((a, p) => a + p.units, 0);
  const provs = new Set(PROMOS.map(p => p.locShort)).size;
  return (
    <section className="ph-hero">
      <div className="container">
        <div className="ph-hero-grid">
          <div className="ph-hero-left">
            <div className="ph-rule">
              <span className="ph-rule-l">N.º 07</span>
              <span className="ph-rule-d">·</span>
              <span className="ph-rule-l">Atlas KSANET · 2026</span>
              <span className="ph-rule-line"></span>
              <span className="ph-rule-l">Comunidad de Madrid</span>
            </div>
            <h1 className="ph-hero-title">
              Siete cooperativas<br/>
              en obra. <em>Una sola</em><br/>
              forma de construir.
            </h1>
            <p className="ph-hero-lede">
              Cada promoción es una cooperativa de socios. El precio es el coste real,
              auditado mes a mes. Sin promotor, sin margen oculto. Filtra por estado, zona o tipología.
            </p>
            <div className="ph-hero-cta">
              <a href="#index" className="btn btn-primary">Ver el índice <span className="btn-arrow">↓</span></a>
              <a href="cooperativa.html" className="btn btn-ghost">Cómo funciona la cooperativa <span className="btn-arrow">→</span></a>
            </div>
          </div>
          <div className="ph-hero-right">
            <div className="ph-stack">
              <div className="ph-stack-h">
                <span className="eyebrow"><span className="dot"></span>Cifras del catálogo</span>
              </div>
              <div className="ph-stack-rows">
                <div className="ph-stack-row">
                  <span className="ph-stack-n">{total}</span>
                  <span className="ph-stack-l">Promociones activas</span>
                </div>
                <div className="ph-stack-row">
                  <span className="ph-stack-n">{units}</span>
                  <span className="ph-stack-l">Viviendas en cooperativa</span>
                </div>
                <div className="ph-stack-row">
                  <span className="ph-stack-n">{provs}</span>
                  <span className="ph-stack-l">Municipios</span>
                </div>
                <div className="ph-stack-row">
                  <span className="ph-stack-n"><span style={{ color: 'var(--brand)' }}>A</span></span>
                  <span className="ph-stack-l">Calificación energética</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        {/* Mini reel de fotos */}
        <div className="ph-reel" aria-hidden="true">
          {PROMOS.flatMap(p => (p.photos || []).slice(0, 1).map((src, i) => (
            <div key={p.id + i} className="ph-reel-cell" style={{ backgroundImage: `url(${src})` }}>
              <span className="ph-reel-tag">{p.locShort}</span>
            </div>
          )))}
          {/* fill */}
          {PROMOS.filter(p => !p.photos || !p.photos.length).map(p => (
            <div key={p.id} className="ph-reel-cell" style={{ background: p.image }}>
              <span className="ph-reel-tag">{p.locShort}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────────────────────
   FILTROS
   ───────────────────────────────────────────────────────────── */
function PromoFilters({ filter, setFilter, total }) {
  const STATUSES = [
    { k: 'all', label: 'Todas' },
    { k: 'comercial', label: 'Comercialización' },
    { k: 'obra', label: 'En obra' },
    { k: 'proxima', label: 'Próximamente' },
    { k: 'entregada', label: 'Entregadas' },
  ];
  const PROVS = [...new Set(PROMOS.map(p => p.locShort))];
  return (
    <div className="filters-v2">
      <div className="filters-v2-inner">
        <div className="filter-row">
          <span className="filter-label">Estado</span>
          <div className="filter-chips">
            {STATUSES.map(s => (
              <button key={s.k}
                className={'chip' + (filter.status === s.k ? ' active' : '')}
                onClick={() => setFilter({ ...filter, status: s.k })}>
                {s.label}
              </button>
            ))}
          </div>
        </div>
        <div className="filter-row">
          <span className="filter-label">Municipio</span>
          <div className="filter-chips">
            <button className={'chip' + (filter.prov === 'all' ? ' active' : '')} onClick={() => setFilter({ ...filter, prov: 'all' })}>Todos</button>
            {PROVS.map(p => (
              <button key={p}
                className={'chip' + (filter.prov === p ? ' active' : '')}
                onClick={() => setFilter({ ...filter, prov: p })}>
                {p}
              </button>
            ))}
          </div>
        </div>
        <div className="filter-row">
          <span className="filter-label">Dormitorios</span>
          <div className="filter-chips">
            {['all', '2', '3', '4'].map(d => (
              <button key={d}
                className={'chip' + (filter.dorm === d ? ' active' : '')}
                onClick={() => setFilter({ ...filter, dorm: d })}>
                {d === 'all' ? 'Cualquiera' : d + ' dorm'}
              </button>
            ))}
          </div>
        </div>
      </div>
      <div className="filter-result">
        <span className="filter-count">{pad2(total)} <span className="filter-count-l">resultados</span></span>
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────
   ATLAS · mapa real (Leaflet + OpenStreetMap)
   Mapa interactivo de la Comunidad de Madrid con marcadores
   numerados sincronizados con el listado lateral.
   ───────────────────────────────────────────────────────────── */
function MadridAtlas({ promos, hover, setHover }) {
  const focus = promos.find(p => p.id === hover) || promos[0];
  const mapRef = useRef(null);
  const mapEl = useRef(null);
  const markersRef = useRef({});

  // Init mapa
  useEffect(() => {
    if (!mapEl.current || mapRef.current) return;
    if (typeof L === 'undefined') return;

    const map = L.map(mapEl.current, {
      center: [40.45, -3.65],
      zoom: 9,
      zoomControl: false,
      attributionControl: true,
      scrollWheelZoom: false,
    });

    // Cartografía monocroma editorial (Stadia Stamen Toner Lite — sin pedir clave si origen permitido)
    L.tileLayer('https://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}{r}.png', {
      maxZoom: 18,
      attribution: '© OpenStreetMap · © CARTO',
    }).addTo(map);

    // Capa labels separada (sutil)
    L.tileLayer('https://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}{r}.png', {
      maxZoom: 18,
      pane: 'shadowPane',
    }).addTo(map);

    L.control.zoom({ position: 'bottomright' }).addTo(map);

    mapRef.current = map;
  }, []);

  // Añadir marcadores
  useEffect(() => {
    const map = mapRef.current;
    if (!map) return;

    // Limpiar
    Object.values(markersRef.current).forEach(m => map.removeLayer(m));
    markersRef.current = {};

    promos.forEach(p => {
      if (!p.latlng) return;
      const num = pad2(PROMOS.findIndex(x => x.id === p.id) + 1);
      const colorVar = p.statusKey === 'comercial' ? 'var(--brand)'
                     : p.statusKey === 'obra' ? 'var(--gold)'
                     : p.statusKey === 'proxima' ? 'var(--moss)'
                     : 'var(--silver-2)';
      const icon = L.divIcon({
        className: 'atlas-pin',
        html: `<span class="atlas-pin-num" style="--pin-color:${colorVar}">${num}</span>`,
        iconSize: [38, 38],
        iconAnchor: [19, 19],
      });
      const marker = L.marker(p.latlng, { icon, riseOnHover: true })
        .addTo(map)
        .on('mouseover', () => setHover(p.id))
        .on('mouseout', () => setHover(null))
        .on('click', () => {
          window.location.href = p.id === 'edificio-victoria'
            ? 'victoria-landing.html'
            : `promocion.html?id=${p.id}`;
        });
      markersRef.current[p.id] = marker;
    });

    // Encajar a límites
    const validPromos = promos.filter(p => p.latlng);
    if (validPromos.length) {
      const bounds = L.latLngBounds(validPromos.map(p => p.latlng));
      map.fitBounds(bounds, { padding: [60, 60], maxZoom: 10 });
    }
  }, [promos]);

  // Hover externo → resalta marcador
  useEffect(() => {
    Object.entries(markersRef.current).forEach(([id, m]) => {
      const el = m.getElement();
      if (!el) return;
      el.classList.toggle('is-hover', id === hover);
    });
  }, [hover]);

  return (
    <div className="atlas">
      {/* — Cabecera del atlas — */}
      <div className="atlas-head">
        <div className="atlas-head-l">
          <div className="atlas-head-eyebrow">Lám. 01 · Atlas Comunidad de Madrid</div>
          <div className="atlas-head-coord">40°25′N · 3°42′W · datos OpenStreetMap</div>
        </div>
        <div className="atlas-head-r">N ↑</div>
      </div>

      {/* — Mapa real — */}
      <div className="atlas-canvas">
        <div ref={mapEl} className="atlas-leaflet"></div>

        {/* Esquina: leyenda */}
        <div className="atlas-legend">
          <span><span className="dot" style={{ background: 'var(--brand)' }}></span>Comercializa.</span>
          <span><span className="dot" style={{ background: 'var(--gold)' }}></span>En obra</span>
          <span><span className="dot" style={{ background: 'var(--moss)' }}></span>Próximas</span>
          <span><span className="dot" style={{ background: 'var(--silver-2)' }}></span>Entregadas</span>
        </div>
      </div>

      {/* — Panel de preview foto + datos del marcador activo — */}
      {focus && (
        <div className="atlas-focus">
          <div className="atlas-focus-img"
               style={{
                 backgroundImage: focus.photos && focus.photos[0]
                   ? `linear-gradient(180deg, rgba(20,8,10,0) 50%, rgba(20,8,10,.55) 100%), url(${focus.photos[0]})`
                   : focus.image
               }}>
            <span className="atlas-focus-num">{pad2(PROMOS.findIndex(x => x.id === focus.id) + 1)}</span>
          </div>
          <div className="atlas-focus-body">
            <div className="atlas-focus-loc">{focus.locShort} · Madrid</div>
            <div className="atlas-focus-name">{focus.fullName || focus.name}</div>
            <div className="atlas-focus-meta">
              <span>{focus.units} viv.</span>
              <span>·</span>
              <span>{focus.bedrooms[0]}–{focus.bedrooms[focus.bedrooms.length-1]} dorm</span>
              <span>·</span>
              <span style={{ color: 'var(--brand)' }}>{focus.priceFromLabel}</span>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────
   FICHA · tarjeta archivada
   ───────────────────────────────────────────────────────────── */
function PromoListCard({ p, hover, setHover, idx, total }) {
  const isHover = hover === p.id;
  const num = pad2(PROMOS.findIndex(x => x.id === p.id) + 1);
  const sold = p.sold || 0;
  const pct = Math.round((sold / p.units) * 100);
  return (
    <a href={p.id === 'edificio-victoria' ? 'victoria-landing.html' : `promocion.html?id=${p.id}`}
       className={'fcard' + (isHover ? ' is-hover' : '')}
       onMouseEnter={() => setHover(p.id)}
       onMouseLeave={() => setHover(null)}>
      <div className="fcard-stripe">
        <span className="fcard-stripe-num">{num} <span>/</span> {pad2(PROMOS.length)}</span>
        <span className="fcard-stripe-code">{p.code}</span>
      </div>

      <div className="fcard-grid">
        <div className="fcard-img" style={{
          background: p.photos && p.photos.length
            ? `linear-gradient(180deg, rgba(20,8,10,0) 55%, rgba(20,8,10,.5) 100%), url(${p.photos[0]}) center/cover no-repeat, ${p.image}`
            : p.image
        }}>
          <span className={'fcard-status ' + (p.statusKey === 'proxima' ? 'upcoming' : p.statusKey === 'entregada' ? 'delivered' : '')}>
            <span className="dot"></span>{p.status}
          </span>
          <span className="fcard-tipo">{p.tipo}</span>
        </div>

        <div className="fcard-body">
          <div className="fcard-loc">{p.location}</div>
          <h3 className="fcard-name">{p.name}</h3>

          <p className="fcard-desc">{(p.description || '').slice(0, 138)}…</p>

          <div className="fcard-stats">
            <div><span className="lbl">Viviendas</span><span className="val">{p.units}</span></div>
            <div><span className="lbl">Dorms</span><span className="val">{p.bedrooms[0]}–{p.bedrooms[p.bedrooms.length-1]}</span></div>
            <div><span className="lbl">Sup. desde</span><span className="val">{p.surfaceFrom} <em>m²</em></span></div>
            <div><span className="lbl">Calificación energ.</span><span className="val">A</span></div>
          </div>

          {p.statusKey !== 'entregada' && p.statusKey !== 'proxima' && (
            <div className="fcard-progress">
              <div className="fcard-progress-bar">
                <span style={{ width: pct + '%' }}></span>
              </div>
              <div className="fcard-progress-meta">
                <span>{sold} / {p.units} adjudicadas</span>
                <span>{pct}%</span>
              </div>
            </div>
          )}

          <div className="fcard-foot">
            <div>
              <div className="fcard-foot-l">Desde</div>
              <div className="fcard-price">{cFmt(p.priceFrom)}</div>
            </div>
            <span className="fcard-cta">Ver promoción <span className="btn-arrow">→</span></span>
          </div>
        </div>
      </div>
    </a>
  );
}

/* ─────────────────────────────────────────────────────────────
   PÁGINA
   ───────────────────────────────────────────────────────────── */
function PromosListPage() {
  useReveal();
  const [filter, setFilter] = useState({ status: 'all', prov: 'all', dorm: 'all' });
  const [hover, setHover] = useState(null);

  const filtered = useMemo(() => PROMOS.filter(p => {
    if (filter.status !== 'all' && p.statusKey !== filter.status) return false;
    if (filter.prov !== 'all' && p.locShort !== filter.prov) return false;
    if (filter.dorm !== 'all' && !p.bedrooms.includes(parseInt(filter.dorm))) return false;
    return true;
  }), [filter]);

  return (
    <>
      <Header active="promociones"/>

      {/* ATLAS · sección destacada full-width */}
      <section className="section atlas-section" style={{ paddingTop: 80, paddingBottom: 80, borderTop: '1px solid var(--line)' }}>
        <div className="container">
          <div className="atlas-section-h">
            <div>
              <span className="eyebrow"><span className="dot"></span>Lám. 01 · Atlas KSANET</span>
              <h2 className="h-1" style={{ marginTop: 14 }}>
                <em>Siete</em> cooperativas<br/>en la Comunidad de Madrid.
              </h2>
            </div>
            <p className="lede atlas-section-lede">
              Pasa el ratón por cualquier marcador para previsualizar la promoción.
              Cada cooperativa está numerada según el orden del catálogo 2026.
            </p>
          </div>
          <div className="atlas-feature">
            <div className="atlas-feature-map">
              <MadridAtlas promos={filtered.length ? filtered : PROMOS} hover={hover} setHover={setHover}/>
            </div>
            <div className="atlas-feature-list">
              <div className="atlas-feature-list-h">
                <span className="eyebrow"><span className="dot"></span>Catálogo</span>
              </div>
              <div className="atlas-feature-list-rows">
                {(filtered.length ? filtered : PROMOS).map((p, i) => {
                  const num = pad2(PROMOS.findIndex(x => x.id === p.id) + 1);
                  return (
                    <a key={p.id}
                       href={p.id === 'edificio-victoria' ? 'victoria-landing.html' : `promocion.html?id=${p.id}`}
                       className={'afl-row' + (hover === p.id ? ' is-hover' : '')}
                       onMouseEnter={() => setHover(p.id)}
                       onMouseLeave={() => setHover(null)}>
                      <span className="afl-num">{num}</span>
                      <div className="afl-body">
                        <div className="afl-name">{p.name}</div>
                        <div className="afl-loc">{p.locShort} · {p.tipo}</div>
                      </div>
                      <span className={'afl-pill ' + p.statusKey}>
                        <span className="dot"></span>
                      </span>
                      <span className="afl-arr">→</span>
                    </a>
                  );
                })}
              </div>
            </div>
          </div>
        </div>
      </section>

      <section className="section paper" id="index" style={{ paddingTop: 64, paddingBottom: 32, borderTop: 'none' }}>
        <div className="container">
          <PromoFilters filter={filter} setFilter={setFilter} total={filtered.length}/>
        </div>
      </section>

      <section className="section paper" style={{ paddingTop: 24, paddingBottom: 100, borderTop: 'none' }}>
        <div className="container">
          <div className="list-col">
            {filtered.length === 0 && (
              <div className="empty-state">
                <span className="eyebrow"><span className="dot"></span>Sin resultados</span>
                <p className="body" style={{ marginTop: 12 }}>Ajusta los filtros o consulta el atlas completo.</p>
              </div>
            )}
            {filtered.map((p, i) => (
              <PromoListCard key={p.id} p={p} hover={hover} setHover={setHover} idx={i} total={filtered.length}/>
            ))}
          </div>
        </div>
      </section>

      {/* Banda inferior: índice tabular */}
      <section className="section dark" style={{ paddingTop: 90, paddingBottom: 90 }}>
        <div className="container">
          <div className="ph-index-h">
            <span className="eyebrow"><span className="dot"></span>Índice general · Atlas KSANET 2026</span>
            <h2 className="h-2" style={{ marginTop: 14, color: '#f3e8da', maxWidth: 760 }}>
              Las siete cooperativas en una sola tabla. <em>Trazabilidad pública.</em>
            </h2>
          </div>
          <div className="ph-index-table">
            <div className="ph-index-row ph-index-head">
              <span>Nº</span>
              <span>Promoción</span>
              <span>Municipio</span>
              <span>Tipología</span>
              <span>Viviendas</span>
              <span>Estado</span>
              <span>Desde</span>
              <span>Cert.</span>
              <span></span>
            </div>
            {PROMOS.map((p, i) => (
              <a key={p.id}
                 href={p.id === 'edificio-victoria' ? 'victoria-landing.html' : `promocion.html?id=${p.id}`}
                 className="ph-index-row"
                 onMouseEnter={() => setHover(p.id)}
                 onMouseLeave={() => setHover(null)}>
                <span className="ph-index-num">{pad2(i + 1)}</span>
                <span className="ph-index-name">{p.fullName || p.name}</span>
                <span>{p.locShort}</span>
                <span>{p.tipo}</span>
                <span>{p.units}</span>
                <span>
                  <span className={'ph-index-pill ' + p.statusKey}>
                    <span className="dot"></span>{p.status}
                  </span>
                </span>
                <span className="ph-index-price">{cFmt(p.priceFrom)}</span>
                <span className="ph-index-cert">A</span>
                <span className="ph-index-arr">→</span>
              </a>
            ))}
          </div>
        </div>
      </section>

      <Footer/>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<PromosListPage/>);
