/* Data-scherm: zoeken op panden/percelen + detailview
   Redesigned - Thema Centric DutchGovernmentModern */

/* ================================================================
   ZOEKSCHERM
   ================================================================ */
function DataZoekScherm({ onSelectPand }) {
  const [zoekterm, setZoekterm] = React.useState('');
  const [resultaten, setResultaten] = React.useState([]);
  const [laden, setLaden] = React.useState(false);
  const [fout, setFout] = React.useState(null);

  async function zoek(q) {
    if (!q || q.length < 2) { setResultaten([]); return; }
    setLaden(true); setFout(null);
    try {
      const r = await fetch(`${API}/data/zoek?q=${encodeURIComponent(q)}`);
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      setResultaten(await r.json());
    } catch(e) {
      setFout(e.message);
    } finally {
      setLaden(false);
    }
  }

  React.useEffect(() => {
    const t = setTimeout(() => zoek(zoekterm), 300);
    return () => clearTimeout(t);
  }, [zoekterm]);

  return (
    <div className="bd-page">
      <div className="bd-page-head">
        <div>
          <h1>Panden zoeken</h1>
          <p>Zoek op adres, straatnaam, BAG ID, VBO ID of perceelnummer</p>
        </div>
      </div>

      <div className="bd-card" style={{ padding: '0', overflow: 'hidden' }}>
        <div style={{ padding: 'var(--space-4) var(--space-5)', borderBottom: '1px solid var(--color-border-light)' }}>
          <div className="tc-header-search" style={{ maxWidth: '100%' }}>
            <Icon name="search" size={16} />
            <input
              type="text"
              placeholder="Zoek op adres, BAG ID, VBO ID of perceelnummer..."
              value={zoekterm}
              onChange={e => setZoekterm(e.target.value)}
              autoFocus
            />
            {laden && <Icon name="loader" size={14} style={{ animation: 'spin 1s linear infinite', opacity: 0.5 }} />}
            {zoekterm && <button className="tc-icon-btn tc-icon-btn--sm" onClick={() => setZoekterm('')} style={{flexShrink:0}}><Icon name="x" size={14} /></button>}
          </div>
        </div>

        {fout && (
          <div style={{ padding: 'var(--space-4) var(--space-5)' }}>
            <Alert kind="error">Fout bij ophalen: {fout}</Alert>
          </div>
        )}

        {!laden && zoekterm.length >= 2 && resultaten.length === 0 && !fout && (
          <Empty icon="search-x" title="Geen resultaten" hint={`Geen panden gevonden voor "${zoekterm}".`} />
        )}

        {zoekterm.length < 2 && (
          <div style={{ padding: 'var(--space-8)', textAlign: 'center', color: 'var(--text-muted)' }}>
            <Icon name="building-2" size={36} style={{ color: 'var(--color-border-light)', marginBottom: 'var(--space-3)', display: 'block', margin: '0 auto var(--space-3)' }} />
            <div style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--text-body)', marginBottom: 4 }}>Voer een zoekopdracht in</div>
            <div style={{ fontSize: 'var(--font-size-sm)' }}>Minimaal 2 tekens om te beginnen met zoeken</div>
          </div>
        )}

        {resultaten.length > 0 && (
          <>
            <div className="bd-table-wrap">
              <table className="bd-table">
                <thead>
                  <tr>
                    <th>Adres</th>
                    <th>Pand-ID</th>
                    <th>Perceel-ID</th>
                    <th>Gemeente</th>
                    <th style={{ textAlign: 'center' }}>Runs</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {resultaten.map(r => (
                    <tr key={r.pand_id} onClick={() => onSelectPand(r.pand_id)} style={{ cursor: 'pointer' }}>
                      <td>
                        <div className="bd-table-main">{r.adres || '-'}</div>
                        {r.postcode && <div className="bd-table-sub">{r.postcode}</div>}
                      </td>
                      <td><span className="bd-mono">{r.pand_id}</span></td>
                      <td><span className="bd-mono">{r.perceel_id || '-'}</span></td>
                      <td>{r.gemeente_naam || r.gemeente_code}</td>
                      <td style={{ textAlign: 'center' }}>
                        {r.pipeline_runs > 0
                          ? <Badge kind="info">{r.pipeline_runs}</Badge>
                          : <span style={{ color: 'var(--text-muted)' }}>-</span>}
                      </td>
                      <td>
                        <button className="tc-btn tc-btn--ghost tc-btn--sm">
                          <Icon name="arrow-right" size={14} />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            {resultaten.length === 100 && (
              <div style={{ padding: 'var(--space-3) var(--space-5)', borderTop: '1px solid var(--color-border-light)', fontSize: 'var(--font-size-xs)', color: 'var(--text-muted)' }}>
                Maximaal 100 resultaten getoond - verfijn uw zoekopdracht voor nauwkeurigere resultaten.
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}

/* ================================================================
   DETAILSCHERM
   ================================================================ */
function InfoRij({ label, waarde, mono }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
      <span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--text-muted)' }}>{label}</span>
      <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--text-body)', fontFamily: mono ? 'var(--font-family-mono)' : 'inherit', wordBreak: 'break-all' }}>{waarde || '-'}</span>
    </div>
  );
}

function BoolRij({ label, waarde }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      <span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--text-muted)' }}>{label}</span>
      <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
        <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 'var(--font-size-sm)', cursor: 'default' }}>
          <input type="radio" readOnly checked={waarde === true} style={{ accentColor: 'var(--color-primary)' }} /> Ja
        </label>
        <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 'var(--font-size-sm)', cursor: 'default' }}>
          <input type="radio" readOnly checked={waarde !== true} style={{ accentColor: 'var(--color-primary)' }} /> Nee
        </label>
      </div>
    </div>
  );
}

function ZekerheidBalk({ zekerheid }) {
  const pct = zekerheid === 'hoog' ? 90 : zekerheid === 'midden' ? 55 : 25;
  const kleur = zekerheid === 'hoog' ? 'var(--color-success)' : zekerheid === 'midden' ? 'var(--color-warning)' : 'var(--color-error)';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <div style={{ flex: 1, height: 4, background: 'var(--color-border-light)', borderRadius: 'var(--radius-full)', overflow: 'hidden' }}>
        <div style={{ width: `${pct}%`, height: '100%', background: kleur, borderRadius: 'var(--radius-full)' }} />
      </div>
      <Badge kind={ZEKERHEID_KIND[zekerheid] || 'neutral'}>{zekerheid || '-'}</Badge>
    </div>
  );
}

function fmtM2(waarde) {
  const n = Number(waarde);
  if (!Number.isFinite(n)) return null;
  return `${n.toFixed(n >= 10 ? 1 : 2)} m2`;
}

