// DetailPanel — rechterkolom met alle velden van geselecteerd record.
// Krijgt een detail-response (via /v1/vergunningen/{koop_id}) of null+loading.

const { useEffect: useEffectDP, useRef: useRefDP, useState: useStateDP, useMemo: useMemoDP } = React;

// Lookups — zelfde patroon als ResultList/MapView.
const TB_BY_CODE_DP = WAARDELIJSTEN.type_besluit.reduce((m, t) => { m[t.code] = t; return m; }, {});
const AC_BY_CODE_DP = WAARDELIJSTEN.activiteit_code.reduce((m, a) => { m[a.code] = a; return m; }, {});
const PB_BY_CODE_DP = WAARDELIJSTEN.publicatieblad.reduce((m, p) => { m[p.code] = p; return m; }, {});

// proj4 RD New transformer — alleen registreren als 'ie nog niet bestaat.
// (mock-vergunningen.example.js doet hetzelfde, maar wordt niet meer geladen.)
if (typeof proj4 !== 'undefined' && !proj4.defs('EPSG:28992')) {
  proj4.defs(
    'EPSG:28992',
    '+proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 ' +
      '+k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel ' +
      '+towgs84=565.4171,50.3319,465.5524,-0.398957,0.343988,-1.8774,4.0725 +units=m +no_defs'
  );
}

function extractPoint(geom) {
  if (!geom) return null;
  if (geom.type === 'Point') return { lon: geom.coordinates[0], lat: geom.coordinates[1] };
  if (geom.type === 'Polygon') {
    // Centroid-ish: gemiddelde van outer ring (genoeg voor een mini-kaart-pin).
    const ring = geom.coordinates[0] || [];
    if (!ring.length) return null;
    let sx = 0, sy = 0;
    for (const [x, y] of ring) { sx += x; sy += y; }
    return { lon: sx / ring.length, lat: sy / ring.length };
  }
  return null;
}

