// ResultList — server-gepagineerde lijst (50/pagina), niet meer virtual.
// Sort wordt nu server-side gedaan (sort-key gaat naar parent → /vergunningen).
// Records komen uit /v1/vergunningen — flat schema, lon/lat als plain props.

const ROW_HEIGHT = 76;

// Lookups uit waardelijsten (kleur/label zitten niet meer in record-payload).
const TB_BY_CODE = WAARDELIJSTEN.type_besluit.reduce((m, t) => { m[t.code] = t; return m; }, {});
const AC_BY_CODE = WAARDELIJSTEN.activiteit_code.reduce((m, a) => { m[a.code] = a; return m; }, {});

function ResultList({ records, total, limit, offset, loading, onPrev, onNext, selectedId, onSelect, mapCenter, sortBy, setSortBy }) {
  const containerRef = React.useRef(null);
  const hasPrev = offset > 0;
  const hasNext = offset + records.length < total;
  const rangeFrom = total === 0 ? 0 : offset + 1;
  const rangeTo = offset + records.length;

  // Scroll selected into view when selection changes externally
  React.useLayoutEffect(() => {
    if (!selectedId || !containerRef.current) return;
    const idx = records.findIndex((r) => r.koop_id === selectedId);
    if (idx < 0) return;
    const top = idx * ROW_HEIGHT;
    const bottom = top + ROW_HEIGHT;
    const sT = containerRef.current.scrollTop;
    const sB = sT + containerRef.current.clientHeight;
    if (top < sT || bottom > sB) {
      containerRef.current.scrollTo({ top: Math.max(0, top - 80), behavior: 'smooth' });
    }
  }, [selectedId, records]);

  // Reset scroll naar boven bij paginatie/sort/filter-wijziging.
  React.useLayoutEffect(() => {
    if (containerRef.current) containerRef.current.scrollTop = 0;
  }, [offset, sortBy]);

  return (
    <div className="flex flex-col h-full w-full bg-white border-t border-slate-200">
      {/* Toolbar */}
      <div className="flex items-center justify-between px-4 py-2 border-b border-slate-200 bg-[#FAFAF7] text-[12px]">
        <div className="text-slate-700 tabular-nums flex items-center gap-2">
          {total === 0 ? (
            <span>Geen resultaten</span>
          ) : (
            <span>
              <span className="font-medium">{fmt.number(rangeFrom)}</span>–
              <span className="font-medium">{fmt.number(rangeTo)}</span>
              <span className="text-slate-500"> van </span>
              <span className="font-medium">{fmt.number(total)}</span>
            </span>
          )}
          {loading && (
            <span
              aria-label="Bezig met laden"
              className="inline-block w-2 h-2 rounded-full bg-emerald-900 animate-pulse"
            ></span>
          )}
        </div>
        <label className="flex items-center gap-2 text-slate-600">
          <span>Sorteer:</span>
          <select
            value={sortBy}
            onChange={(e) => setSortBy(e.target.value)}
            className="bg-white border border-slate-200 rounded px-1.5 py-0.5 text-[12px] focus:outline-none focus:border-emerald-900"
          >
            <option value="datum">datum publicatie (recent eerst)</option>
            <option value="datum_asc">datum publicatie (oud eerst)</option>
            <option value="ontvangst">datum aanvraag</option>
            <option value="bg">bevoegd gezag (A–Z)</option>
          </select>
        </label>
      </div>

      {/* List */}
      <div
        ref={containerRef}
        className="flex-1 overflow-y-auto relative"
        role="listbox"
        aria-label="Vergunningkennisgevingen"
      >
        {total === 0 && !loading && (
          <div className="px-6 py-12 text-center text-[13px] text-slate-600 max-w-md mx-auto">
            <div className="font-serif text-slate-900 text-[15px] mb-1">Geen vergunningen</div>
            <p>Geen vergunningen binnen huidige selectie. Verwijder een filter of zoom verder uit.</p>
          </div>
        )}
        {records.map((r) => (
          <ListRow
            key={r.koop_id}
            rec={r}
            selected={r.koop_id === selectedId}
            onClick={() => onSelect(r.koop_id)}
            distance={r.lat != null && r.lon != null && mapCenter ? haversineKm(mapCenter, { lat: r.lat, lon: r.lon }) : null}
          />
        ))}
      </div>

      {/* Pagination footer */}
      {total > 0 && (
        <div className="flex items-center justify-between px-4 py-2 border-t border-slate-200 bg-[#FAFAF7] text-[12px]">
          <button
            type="button"
            onClick={onPrev}
            disabled={!hasPrev}
            className="px-2.5 py-1 rounded border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 hover:border-slate-300 disabled:opacity-40 disabled:cursor-not-allowed focus:outline-none focus:border-emerald-900"
          >
            ← Vorige {fmt.number(limit)}
          </button>
          <div className="text-slate-500 tabular-nums">
            Pagina {Math.floor(offset / limit) + 1} van {Math.max(1, Math.ceil(total / limit))}
          </div>
          <button
            type="button"
            onClick={onNext}
            disabled={!hasNext}
            className="px-2.5 py-1 rounded border border-slate-200 bg-white text-slate-700 hover:bg-slate-50 hover:border-slate-300 disabled:opacity-40 disabled:cursor-not-allowed focus:outline-none focus:border-emerald-900"
          >
            Volgende {fmt.number(limit)} →
          </button>
        </div>
      )}
    </div>
  );
}

