// Copyright (c) 2026 PowerOn AG
// All rights reserved.
import React from 'react';
import { MapView, ParcelInfoPanel } from '../../../../../components/UiComponents';
import { usePekContext } from '../../../../../contexts/PekContext';

const PekMapView: React.FC = () => {
  const {
    mapCenter,
    mapZoomBounds,
    parcelGeometries,
    handleMapClick,
    handleParcelClick,
    selectedParcels,
    removeParcel,
    isPanelOpen,
    setIsPanelOpen
  } = usePekContext();

  // Aggregate all adjacent parcels from all selected parcels
  const allAdjacentParcels = React.useMemo(() => {
    const adjacentSet = new Map<string, any>();
    selectedParcels.forEach(parcel => {
      if (parcel.adjacent_parcels) {
        parcel.adjacent_parcels.forEach((adj: { id: string }) => {
          if (!adjacentSet.has(adj.id)) {
            adjacentSet.set(adj.id, adj);
          }
        });
      }
    });
    return Array.from(adjacentSet.values());
  }, [selectedParcels]);

  return (
    <>
      <div style={{ marginBottom: '1.5rem' }}>
        <MapView
          parcels={parcelGeometries}
          center={mapCenter || undefined}
          zoomBounds={mapZoomBounds || undefined}
          onMapClick={handleMapClick}
          onParcelClick={handleParcelClick}
          height="600px"
          emptyMessage="Klicken Sie auf die Karte, um einen Standort auszuwählen, oder suchen Sie nach einer Adresse oben."
        />
      </div>
      
      <ParcelInfoPanel
        isOpen={isPanelOpen}
        onClose={() => setIsPanelOpen(false)}
        parcels={selectedParcels}
        onRemoveParcel={removeParcel}
        adjacentParcels={allAdjacentParcels}
      />
    </>
  );
};

export default PekMapView;