function DetailPanel({ rec, loading, onClose }) {
  // Hook vóór elke early return — anders verandert de hook-count tussen
  // de loading-render (rec=null) en de loaded-render, en crasht React.
  const point = rec
    ? (extractPoint(rec.geometrie_geojson) || (rec.lat != null && rec.lon != null ? { lat: rec.lat, lon: rec.lon } : null))
    : null;
  const rdPt = useMemoDP(() => {
    if (!point || typeof proj4 === 'undefined') return null;
    try {
      const [x, y] = proj4('EPSG:4326', 'EPSG:28992', [point.lon, point.lat]);
      return { x: Math.round(x), y: Math.round(y) };
    } catch (_) { return null; }
  }, [point && point.lat, point && point.lon]);

  if (loading && !rec) return <DetailSkeleton onClose={onClose} />;
  if (!rec) return null;

  const tb = TB_BY_CODE_DP[rec.type_besluit];
  const tbColor = (tb && tb.color) || '#6B7280';
  const tbLabel = (tb && tb.label) || rec.type_besluit;
  const acLabel = (AC_BY_CODE_DP[rec.activiteit_code] && AC_BY_CODE_DP[rec.activiteit_code].label) || rec.activiteit_code;
  const bladLabel = (PB_BY_CODE_DP[rec.publicatieblad] && PB_BY_CODE_DP[rec.publicatieblad].label) || rec.publicatieblad;

  const daysBetween =
    rec.datum_ontvangst && rec.datum_publicatie
      ? Math.max(0, Math.round((new Date(rec.datum_publicatie) - new Date(rec.datum_ontvangst)) / 86400000))
      : null;

  return (
    <aside className="w-[400px] shrink-0 border-l border-slate-200 bg-white overflow-y-auto flex flex-col">
      {/* Top bar */}
      <div className="flex items-center justify-between px-4 py-2.5 border-b border-slate-200 sticky top-0 bg-white z-10">
        <div className="text-[11px] uppercase tracking-wider text-slate-500 font-medium flex items-center gap-2">
          <span>Vergunningkennisgeving</span>
          {loading && (
            <span
              aria-label="Detail wordt bijgewerkt"
              className="inline-block w-1.5 h-1.5 rounded-full bg-emerald-900/60 animate-pulse"
            ></span>
          )}
        </div>
        <button
          type="button"
          onClick={onClose}
          aria-label="Sluit detailpaneel"
          className="text-slate-400 hover:text-slate-900 focus:outline-none focus:text-slate-900 p-1 -mr-1"
        >
          <svg viewBox="0 0 16 16" className="w-4 h-4">
            <path d="M3 3 L13 13 M13 3 L3 13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
          </svg>
        </button>
      </div>

      {/* Header block */}
      <div className="px-5 pt-4 pb-4 border-b border-slate-200">
        <div className="flex flex-wrap items-center gap-1.5 mb-3">
          <span
            className="text-[11px] uppercase tracking-wider font-medium px-2 py-0.5 rounded-sm"
            style={{ background: tbColor + '1A', color: tbColor }}
          >
            {tbLabel}
          </span>
          <span className="text-[11px] uppercase tracking-wider font-medium px-2 py-0.5 rounded-sm bg-slate-100 text-slate-700">
            {acLabel}
          </span>
          {rec.geometrie_type && (
            <span className="text-[11px] uppercase tracking-wider font-medium px-2 py-0.5 rounded-sm bg-slate-100 text-slate-700">
              {rec.geometrie_type}
            </span>
          )}
        </div>
        <h2 className="font-serif text-[19px] leading-snug text-slate-900 text-pretty">
          {rec.titel}
        </h2>
        <div className="mt-3 text-[12px] text-slate-600 flex items-center flex-wrap gap-x-2 gap-y-0.5">
          <span className="font-medium text-slate-800">{rec.bg_naam}</span>
          <span className="text-slate-300">·</span>
          <span>{bladLabel}</span>
          <span className="text-slate-300">·</span>
          <span className="tabular-nums">{fmt.dateLong(rec.datum_publicatie)}</span>
        </div>
      </div>

      {/* Tijdlijn aanvraag → publicatie */}
      {rec.datum_ontvangst && (
        <div className="px-5 py-4 border-b border-slate-200 bg-[#FAFAF7]">
          <div className="text-[10px] uppercase tracking-wider text-slate-500 font-medium mb-2">
            Doorlooptijd
          </div>
          <Timeline from={rec.datum_ontvangst} to={rec.datum_publicatie} days={daysBetween} />
        </div>
      )}

      {/* Adres + mini-kaart */}
      {(rec.straatnaam || point) && (
        <div className="px-5 py-4 border-b border-slate-200">
          <div className="text-[10px] uppercase tracking-wider text-slate-500 font-medium mb-2">
            Locatie
          </div>
          {rec.straatnaam && (
            <div className="text-[14px] text-slate-900 mb-2">
              <div>{fullAddress(rec)}</div>
              <div className="text-slate-600 text-[13px]">
                {fmt.postcode(rec.postcode)} {rec.woonplaats}
              </div>
              {rec.ligt_in_gemeente && rec.ligt_in_gemeente !== rec.woonplaats && (
                <div className="text-slate-500 text-[12px]">Gemeente {rec.ligt_in_gemeente}</div>
              )}
            </div>
          )}
          {point && <MiniMap geom={rec.geometrie_geojson} point={point} color={tbColor} />}
          {rdPt && (
            <div className="text-[11px] text-slate-500 mt-2 tabular-nums font-mono">
              RD: {rdPt.x.toLocaleString('nl-NL')} ×{' '}
              {rdPt.y.toLocaleString('nl-NL')} m
            </div>
          )}
        </div>
      )}

      {/* Veldenblok */}
      <div className="px-5 py-4 border-b border-slate-200">
        <dl className="grid grid-cols-[140px_1fr] gap-y-2 gap-x-3 text-[12px]">
          <DT>Beleidsthema</DT>
          <DD>{rec.subject_taxonomie}</DD>

          <DT>Zaaknummer</DT>
          <DD className="font-mono">{rec.zaaknummer_bg || <em className="text-slate-400">geen</em>}</DD>

          <DT>KOOP-ID</DT>
          <DD className="font-mono">{rec.koop_id}</DD>

          {(rec.jaargang || rec.publicatienummer) && (
            <>
              <DT>Publicatienr.</DT>
              <DD className="font-mono">
                {rec.jaargang ? rec.jaargang + ' / ' : ''}{rec.publicatienummer || ''}
              </DD>
            </>
          )}

          <DT>Publicatie</DT>
          <DD className="tabular-nums">
            {fmt.dateShort(rec.datum_publicatie)}
            {rec.datum_publicatie_ts && (
              <span className="text-slate-500"> om {fmt.time(rec.datum_publicatie_ts)}</span>
            )}
          </DD>

          {rec.datum_ontvangst && (
            <>
              <DT>Aanvraag ontvangen</DT>
              <DD className="tabular-nums">{fmt.dateShort(rec.datum_ontvangst)}</DD>
            </>
          )}

          <DT>Organisatietype</DT>
          <DD className="capitalize">{rec.organisatietype}</DD>

          {rec.bg_scheme && (
            <>
              <DT>BG-scheme</DT>
              <DD className="font-mono text-slate-600">{rec.bg_scheme}</DD>
            </>
          )}

          {rec.geometrielabel && (
            <>
              <DT>Geometrielabel</DT>
              <DD className="text-slate-700">{rec.geometrielabel}</DD>
            </>
          )}

          {/* BG-deeplink — komt uit de koppeltabel via /v1/vergunningen/{id}.
              Veldnaam in afwachting van API-uitbreiding: `bg_deeplink_url`.
              Toont niets zolang het veld leeg/afwezig is. */}
          {rec.bg_deeplink_url && (
            <>
              <DT>Deeplink BG</DT>
              <DD>
                <a
                  href={rec.bg_deeplink_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-emerald-900 hover:underline break-all inline-flex items-center gap-1"
                >
                  <span>{rec.bg_deeplink_url}</span>
                  <svg viewBox="0 0 12 12" className="w-2.5 h-2.5 shrink-0" aria-hidden>
                    <path d="M4 2 L10 2 L10 8 M10 2 L4 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                  </svg>
                </a>
              </DD>
            </>
          )}
        </dl>
      </div>

      {/* Beschrijving (kort) */}
      {rec.beschrijving && (
        <div className="px-5 py-4 border-b border-slate-200">
          <div className="text-[10px] uppercase tracking-wider text-slate-500 font-medium mb-2">
            Beschrijving
          </div>
          <div className="text-[12.5px] text-slate-800 leading-relaxed whitespace-pre-line">
            {rec.beschrijving}
          </div>
        </div>
      )}

      {/* Inhoud_tekst (collapsable) */}
      {rec.inhoud_tekst && <InhoudTekst text={rec.inhoud_tekst} />}

      {/* Action buttons */}
      <div className="px-5 py-4 border-t border-slate-200 mt-auto bg-white sticky bottom-0 flex flex-col gap-2">
        <a
          href={rec.preferred_url}
          target="_blank"
          rel="noopener noreferrer"
          className="flex items-center justify-center gap-2 bg-emerald-900 text-white text-[13px] font-medium px-3 py-2 rounded-md hover:bg-emerald-800 focus:outline-none focus:ring-2 focus:ring-emerald-900/30"
        >
          <span>Open op officielebekendmakingen.nl</span>
          <svg viewBox="0 0 12 12" className="w-3 h-3" aria-hidden>
            <path d="M4 2 L10 2 L10 8 M10 2 L4 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
          </svg>
        </a>
        <a
          href={rec.pdf_url}
          target="_blank"
          rel="noopener noreferrer"
          className="flex items-center justify-center gap-2 bg-white border border-slate-300 text-slate-900 text-[13px] font-medium px-3 py-2 rounded-md hover:bg-slate-50 focus:outline-none focus:ring-2 focus:ring-emerald-900/20"
        >
          <span>Download PDF</span>
          <svg viewBox="0 0 12 12" className="w-3 h-3" aria-hidden>
            <path d="M6 1.5 L6 8 M3 5 L6 8 L9 5 M2 10.5 L10 10.5" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </a>
      </div>
    </aside>
  );
}

function DetailSkeleton({ onClose }) {
  return (
    <aside className="w-[400px] shrink-0 border-l border-slate-200 bg-white overflow-y-auto flex flex-col">
      <div className="flex items-center justify-between px-4 py-2.5 border-b border-slate-200">
        <div className="text-[11px] uppercase tracking-wider text-slate-500 font-medium flex items-center gap-2">
          <span>Vergunningkennisgeving</span>
          <span className="inline-block w-1.5 h-1.5 rounded-full bg-emerald-900/60 animate-pulse"></span>
        </div>
        <button
          type="button"
          onClick={onClose}
          aria-label="Sluit detailpaneel"
          className="text-slate-400 hover:text-slate-900 p-1 -mr-1"
        >
          <svg viewBox="0 0 16 16" className="w-4 h-4">
            <path d="M3 3 L13 13 M13 3 L3 13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
          </svg>
        </button>
      </div>
      <div className="px-5 pt-4 pb-4 border-b border-slate-200 animate-pulse">
        <div className="flex gap-1.5 mb-3">
          <div className="h-4 w-16 bg-slate-200 rounded-sm"></div>
          <div className="h-4 w-20 bg-slate-200 rounded-sm"></div>
        </div>
        <div className="h-5 bg-slate-200 rounded mb-1.5 w-11/12"></div>
        <div className="h-5 bg-slate-200 rounded mb-1.5 w-8/12"></div>
        <div className="h-3 bg-slate-100 rounded mt-3 w-7/12"></div>
      </div>
      <div className="px-5 py-4 border-b border-slate-200 animate-pulse">
        <div className="h-3 bg-slate-100 rounded mb-3 w-20"></div>
        <div className="h-3 bg-slate-100 rounded mb-1.5 w-10/12"></div>
        <div className="h-3 bg-slate-100 rounded mb-1.5 w-9/12"></div>
        <div className="h-[200px] bg-slate-100 rounded mt-2"></div>
      </div>
    </aside>
  );
}

function DT({ children }) {
  return <dt className="text-slate-500 text-[11px] uppercase tracking-wider pt-0.5">{children}</dt>;
}
function DD({ children, className = '' }) {
  return <dd className={`text-slate-900 break-words ${className}`}>{children}</dd>;
}

function Timeline({ from, to, days }) {
  return (
    <div>
      <div className="flex items-center gap-3 text-[12px]">
        <div className="flex-1">
          <div className="text-[10px] uppercase tracking-wider text-slate-500">Aanvraag</div>
          <div className="text-slate-900 tabular-nums">{fmt.dateShort(from)}</div>
        </div>
        <div className="flex-[2] relative pt-3">
          <div className="absolute left-0 right-0 top-3 h-px bg-slate-300"></div>
          <div className="absolute top-2 -translate-y-1/2 w-2 h-2 rounded-full bg-slate-400 ring-2 ring-[#FAFAF7]" style={{ left: 0 }}></div>
          <div className="absolute top-2 -translate-y-1/2 w-2 h-2 rounded-full bg-emerald-900 ring-2 ring-[#FAFAF7]" style={{ right: 0 }}></div>
          <div className="text-center text-[11px] text-slate-600 mt-0.5">
            {days != null ? fmt.days(days) : ''}
          </div>
        </div>
        <div className="flex-1 text-right">
          <div className="text-[10px] uppercase tracking-wider text-slate-500">Publicatie</div>
          <div className="text-slate-900 tabular-nums">{fmt.dateShort(to)}</div>
        </div>
      </div>
    </div>
  );
}

function InhoudTekst({ text }) {
  const [expanded, setExpanded] = useStateDP(false);
  return (
    <div className="px-5 py-4 border-b border-slate-200">
      <div className="flex items-center justify-between mb-2">
        <div className="text-[10px] uppercase tracking-wider text-slate-500 font-medium">
          Tekst van bekendmaking
        </div>
        <button
          type="button"
          onClick={() => setExpanded(!expanded)}
          className="text-[11px] text-slate-500 hover:text-emerald-900 focus:outline-none focus:text-emerald-900"
        >
          {expanded ? 'inklappen' : 'uitklappen'}
        </button>
      </div>
      <div
        className={`text-[12.5px] text-slate-800 leading-relaxed whitespace-pre-line ${
          expanded ? 'max-h-[400px] overflow-y-auto pr-1' : 'max-h-20 overflow-hidden relative'
        }`}
        style={
          !expanded
            ? {
                WebkitMaskImage: 'linear-gradient(to bottom, black 0, black 50%, transparent 100%)',
                maskImage: 'linear-gradient(to bottom, black 0, black 50%, transparent 100%)',
              }
            : {}
        }
      >
        {text}
      </div>
    </div>
  );
}

function MiniMap({ geom, point, color }) {
  const ref = useRefDP(null);
  const mapRef = useRefDP(null);

  useEffectDP(() => {
    if (!ref.current || mapRef.current) return;
    const map = new maplibregl.Map({
      container: ref.current,
      style: {
        version: 8,
        sources: {
          'pdok-brt': {
            type: 'raster',
            tiles: [
              'https://service.pdok.nl/brt/achtergrondkaart/wmts/v2_0/grijs/EPSG:3857/{z}/{x}/{y}.png',
            ],
            tileSize: 256,
            attribution: '© Kadaster',
          },
        },
        layers: [
          { id: 'bg', type: 'background', paint: { 'background-color': '#F2EFE8' } },
          { id: 'pdok', type: 'raster', source: 'pdok-brt' },
        ],
      },
      center: [point.lon, point.lat],
      zoom: 15.5,
      interactive: false,
      attributionControl: false,
    });
    map.on('load', () => {
      map.addSource('p', {
        type: 'geojson',
        data: {
          type: 'Feature',
          geometry: { type: 'Point', coordinates: [point.lon, point.lat] },
          properties: {},
        },
      });
      if (geom && geom.type === 'Polygon') {
        map.addSource('poly', { type: 'geojson', data: { type: 'Feature', geometry: geom, properties: {} } });
        map.addLayer({ id: 'poly-f', type: 'fill', source: 'poly', paint: { 'fill-color': color, 'fill-opacity': 0.3 } });
        map.addLayer({ id: 'poly-l', type: 'line', source: 'poly', paint: { 'line-color': color, 'line-width': 2 } });
      }
      map.addLayer({ id: 'p-halo', type: 'circle', source: 'p', paint: { 'circle-color': '#fff', 'circle-radius': 12, 'circle-stroke-color': color, 'circle-stroke-width': 2 } });
      map.addLayer({ id: 'p', type: 'circle', source: 'p', paint: { 'circle-color': color, 'circle-radius': 6, 'circle-stroke-color': '#fff', 'circle-stroke-width': 2 } });
      map.resize();
    });
    mapRef.current = map;
    return () => { map.remove(); mapRef.current = null; };
  // eslint-disable-next-line
  }, [point.lon, point.lat]);

  return (
    <div
      ref={ref}
      className="w-full h-[200px] rounded border border-slate-200 overflow-hidden"
      aria-label="Detail-kaart locatie"
    />
  );
}

Object.assign(window, { DetailPanel });