function ListRow({ rec, selected, onClick, distance }) {
  const tb = TB_BY_CODE[rec.type_besluit];
  const tbColor = (tb && tb.color) || '#6B7280';
  const tbLabel = (tb && tb.label) || rec.type_besluit;
  const acLabel = (AC_BY_CODE[rec.activiteit_code] && AC_BY_CODE[rec.activiteit_code].label) || rec.activiteit_code;
  return (
    <button
      type="button"
      onClick={onClick}
      style={{ height: ROW_HEIGHT }}
      className={`w-full flex items-stretch gap-3 pl-3 pr-3 border-b border-slate-100 text-left transition-colors
        ${selected ? 'bg-emerald-900/[0.06]' : 'hover:bg-slate-50'}
        focus:outline-none focus:bg-emerald-900/[0.08]`}
      aria-selected={selected}
      role="option"
    >
      {/* Colored stripe */}
      <span
        aria-hidden
        className="w-[3px] shrink-0 -my-px rounded-sm"
        style={{ background: tbColor }}
      ></span>

      {/* Body — full-width title + metadata-row */}
      <div className="flex-1 min-w-0 py-2 flex flex-col justify-center gap-1">
        {/* Title row: title + datum (right) */}
        <div className="flex items-baseline gap-3">
          <div className="flex-1 min-w-0 text-[13.5px] text-slate-900 leading-snug truncate" title={rec.titel}>
            {rec.titel}
          </div>
          <div className="shrink-0 text-[11.5px] text-slate-500 tabular-nums">
            {fmt.dateShort(rec.datum_publicatie)}
          </div>
        </div>

        {/* Meta row */}
        <div className="flex items-center gap-2 text-[11px] min-w-0">
          <span
            className="inline-flex items-center text-[10px] uppercase tracking-wider font-medium px-1.5 py-0.5 rounded-sm shrink-0"
            style={{ background: tbColor + '1A', color: tbColor }}
          >
            {tbLabel}
          </span>
          <span className="text-slate-600 shrink-0">{acLabel}</span>
          <span className="text-slate-200" aria-hidden>·</span>
          <span className="text-slate-700 truncate min-w-0">{rec.bg_naam}</span>
          {rec.woonplaats && rec.woonplaats !== rec.bg_naam && (
            <>
              <span className="text-slate-200 shrink-0" aria-hidden>·</span>
              <span className="text-slate-500 shrink-0">{rec.woonplaats}</span>
            </>
          )}
          {rec.zaaknummer_bg && (
            <span className="hidden xl:flex items-center gap-2 shrink-0">
              <span className="text-slate-200" aria-hidden>·</span>
              <span className="text-slate-400 font-mono text-[10.5px]">{rec.zaaknummer_bg}</span>
            </span>
          )}
          <span className="flex-1"></span>
          {distance != null && Number.isFinite(distance) && (
            <span className="text-slate-500 tabular-nums shrink-0">{fmt.distance(distance)}</span>
          )}
          <svg viewBox="0 0 12 12" className="w-3 h-3 text-slate-400 shrink-0" aria-hidden>
            <path d="M4.5 3 L7.5 6 L4.5 9" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </div>
      </div>
    </button>
  );
}

Object.assign(window, { ResultList });