function ResultaatClusters({ clusters }) {
  const lijst = Array.isArray(clusters) ? clusters : [];
  if (lijst.length === 0) return null;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 'var(--space-3)' }}>
      <div style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
        Gevonden componenten
      </div>
      {lijst.map((cluster, idx) => {
        const extra = cluster.extra || {};
        const subtype = cluster.subtype || cluster.type || 'niet_geclassificeerd';
        const label = CONTOUR_SUBTYPE_LABEL[subtype] || subtype;
        const area = fmtM2(extra.component_area_m2);
        const nummer = extra.nummer || idx + 1;
        const toelichting = extra.toelichting;
        return (
          <div key={cluster.id || idx} style={{
            border: '1px solid var(--color-border-light)',
            borderRadius: 'var(--radius-sm)',
            background: 'var(--surface-card)',
            padding: '6px 8px',
          }}>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, alignItems: 'center', fontSize: 'var(--font-size-xs)' }}>
              <Badge kind="neutral">#{nummer}</Badge>
              <span style={{ fontWeight: 'var(--font-weight-semibold)', color: 'var(--text-body)' }}>{label}</span>
              {area && <span style={{ color: 'var(--text-muted)' }}>{area}</span>}
              {cluster.zekerheid && <Badge kind={ZEKERHEID_KIND[cluster.zekerheid] || 'neutral'}>{cluster.zekerheid}</Badge>}
              {extra.ai_status && extra.ai_status !== 'ok' && <Badge kind="warning">{extra.ai_status}</Badge>}
            </div>
            {toelichting && (
              <div style={{ marginTop: 4, fontSize: 'var(--font-size-xs)', color: 'var(--text-muted)', lineHeight: 1.45 }}>
                {toelichting}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

function AfbeeldingViewer({ resultaatId }) {
  const [status, setStatus] = React.useState('laden'); // laden | ok | geen
  const [variant, setVariant] = React.useState('default'); // default | dsm
  const [dsmBeschikbaar, setDsmBeschikbaar] = React.useState(false);

  React.useEffect(() => {
    setDsmBeschikbaar(false);
    fetch(`${API}/afbeelding/${resultaatId}?variant=dsm`, { method: 'HEAD' })
      .then(r => setDsmBeschikbaar(r.ok))
      .catch(() => setDsmBeschikbaar(false));
  }, [resultaatId]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 'var(--space-2)', minWidth: 200, minHeight: 150 }}>
      {dsmBeschikbaar && (
        <div style={{ display: 'flex', gap: 'var(--space-1)' }}>
          <button
            className="tc-btn"
            onClick={() => { setVariant('default'); setStatus('laden'); }}
            style={{ fontWeight: variant === 'default' ? 'var(--font-weight-semibold)' : 'normal' }}
          >Luchtfoto</button>
          <button
            className="tc-btn"
            onClick={() => { setVariant('dsm'); setStatus('laden'); }}
            style={{ fontWeight: variant === 'dsm' ? 'var(--font-weight-semibold)' : 'normal' }}
          >Luchtfoto + AHN</button>
        </div>
      )}
      {status === 'laden' && (
        <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--text-muted)' }}>Laden...</span>
      )}
      {status === 'geen' && (
        <div style={{ textAlign: 'center', color: 'var(--text-muted)', fontSize: 'var(--font-size-sm)' }}>
          <Icon name="image-off" size={28} style={{ display: 'block', margin: '0 auto var(--space-2)', color: 'var(--color-border-light)' }} />
          Geen afbeelding beschikbaar
        </div>
      )}
      <img
        key={variant}
        src={`${API}/afbeelding/${resultaatId}${variant === 'dsm' ? '?variant=dsm' : ''}`}
        alt={variant === 'dsm' ? 'AHN/DSM hoogtekaart' : 'Luchtfoto pipeline'}
        onLoad={() => setStatus('ok')}
        onError={() => setStatus('geen')}
        style={{
          display: status === 'ok' ? 'block' : 'none',
          maxWidth: 'min(800px, 80vw)',
          maxHeight: '70vh',
          borderRadius: 'var(--radius-sm)',
          objectFit: 'contain',
        }}
      />
    </div>
  );
}

/* Lagen-config voor de Data-detailkaart — gespiegeld op Kaart-pagina (kaart.jsx).
   id's komen overeen met laagInstellingen-keys; mapLayers/sourceId zijn de
   detail-specifieke MapLibre-id's. */
const DETAIL_LAGEN_CONFIG = [
  { id: 'panden',   label: 'Panden rondom', swatch: '#3b82f6', mapLayers: ['detail-panden-fill', 'detail-panden-outline'], sourceId: 'detail-panden' },
  ...RESULTAAT_LAGEN.map(l => ({ id: l.id, label: l.label, swatch: l.swatch, mapLayers: [l.fillId, l.lineId], sourceId: l.sourceId })),
];

function detailBoundsVanSource(map, sourceId) {
  const src = map.getSource(sourceId);
  if (!src || !src._data?.features?.length) return null;
  const bounds = new maplibregl.LngLatBounds();
  const flat = (coords) => {
    if (!coords?.length) return;
    if (typeof coords[0] === 'number') { bounds.extend(coords); return; }
    coords.forEach(flat);
  };
  src._data.features.forEach(f => { if (f.geometry) flat(f.geometry.coordinates); });
  return bounds.isEmpty() ? null : bounds;
}

function DetailLaagRij({ laag, inst, updateLaag, mapInstanceRef, onDragStart, onDragOver, onDrop, isDragOver }) {
  const aan = !!inst?.aan;
  const [expanded, setExpanded] = React.useState(false);
  const opPct = Math.round((inst?.opacity ?? 1) * 10) * 10;
  function stap(delta) {
    const huidig = Math.round((inst?.opacity ?? 1) * 10) * 10;
    updateLaag(laag.id, { opacity: Math.min(100, Math.max(10, huidig + delta)) / 100 });
  }
  return (
    <div className={'bd-layer-item' + (isDragOver ? ' drag-over' : '')}
      draggable
      onDragStart={e => { e.dataTransfer.effectAllowed = 'move'; onDragStart(laag.id); }}
      onDragOver={e => { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; onDragOver(laag.id); }}
      onDrop={e => { e.preventDefault(); onDrop(laag.id); }}
      onDragEnd={() => onDrop(null)}>
      <div className="bd-layer-row">
        <span className="bd-layer-drag" style={{ cursor: 'grab' }}><Icon name="grip-vertical" size={11} /></span>
        <span className={'bd-layer-chevron' + (expanded ? ' is-open' : '')}
          onClick={e => { e.stopPropagation(); setExpanded(v => !v); }}>
          <Icon name="chevron-right" size={9} />
        </span>
        <span className={'bd-layer-check' + (aan ? ' is-on' : '')} onClick={() => updateLaag(laag.id, { aan: !aan })}>
          {aan && <Icon name="check" size={9} style={{ color: '#fff', strokeWidth: 3 }} />}
        </span>
        <span className="bd-layer-swatch" style={{ background: laag.swatch }} />
        <span className={'bd-layer-name' + (aan ? '' : ' is-off')} onClick={() => updateLaag(laag.id, { aan: !aan })}>{laag.label}</span>
        {laag.sourceId && (
          <button className="bd-layer-zoom-btn" title="Zoom naar laag"
            onClick={e => {
              e.stopPropagation();
              const map = mapInstanceRef.current;
              if (!map) return;
              const b = detailBoundsVanSource(map, laag.sourceId);
              if (b) map.fitBounds(b, { padding: 60, animate: true });
            }}>
            <Icon name="maximize-2" size={10} />
          </button>
        )}
      </div>
      {expanded && (
        <div className="bd-layer-expand">
          <div className="bd-layer-opacity">
            <span className="bd-layer-opacity-label">Helderheid</span>
            <button className="bd-layer-opacity-btn" onClick={() => stap(-10)}>◄</button>
            <div className="bd-layer-opacity-track"><div className="bd-layer-opacity-fill" style={{ width: opPct + '%' }} /></div>
            <button className="bd-layer-opacity-btn" onClick={() => stap(10)}>►</button>
            <span className="bd-layer-opacity-val">{opPct}%</span>
          </div>
        </div>
      )}
    </div>
  );
}

function DataDetailKaart({ data, kaartmateriaal = [], onOpenPand }) {
  const mapRef = React.useRef(null);
  const mapInstanceRef = React.useRef(null);
  const dataRef = React.useRef(data);
  const laagInstellingenRef = React.useRef(null);
  const achtergrondIdRef = React.useRef(null);
  const [lagenOpen, setLagenOpen] = React.useState(true);
  const [laagInstellingen, setLaagInstellingen] = React.useState({
    achtergrond: { aan: true, opacity: 1 },
    panden: { aan: true, opacity: 0.65 },
    zonnepanelen: { aan: false, opacity: 1 },
    dakkapellen: { aan: false, opacity: 1 },
    contourafwijking: { aan: true, opacity: 1 },
  });
  const [achtergrondId, setAchtergrondId] = React.useState(null);
  const [lagenVolgorde, setLagenVolgorde] = React.useState(() => DETAIL_LAGEN_CONFIG.map(l => l.id));
  const [dragBron, setDragBron] = React.useState(null);
  const [dragDoel, setDragDoel] = React.useState(null);
  const [nietAanwezigZichtbaar, setNietAanwezigZichtbaar] = React.useState(false);

  dataRef.current = data;
  laagInstellingenRef.current = laagInstellingen;
  achtergrondIdRef.current = achtergrondId;

  const heeftDetectieAan = RESULTAAT_LAGEN.some(l => laagInstellingen[l.id]?.aan);

  function legeCollectie() {
    return { type: 'FeatureCollection', features: [] };
  }

  function eersteRing(geom) {
    if (!geom?.coordinates) return null;
    if (geom.type === 'Polygon') return geom.coordinates[0];
    if (geom.type === 'MultiPolygon') return geom.coordinates[0]?.[0];
    return null;
  }

  function boundsVoorGeom(geom) {
    const bounds = new maplibregl.LngLatBounds();
    function voegToe(coords) {
      if (!coords?.length) return;
      if (typeof coords[0] === 'number') {
        bounds.extend(coords);
        return;
      }
      coords.forEach(voegToe);
    }
    voegToe(geom?.coordinates);
    return bounds.isEmpty() ? null : bounds;
  }

  function updateLaag(id, patch) {
    setLaagInstellingen(prev => {
      const next = { ...prev, [id]: { ...prev[id], ...patch } };
      laagInstellingenRef.current = next;
      return next;
    });
  }

  function handleDetailDrag(doelId) {
    if (!dragBron || !doelId || dragBron === doelId) { setDragDoel(null); return; }
    const volgorde = [...lagenVolgorde];
    const vanIdx = volgorde.indexOf(dragBron);
    const naarIdx = volgorde.indexOf(doelId);
    if (vanIdx === -1 || naarIdx === -1) return;
    volgorde.splice(vanIdx, 1);
    volgorde.splice(naarIdx, 0, dragBron);
    setLagenVolgorde(volgorde);
    setDragBron(null); setDragDoel(null);
    const map = mapInstanceRef.current;
    if (!map) return;
    // Lijst boven = voorgrond → MapLibre van achter naar voren plaatsen
    [...volgorde].reverse().forEach((id, i, omg) => {
      const lc = DETAIL_LAGEN_CONFIG.find(l => l.id === id);
      if (!lc) return;
      const volgendConf = DETAIL_LAGEN_CONFIG.find(l => l.id === omg[i + 1]);
      const beforeId = volgendConf ? volgendConf.mapLayers[0] : undefined;
      lc.mapLayers.forEach(lid => { try { map.moveLayer(lid, beforeId); } catch (e) {} });
    });
  }

  async function laadPandenRondom(map) {
    if (!dataRef.current?.gemeente_code || !map?.getBounds) return;
    const b = map.getBounds();
    const url = `${API}/gemeenten/${dataRef.current.gemeente_code}/panden?minlng=${b.getWest()}&minlat=${b.getSouth()}&maxlng=${b.getEast()}&maxlat=${b.getNorth()}`;
    const geojson = await fetch(url).then(r => r.json()).catch(() => null);
    if (geojson && map.getSource('detail-panden')) {
      map.getSource('detail-panden').setData(geojson);
    }
  }

  async function laadResultaten(map) {
    if (!dataRef.current?.gemeente_code) return;
    for (const laag of RESULTAAT_LAGEN) {
      const zichtbaar = !!laagInstellingenRef.current?.[laag.id]?.aan;
      const geojson = await fetch(`${API}/gemeenten/${dataRef.current.gemeente_code}/resultaten-geojson?detectie_type=${laag.type}`)
        .then(r => r.json())
        .catch(() => legeCollectie());
      voegResultaatLagenToe(map, laag, geojson, zichtbaar);
    }
  }

  function toonPandPopup(map, lngLat, pandId) {
    const container = document.createElement('div');
    const titel = document.createElement('strong');
    const regel = document.createElement('div');
    const knop = document.createElement('button');
    titel.textContent = 'Pand';
    knop.className = 'bd-popup-link bd-mono';
    knop.textContent = pandId;
    knop.type = 'button';
    knop.style.border = '0';
    knop.style.background = 'transparent';
    knop.style.color = '#004494';
    knop.style.padding = '2px 0 0';
    knop.style.cursor = 'pointer';
    knop.style.fontFamily = 'var(--font-family-mono)';
    knop.onclick = () => {
      if (onOpenPand) onOpenPand(pandId);
    };
    container.appendChild(titel);
    regel.appendChild(knop);
    container.appendChild(regel);
    new maplibregl.Popup().setLngLat(lngLat).setDOMContent(container).addTo(map);
  }

  function toonResultaatPopup(map, lngLat, laag, props) {
    const subtype = props.subtype || props.type || laag.label || 'Resultaat';
    const zekerheid = props.zekerheid || '?';
    const oppervlak = props.component_area_m2 ?? props.oppervlak_m2 ?? '?';
    const kandidaat = props.kandidaat_pand === true || props.kandidaat_pand === 'true';
    new maplibregl.Popup()
      .setLngLat(lngLat)
      .setHTML(`
        <strong>${subtype.toString().toUpperCase()}</strong><br/>
        Zekerheid: ${zekerheid}<br/>
        Oppervlak: ${oppervlak} m2
        ${kandidaat ? '<br/><span style="color:#b45309;font-weight:600">⚠ Vrijstaand — mogelijk ontbrekend pand</span>' : ''}
      `)
      .addTo(map);
  }

  React.useEffect(() => {
    if (!data?.geom_wgs84 || mapInstanceRef.current) return undefined;
    const bounds = boundsVoorGeom(data.geom_wgs84);
    const ring = eersteRing(data.geom_wgs84);
    if (!bounds || !ring?.length) return undefined;

    const center = bounds.getCenter();
    const map = new maplibregl.Map({
      container: mapRef.current,
      style: { version: 8, sources: {}, layers: [], glyphs: 'https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf' },
      center: [center.lng, center.lat],
      zoom: 18,
      attributionControl: false,
    });
    map.addControl(new maplibregl.AttributionControl({ compact: true }), 'bottom-right');

    map.on('load', async () => {
      const achtergrond = kaartmateriaal.find(k => k.id === achtergrondIdRef.current)
        || kaartmateriaal.find(k => k.voor_kaart && (k.naam || '').toLowerCase().includes('luchtfoto'))
        || kaartmateriaal.find(k => k.voor_kaart)
        || kaartmateriaal.find(k => (k.naam || '').toLowerCase().includes('brt'));
      map.addSource('detail-achtergrond', { type: 'raster', tiles: [tileUrlVoorKaartmateriaal(achtergrond) || BRT_WMTS_TEMPLATE], tileSize: 256 });
      map.addLayer({ id: 'detail-achtergrond', type: 'raster', source: 'detail-achtergrond' });

      map.addSource('detail-panden', { type: 'geojson', data: legeCollectie() });
      map.addLayer({
        id: 'detail-panden-fill',
        type: 'fill',
        source: 'detail-panden',
        paint: {
          'fill-color': ['case', ['==', ['get', 'inactief'], true], '#888', '#3b82f6'],
          'fill-opacity': laagInstellingenRef.current.panden.opacity * 0.28,
        },
      });
      map.addLayer({
        id: 'detail-panden-outline',
        type: 'line',
        source: 'detail-panden',
        paint: {
          'line-color': ['case', ['==', ['get', 'inactief'], true], '#e74c3c', '#fff'],
          'line-width': 0.75,
          'line-opacity': laagInstellingenRef.current.panden.opacity,
        },
      });

      map.addSource('detail-pand-selected', {
        type: 'geojson',
        data: { type: 'Feature', geometry: data.geom_wgs84, properties: { identificatie: data.pand_id } },
      });
      map.addLayer({
        id: 'detail-pand-selected-fill',
        type: 'fill',
        source: 'detail-pand-selected',
        paint: { 'fill-color': '#004494', 'fill-opacity': 0.25 },
      });
      map.addLayer({
        id: 'detail-pand-selected-line',
        type: 'line',
        source: 'detail-pand-selected',
        paint: { 'line-color': '#004494', 'line-width': 2 },
      });

      map.on('click', 'detail-panden-fill', e => {
        const id = e.features?.[0]?.properties?.identificatie;
        if (!id || id === dataRef.current?.pand_id) return;
        toonPandPopup(map, e.lngLat, id);
      });
      map.on('mouseenter', 'detail-panden-fill', () => { map.getCanvas().style.cursor = 'pointer'; });
      map.on('mouseleave', 'detail-panden-fill', () => { map.getCanvas().style.cursor = ''; });

      await laadPandenRondom(map);
      await laadResultaten(map);

      RESULTAAT_LAGEN.forEach(laag => {
        map.on('click', laag.fillId, e => {
          const props = e.features?.[0]?.properties || {};
          toonResultaatPopup(map, e.lngLat, laag, props);
        });
        map.on('mouseenter', laag.fillId, () => { map.getCanvas().style.cursor = 'pointer'; });
        map.on('mouseleave', laag.fillId, () => { map.getCanvas().style.cursor = ''; });
      });

      map.fitBounds(bounds, { padding: 80, animate: false, maxZoom: 19 });
    });

    map.on('moveend', () => {
      laadPandenRondom(map);
    });

    function fitPand() {
      const b = boundsVoorGeom(dataRef.current?.geom_wgs84);
      if (b) map.fitBounds(b, { padding: 80, animate: true, maxZoom: 19 });
    }

    mapInstanceRef.current = map;
    window.addEventListener('bd-detail-map-fit-pand', fitPand);
    return () => {
      window.removeEventListener('bd-detail-map-fit-pand', fitPand);
      map.remove();
      mapInstanceRef.current = null;
    };
  }, [data?.pand_id]);

  React.useEffect(() => {
    const map = mapInstanceRef.current;
    if (!map || !map.isStyleLoaded()) return;
    setMapLayerVisibility(map, ['detail-achtergrond'], laagInstellingen.achtergrond.aan);
    setMapLayerVisibility(map, ['detail-panden-fill', 'detail-panden-outline'], laagInstellingen.panden.aan);
    RESULTAAT_LAGEN.forEach(laag => setMapLayerVisibility(map, [laag.fillId, laag.lineId], laagInstellingen[laag.id]?.aan));

    try {
      map.setPaintProperty('detail-panden-fill', 'fill-opacity', laagInstellingen.panden.opacity * 0.28);
      map.setPaintProperty('detail-panden-outline', 'line-opacity', laagInstellingen.panden.opacity);
      RESULTAAT_LAGEN.forEach(laag => {
        map.setPaintProperty(laag.fillId, 'fill-opacity', (laagInstellingen[laag.id]?.opacity || 1) * 0.4);
        map.setPaintProperty(laag.lineId, 'line-opacity', laagInstellingen[laag.id]?.opacity || 1);
      });
    } catch (e) {}
  }, [laagInstellingen]);

  // Standaard-achtergrond kiezen zodra kaartmateriaal geladen is (zoals Kaart-pagina)
  React.useEffect(() => {
    if (kaartmateriaal.length > 0 && achtergrondId === null) {
      const achter = kaartmateriaal.filter(k => k.voor_kaart);
      const standaard = achter.find(k => (k.naam || '').toLowerCase().includes('luchtfoto'))
        || achter.find(k => k.type === 'wmts')
        || achter[0];
      if (standaard) setAchtergrondId(standaard.id);
    }
  }, [kaartmateriaal]);

  // Achtergrondlaag wisselen bij selectie
  React.useEffect(() => {
    const map = mapInstanceRef.current;
    if (!map || achtergrondId === null || !map.isStyleLoaded()) return;
    const km = kaartmateriaal.find(k => k.id === achtergrondId);
    const tileUrl = tileUrlVoorKaartmateriaal(km);
    if (!tileUrl || !map.getSource('detail-achtergrond')) return;
    if (map.getLayer('detail-achtergrond')) map.removeLayer('detail-achtergrond');
    map.removeSource('detail-achtergrond');
    map.addSource('detail-achtergrond', { type: 'raster', tiles: [tileUrl], tileSize: 256 });
    const onderlaag = map.getLayer('detail-panden-fill') ? 'detail-panden-fill' : undefined;
    map.addLayer({ id: 'detail-achtergrond', type: 'raster', source: 'detail-achtergrond' }, onderlaag);
    setMapLayerVisibility(map, ['detail-achtergrond'], laagInstellingenRef.current.achtergrond.aan);
  }, [achtergrondId, kaartmateriaal]);

  // "Niet aanwezig"-detecties tonen/verbergen (filter op zekerheid-resultaatlagen)
  React.useEffect(() => {
    const map = mapInstanceRef.current;
    if (!map || !map.isStyleLoaded()) return;
    RESULTAAT_LAGEN.forEach(laag => {
      [laag.fillId, laag.lineId].forEach(lid => {
        if (!map.getLayer(lid)) return;
        try { map.setFilter(lid, nietAanwezigZichtbaar ? null : ['==', ['get', 'aanwezig'], true]); } catch (e) {}
      });
    });
  }, [nietAanwezigZichtbaar]);

  return (
    <div style={{ flex: 1, position: 'relative', overflow: 'hidden' }}>
      <div ref={mapRef} style={{ width: '100%', height: '100%' }} />
      <button
        className={'bd-tool-btn' + (lagenOpen ? ' is-active' : '')}
        onClick={() => setLagenOpen(v => !v)}
        title="Kaartlagen"
        style={{ position: 'absolute', top: 14, right: 14, zIndex: 12, background: 'var(--surface-card)' }}
      >
        <Icon name="layers" size={14} />
      </button>
      {lagenOpen && (
        <div className="bd-layers-panel" style={{ position: 'absolute', right: 14, top: 52, width: 284, maxHeight: 'calc(100% - 80px)', zIndex: 11 }}>
          <div className="bd-layers-header">
            <span className="bd-layers-title"><Icon name="layers" size={15} /> Kaartlagen</span>
            <button className="bd-layers-close" onClick={() => setLagenOpen(false)} title="Sluiten"><Icon name="x" size={13} /></button>
          </div>
          <div className="bd-layers-list">

            {/* Achtergrondlagen uit kaartmateriaal (Databeheer) */}
            {kaartmateriaal.filter(k => k.voor_kaart).length > 0 && (
              <div style={{ padding: '6px 14px 4px', borderBottom: '1px solid #f0f4f8' }}>
                <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--text-muted)', marginBottom: 4 }}>Achtergrond</div>
                {kaartmateriaal.filter(k => k.voor_kaart).map(k => (
                  <div key={k.id} className="bd-layer-row" style={{ padding: '4px 0' }} onClick={() => setAchtergrondId(k.id)}>
                    <span className={'bd-layer-check' + (achtergrondId === k.id ? ' is-on' : '')}>
                      {achtergrondId === k.id && <Icon name="check" size={9} style={{ color: '#fff', strokeWidth: 3 }} />}
                    </span>
                    <span className="bd-layer-swatch" style={{ background: '#94a3b8', borderRadius: '50%' }} />
                    <span className={'bd-layer-name' + (achtergrondId === k.id ? '' : ' is-off')}>{k.naam}{k.jaar ? ` (${k.jaar})` : ''}</span>
                  </div>
                ))}
              </div>
            )}

            {/* Lagen — sleep om volgorde te wijzigen (boven = voorgrond) */}
            {lagenVolgorde.map(id => {
              const laag = DETAIL_LAGEN_CONFIG.find(l => l.id === id);
              if (!laag) return null;
              return (
                <DetailLaagRij key={laag.id} laag={laag}
                  inst={laagInstellingen[laag.id]}
                  updateLaag={updateLaag}
                  mapInstanceRef={mapInstanceRef}
                  onDragStart={setDragBron}
                  onDragOver={setDragDoel}
                  onDrop={handleDetailDrag}
                  isDragOver={dragDoel === laag.id}
                />
              );
            })}

            {/* Zekerheidslegenda — identiek aan Kaart-pagina */}
            {heeftDetectieAan && (
              <div style={{ padding: '8px 14px 10px', borderTop: '1px solid var(--color-border-light)', marginTop: 4 }}>
                <div style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--text-muted)', marginBottom: 6 }}>Zekerheid detectie</div>
                <div style={{ fontSize: 10, color: 'var(--text-muted)', textTransform: 'uppercase', marginBottom: 3 }}>Aanwezig</div>
                {[{ k: '#1a9e4a', l: 'Hoog' }, { k: '#f1c40f', l: 'Midden' }, { k: '#e67e22', l: 'Laag' }].map(({ k, l }) => (
                  <div key={l} className="bd-layer-legend-item"><div className="bd-layer-legend-swatch" style={{ background: k }} /><span className="bd-layer-legend-label">{l}</span></div>
                ))}
                <div style={{ height: 1, background: 'var(--color-border-light)', margin: '6px 0' }} />
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 3 }}>
                  <span style={{ fontSize: 10, color: 'var(--text-muted)', textTransform: 'uppercase' }}>Niet aanwezig</span>
                  <label style={{ display: 'flex', alignItems: 'center', gap: 3, cursor: 'pointer', fontSize: 10, color: 'var(--text-muted)' }}>
                    <input type="checkbox" checked={nietAanwezigZichtbaar} onChange={e => setNietAanwezigZichtbaar(e.target.checked)} style={{ accentColor: 'var(--color-primary)', width: 11, height: 11 }} />
                    toon
                  </label>
                </div>
                {[{ k: '#c0392b', l: 'Hoog' }, { k: '#e74c3c', l: 'Midden' }, { k: '#f1948a', l: 'Laag' }].map(({ k, l }) => (
                  <div key={l} className="bd-layer-legend-item" style={{ opacity: nietAanwezigZichtbaar ? 1 : 0.3 }}>
                    <div className="bd-layer-legend-swatch" style={{ background: k }} /><span className="bd-layer-legend-label">{l}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

function DataDetailScherm({ pandId, onTerug, kaartmateriaal = [], onOpenPand, onNaarReview }) {
  const [data, setData] = React.useState(null);
  const [laden, setLaden] = React.useState(true);
  const [fout, setFout] = React.useState(null);
  const [vboOpen, setVboOpen] = React.useState(false);
  const [afbeeldingModal, setAfbeeldingModal] = React.useState(null); // resultaat_id

  // Sleepbaar paneel
  const PANEL_MIN = 260; const PANEL_MAX = 620;
  const [panelWidth, setPanelWidth] = React.useState(() => {
    const saved = parseInt(localStorage.getItem('bd-data-panel-width'));
    return (saved >= PANEL_MIN && saved <= PANEL_MAX) ? saved : 380;
  });
  const panelWidthRef = React.useRef(panelWidth);
  panelWidthRef.current = panelWidth;
  const draggingRef = React.useRef(false);
  const startXRef = React.useRef(0);
  const startWRef = React.useRef(0);

  function onDragStart(e) {
    draggingRef.current = true;
    startXRef.current = e.clientX;
    startWRef.current = panelWidthRef.current;
    document.body.style.userSelect = 'none';
    document.body.style.cursor = 'col-resize';
    function onMove(e) {
      if (!draggingRef.current) return;
      const delta = e.clientX - startXRef.current;
      const newW = Math.max(PANEL_MIN, Math.min(PANEL_MAX, startWRef.current + delta));
      setPanelWidth(newW);
    }
    function onUp() {
      draggingRef.current = false;
      document.body.style.userSelect = '';
      document.body.style.cursor = '';
      localStorage.setItem('bd-data-panel-width', panelWidthRef.current);
      document.removeEventListener('mousemove', onMove);
      document.removeEventListener('mouseup', onUp);
    }
    document.addEventListener('mousemove', onMove);
    document.addEventListener('mouseup', onUp);
  }

  React.useEffect(() => {
    setLaden(true); setFout(null);
    Promise.all([
      fetch(`${API}/data/pand/${encodeURIComponent(pandId)}`)
      .then(r => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); })
      ,
      fetch(`${API}/perceel-objecten?gekoppeld_pand_id=${encodeURIComponent(pandId)}`)
        .then(r => r.ok ? r.json() : [])
        .catch(() => []),
    ])
      .then(([pandData, perceelObjecten]) => setData({...pandData, perceel_objecten: Array.isArray(perceelObjecten) ? perceelObjecten : []}))
      .catch(e => setFout(e.message))
      .finally(() => setLaden(false));
  }, [pandId]);

  async function verwijderResultaat(res) {
    if (!confirm(`Detectieresultaat #${res.id} verwijderen? Bijbehorende vlakken, review en afbeelding gaan ook weg.`)) return;
    const r = await fetch(`${API}/resultaten/${res.id}`, { method: 'DELETE' });
    if (r.ok) {
      const vernieuwd = await fetch(`${API}/data/pand/${encodeURIComponent(pandId)}`).then(r => r.json());
      setData(prev => ({...vernieuwd, perceel_objecten: prev?.perceel_objecten || []}));
    } else {
      alert('Verwijderen mislukt.');
    }
  }

  if (laden) return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%', color: 'var(--text-muted)' }}>
      <Icon name="loader" size={24} style={{ animation: 'spin 1s linear infinite', marginRight: 8 }} />
      Pandgegevens laden...
    </div>
  );
  if (fout) return (
    <div className="bd-page"><Alert kind="error">Fout bij ophalen pandgegevens: {fout}</Alert></div>
  );
  if (!data) return null;

  const heeftResultaten = data.resultaten && data.resultaten.length > 0;
  const heeftPerceelObjecten = data.perceel_objecten && data.perceel_objecten.length > 0;

  return (
    <div style={{ display: 'flex', height: '100%', overflow: 'hidden' }}>

      {/* AFBEELDING MODAL */}
      {afbeeldingModal !== null && (
        <div
          onClick={() => setAfbeeldingModal(null)}
          style={{
            position: 'fixed', inset: 0, zIndex: 1000,
            background: 'rgba(0,0,0,0.75)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}
        >
          <div
            onClick={e => e.stopPropagation()}
            style={{
              background: 'var(--surface-card)',
              borderRadius: 'var(--radius-md)',
              padding: 'var(--space-4)',
              maxWidth: '90vw', maxHeight: '90vh',
              display: 'flex', flexDirection: 'column', gap: 'var(--space-3)',
              boxShadow: '0 8px 32px rgba(0,0,0,0.4)',
            }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)' }}>
              <Icon name="image" size={14} style={{ color: 'var(--color-primary)' }} />
              <span style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)', flex: 1 }}>
                Pipeline-afbeelding
              </span>
              <button
                className="tc-icon-btn"
                onClick={() => setAfbeeldingModal(null)}
                title="Sluiten"
              >
                <Icon name="x" size={16} />
              </button>
            </div>
            <AfbeeldingViewer resultaatId={afbeeldingModal} />
          </div>
        </div>
      )}

      {/* LEFT PANEL */}
      <div style={{
        width: panelWidth,
        flexShrink: 0,
        background: 'var(--surface-card)',
        borderRight: '1px solid var(--color-border-light)',
        display: 'flex',
        flexDirection: 'column',
        overflow: 'hidden',
      }}>
        {/* Panel header */}
        <div style={{
          padding: 'var(--space-4) var(--space-5)',
          borderBottom: '1px solid var(--color-border-light)',
          display: 'flex',
          alignItems: 'center',
          gap: 'var(--space-3)',
          flexShrink: 0,
          background: 'var(--surface-card)',
        }}>
          <button className="tc-icon-btn" onClick={onTerug} title="Terug naar zoeken">
            <Icon name="arrow-left" size={16} />
          </button>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 'var(--font-size-xs)', color: 'var(--text-muted)', marginBottom: 2 }}>
              Pand
            </div>
            <div style={{
              fontFamily: 'var(--font-family-mono)',
              fontSize: 'var(--font-size-sm)',
              fontWeight: 'var(--font-weight-semibold)',
              color: 'var(--text-body)',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            }}>
              {data.pand_id}
            </div>
          </div>
          {data.rd_x != null && data.rd_y != null && (
            <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
              <button className="tc-btn tc-btn--ghost tc-btn--sm" title="Open Street Smart (Cyclomedia) op deze locatie"
                onClick={() => {
                  const b = 60;
                  const mq = `${(data.rd_x - b).toFixed(2)};${(data.rd_y - b).toFixed(2)};${(data.rd_x + b).toFixed(2)};${(data.rd_y + b).toFixed(2)}`;
                  window.open(`https://streetsmart.cyclomedia.com/?mq=${mq}&msrs=EPSG:28992`, '_blank', 'noopener');
                }}>
                <Icon name="camera" size={14} /> Streetsmart
              </button>
              <button className="tc-btn tc-btn--ghost tc-btn--sm" title="Open BAG Viewer (Kadaster) op deze locatie"
                onClick={() => {
                  window.open(`https://bagviewer.kadaster.nl/lvbag/bag-viewer/?theme=${encodeURIComponent('BRT Achtergrond')}&geometry.x=${data.rd_x}&geometry.y=${data.rd_y}&zoomlevel=13`, '_blank', 'noopener');
                }}>
                <Icon name="map" size={14} /> BAG Viewer
              </button>
            </div>
          )}
          <Badge kind={data.status === 'Pand in gebruik' ? 'success' : 'neutral'}>
            {data.status || 'Onbekend'}
          </Badge>
        </div>

        {/* Scrollable content */}
        <div style={{ flex: 1, overflowY: 'auto', padding: 'var(--space-5)' }}>

          {/* Sectie: Pandgegevens */}
          <div style={{ marginBottom: 'var(--space-6)' }}>
            <div style={{
              display: 'flex',
              alignItems: 'center',
              gap: 'var(--space-2)',
              marginBottom: 'var(--space-4)',
              paddingBottom: 'var(--space-2)',
              borderBottom: '1px solid var(--color-border-light)',
            }}>
              <Icon name="building-2" size={14} style={{ color: 'var(--color-primary)' }} />
              <span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-muted)' }}>Pandgegevens</span>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)' }}>
              <InfoRij label="Identificatie" waarde={data.pand_id} mono />
              <InfoRij label="Bouwjaar" waarde={data.bouwjaar} />
              <InfoRij label="Gemeente" waarde={data.gemeente_naam ? `${data.gemeente_naam} (${data.gemeente_code})` : data.gemeente_code} />
              <InfoRij label="Status" waarde={data.status} />
              <InfoRij label="Brondocument" waarde={data.document_nummer} mono />
              <InfoRij label="Brondocument datum" waarde={data.document_datum} />
              <InfoRij label="Registratiedatum" waarde={data.begin_geldigheid} />
              {data.perceel_id && <InfoRij label="Perceel-ID" waarde={data.perceel_id} mono />}
            </div>
          </div>

          {/* Sectie: VBO's */}
          {data.vbos && data.vbos.length > 0 && (
            <div style={{ marginBottom: 'var(--space-6)' }}>
              <button
                onClick={() => setVboOpen(v => !v)}
                style={{
                  width: '100%',
                  display: 'flex',
                  alignItems: 'center',
                  gap: 'var(--space-2)',
                  background: 'none',
                  border: 'none',
                  borderBottom: '1px solid var(--color-border-light)',
                  padding: '0 0 var(--space-2)',
                  marginBottom: vboOpen ? 'var(--space-3)' : 0,
                  cursor: 'pointer',
                  color: 'inherit',
                }}
              >
                <Icon name="home" size={14} style={{ color: 'var(--color-primary)' }} />
                <span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-muted)', flex: 1, textAlign: 'left' }}>
                  Verblijfsobjecten
                </span>
                <Badge kind="info">{data.vbos.length}</Badge>
                <Icon name={vboOpen ? 'chevron-up' : 'chevron-down'} size={14} style={{ color: 'var(--text-muted)' }} />
              </button>
              {vboOpen && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
                  {data.vbos.map(v => (
                    <div key={v.vbo_id} style={{
                      background: 'var(--surface-app)',
                      borderRadius: 'var(--radius-md)',
                      padding: 'var(--space-3)',
                      borderLeft: '3px solid var(--color-primary)',
                    }}>
                      <div style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-xs)', color: 'var(--text-muted)', marginBottom: 4 }}>{v.vbo_id}</div>
                      {v.adres && <div style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--text-body)' }}>{v.adres}</div>}
                      {v.postcode && <div style={{ fontSize: 'var(--font-size-xs)', color: 'var(--text-muted)' }}>{v.postcode} {v.woonplaats}</div>}
                      {v.gebruiksdoel && <div style={{ marginTop: 4 }}><Badge kind="neutral">{v.gebruiksdoel}</Badge></div>}
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Sectie: Perceel-objecten */}
          <div style={{ marginBottom: 'var(--space-6)' }}>
            <div style={{
              display: 'flex',
              alignItems: 'center',
              gap: 'var(--space-2)',
              marginBottom: 'var(--space-4)',
              paddingBottom: 'var(--space-2)',
              borderBottom: '1px solid var(--color-border-light)',
            }}>
              <Icon name="shapes" size={14} style={{ color: 'var(--color-primary)' }} />
              <span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-muted)', flex: 1 }}>
                Perceel-objecten
              </span>
              {heeftPerceelObjecten && <Badge kind="info">{data.perceel_objecten.length}</Badge>}
            </div>
            {!heeftPerceelObjecten ? (
              <div style={{ textAlign: 'center', padding: 'var(--space-4) 0', color: 'var(--text-muted)', fontSize: 'var(--font-size-sm)' }}>
                Geen gekoppelde perceel-objecten voor dit pand.
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
                {data.perceel_objecten.map(obj => (
                  <div key={obj.id} style={{
                    background: 'var(--surface-app)',
                    borderRadius: 'var(--radius-md)',
                    padding: 'var(--space-3) var(--space-4)',
                    border: '1px solid var(--color-border-light)',
                  }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)', marginBottom: 'var(--space-2)' }}>
                      <Badge kind={obj.object_type === 'contourafwijking' ? 'warning' : obj.object_type === 'zonnepanelen' ? 'info' : 'neutral'}>
                        {obj.object_type || 'object'}
                      </Badge>
                      <span style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)', flex: 1 }}>
                        {CONTOUR_SUBTYPE_LABEL[obj.subtype] || obj.subtype || 'Onbekend'}
                      </span>
                      <Badge kind={ZEKERHEID_KIND[obj.zekerheid] || 'neutral'}>{obj.zekerheid || '-'}</Badge>
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)', fontSize: 'var(--font-size-xs)', color: 'var(--text-muted)' }}>
                      <span>Perceel: <span className="bd-mono">{obj.perceel_id || '-'}</span></span>
                      <span>Pand: <span className="bd-mono">{obj.gekoppeld_pand_id || '-'}</span></span>
                      <span>Oppervlak: <span className="bd-mono">{obj.oppervlakte_m2 != null ? `${Number(obj.oppervlakte_m2).toFixed(1)} m2` : '-'}</span></span>
                      <span>Afstand: <span className="bd-mono">{obj.afstand_tot_pand_m != null ? `${Number(obj.afstand_tot_pand_m).toFixed(1)} m` : '-'}</span></span>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Sectie: Detectieresultaten */}
          <div>
            <div style={{
              display: 'flex',
              alignItems: 'center',
              gap: 'var(--space-2)',
              marginBottom: 'var(--space-4)',
              paddingBottom: 'var(--space-2)',
              borderBottom: '1px solid var(--color-border-light)',
            }}>
              <Icon name="scan-search" size={14} style={{ color: 'var(--color-primary)' }} />
              <span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-muted)', flex: 1 }}>
                Detectieresultaten
              </span>
              {heeftResultaten && <Badge kind="info">{data.resultaten.length}</Badge>}
            </div>

            {!heeftResultaten ? (
              <div style={{ textAlign: 'center', padding: 'var(--space-6) 0', color: 'var(--text-muted)', fontSize: 'var(--font-size-sm)' }}>
                <Icon name="inbox" size={28} style={{ color: 'var(--color-border-light)', display: 'block', margin: '0 auto var(--space-2)' }} />
                Geen detectieresultaten voor dit pand.
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
                {data.resultaten.map(res => {
                  const analyseStatus = res.analyse_status || 'ok';
                  const aanwezigKind = res.aanwezig === true ? 'success' : res.aanwezig === false ? 'error' : analyseStatus !== 'ok' ? 'warning' : 'neutral';
                  return (
                    <div key={res.id} style={{
                    background: 'var(--surface-app)',
                    borderRadius: 'var(--radius-md)',
                    padding: 'var(--space-3) var(--space-4)',
                    border: '1px solid var(--color-border-light)',
                  }}>
                    {/* Result header */}
                    <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)', marginBottom: 'var(--space-2)' }}>
                      <Icon name={DETECTIE_ICON[res.detectie_type] || 'scan'} size={14} style={{ color: 'var(--color-primary)', flexShrink: 0 }} />
                      <span style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)', flex: 1 }}>
                        {DETECTIE_LABEL[res.detectie_type] || res.detectie_type}
                      </span>
                      <Badge kind={aanwezigKind}>
                        {res.aanwezig === true ? 'Aanwezig' : res.aanwezig === false ? 'Niet aanwezig' : 'Onbekend'}
                      </Badge>
                      {analyseStatus !== 'ok' && <Badge kind="warning">{res.fout_code || analyseStatus}</Badge>}
                    </div>

                    {/* Zekerheid */}
                    {res.zekerheid && (
                      <div style={{ marginBottom: 'var(--space-2)' }}>
                        <ZekerheidBalk zekerheid={res.zekerheid} />
                      </div>
                    )}

                    {/* Toelichting */}
                    {res.toelichting && (
                      <div style={{ fontSize: 'var(--font-size-xs)', color: 'var(--text-muted)', marginBottom: 'var(--space-2)', lineHeight: 1.5, background: 'var(--color-primary-light)', borderRadius: 'var(--radius-sm)', padding: '6px 8px' }}>
                        {res.toelichting}
                      </div>
                    )}

                    <ResultaatClusters clusters={res.clusters} />

                    {/* Meta */}
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-3)', fontSize: 'var(--font-size-xs)', color: 'var(--text-muted)', marginBottom: 'var(--space-3)' }}>
                      {res.run_datum && <span><Icon name="calendar" size={10} style={{ marginRight: 3 }} />{fmtDate(res.run_datum)}</span>}
                      {res.ai_model && <span><Icon name="cpu" size={10} style={{ marginRight: 3 }} />{res.ai_model}</span>}
                      {res.prompt_naam && <span><Icon name="file-text" size={10} style={{ marginRight: 3 }} />{res.prompt_naam}</span>}
                      {res.finish_reason && <span>finish: {res.finish_reason}</span>}
                      {res.brondocument && <span><Icon name="satellite" size={10} style={{ marginRight: 3 }} />{res.brondocument}</span>}
                    </div>

                    {/* Afbeelding knop */}
                    <div style={{ marginBottom: 'var(--space-2)' }}>
                      <button
                        title="Toon afbeelding uit de pipeline"
                        onClick={() => setAfbeeldingModal(res.id)}
                        style={{
                          padding: '4px 10px',
                          borderRadius: 'var(--radius-sm)',
                          border: '1px solid var(--color-border-light)',
                          fontSize: 'var(--font-size-xs)',
                          fontWeight: 'var(--font-weight-semibold)',
                          cursor: 'pointer',
                          display: 'flex', alignItems: 'center', gap: 4,
                          background: 'var(--surface-card)',
                          color: 'var(--text-muted)',
                        }}
                      >
                        <Icon name="image" size={12} /> Afbeelding
                      </button>
                    </div>

                    {/* Ruwe AI-tekst (uitklapbaar) */}
                    {res.ai_ruw_tekst && (
                      <details style={{ marginBottom: 'var(--space-2)' }}>
                        <summary style={{ cursor: 'pointer', fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--text-muted)' }}>Ruwe AI-tekst</summary>
                        <pre style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word', fontSize: 'var(--font-size-xs)', maxHeight: 240, overflow: 'auto', margin: '6px 0 0', background: 'var(--surface-subtle)', padding: 8, borderRadius: 'var(--radius-sm)', border: '1px solid var(--color-border-light)' }}>{res.ai_ruw_tekst}</pre>
                      </details>
                    )}

                    {/* Acties */}
                    <div style={{ display: 'flex', gap: 'var(--space-2)', alignItems: 'center' }}>
                      <button
                        title="Open dit resultaat in het Review-scherm"
                        onClick={() => onNaarReview && onNaarReview(res.id)}
                        style={{
                          padding: '4px 10px',
                          borderRadius: 'var(--radius-sm)',
                          border: '1px solid var(--color-primary)',
                          fontSize: 'var(--font-size-xs)',
                          fontWeight: 'var(--font-weight-semibold)',
                          cursor: 'pointer',
                          display: 'flex', alignItems: 'center', gap: 4,
                          background: 'var(--color-primary)',
                          color: '#fff',
                        }}
                      >
                        <Icon name="square-pen" size={12} /> Beoordelen in Review
                      </button>
                      {res.beoordeling && (
                        <Badge kind={res.beoordeling === 'correct' ? 'success' : res.beoordeling === 'onzeker' ? 'warning' : 'error'}>
                          {res.beoordeling}
                        </Badge>
                      )}
                      <button
                        title="Resultaat verwijderen"
                        onClick={() => verwijderResultaat(res)}
                        style={{
                          padding: '4px 10px',
                          borderRadius: 'var(--radius-sm)',
                          border: '1px solid #f5c6be',
                          fontSize: 'var(--font-size-xs)',
                          fontWeight: 'var(--font-weight-semibold)',
                          cursor: 'pointer',
                          display: 'flex', alignItems: 'center', gap: 4,
                          background: 'var(--surface-card)',
                          color: 'var(--color-danger)',
                          marginLeft: 'auto',
                        }}
                      >
                        <Icon name="trash-2" size={12} /> Verwijderen
                      </button>
                    </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* DRAG HANDLE */}
      <div
        onMouseDown={onDragStart}
        style={{
          width: 5,
          flexShrink: 0,
          cursor: 'col-resize',
          background: 'transparent',
          position: 'relative',
          zIndex: 10,
        }}
        title="Sleep om breedte aan te passen"
      >
        <div style={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%,-50%)',
          width: 4,
          height: 40,
          borderRadius: 2,
          background: 'var(--color-border-light)',
          transition: 'background 120ms',
        }} />
      </div>

      {/* RIGHT PANEL: MAP */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', background: '#e8eef4' }}>
        <div style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: '0 var(--space-5)',
          background: 'var(--surface-card)',
          borderBottom: '1px solid var(--color-border-light)',
          flexShrink: 0,
          height: 46,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <Icon name="map" size={14} style={{ color: 'var(--color-primary)' }} />
            <span style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)' }}>Kaart</span>
            <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-xs)', color: 'var(--text-muted)' }}>{data.pand_id}</span>
          </div>
          <button className="tc-icon-btn" title="Zoom naar pand" onClick={() => window.dispatchEvent(new CustomEvent('bd-detail-map-fit-pand'))}>
            <Icon name="maximize-2" size={16} />
          </button>
        </div>

        <DataDetailKaart
          data={data}
          kaartmateriaal={kaartmateriaal}
          onOpenPand={onOpenPand}
        />

        <div style={{
          display: 'flex',
          alignItems: 'center',
          gap: 'var(--space-5)',
          padding: 'var(--space-2) var(--space-5)',
          background: 'var(--surface-card)',
          borderTop: '1px solid var(--color-border-light)',
          flexShrink: 0,
          fontSize: 'var(--font-size-xs)',
          color: 'var(--text-muted)',
        }}>
          <span style={{ fontWeight: 'var(--font-weight-semibold)', textTransform: 'uppercase', letterSpacing: '0.06em', marginRight: 'var(--space-2)' }}>Legenda</span>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <div style={{ width: 12, height: 12, borderRadius: 2, background: '#004494', opacity: 0.35 }} />
            Geselecteerd pand
          </div>
          <span style={{ color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Zekerheid:</span>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <div style={{ width: 12, height: 12, borderRadius: 2, background: '#1a9e4a' }} /> Hoog
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <div style={{ width: 12, height: 12, borderRadius: 2, background: '#f1c40f' }} /> Midden
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <div style={{ width: 12, height: 12, borderRadius: 2, background: '#e67e22' }} /> Laag
          </div>
          <div style={{ marginLeft: 'auto', fontFamily: 'var(--font-family-mono)', opacity: 0.5 }}>
            PDOK BRT / Kadastrale kaart v5
          </div>
        </div>
      </div>
    </div>
  );
}

/* ================================================================
   ROOT COMPONENT
   ================================================================ */
function SchermData({ kaartmateriaal, pandId, onPandChange, onNaarReview }) {
  if (pandId) {
    return <DataDetailScherm
      pandId={pandId}
      kaartmateriaal={kaartmateriaal}
      onOpenPand={onPandChange}
      onNaarReview={onNaarReview}
      onTerug={() => onPandChange(null)}
    />;
  }
  return <DataZoekScherm onSelectPand={onPandChange} />;
}

Object.assign(window, { SchermData, DataDetailScherm, DataZoekScherm });
