import React from 'react';
import {
  useMapActions,
  useMapFilter,
  useMapInteraction,
  useMapUI,
} from '@/contexts/MapContexts.tsx';
import { useMapData } from '@/hooks/map/useMapData.ts';
import { useTranslation } from '@/hooks/useI18n.tsx';
import OrganizationListItem from '@/components/map/OrganizationListItem.tsx';

const SidebarList: React.FC = () => {
  const { t } = useTranslation();
  const { filteredAndSortedOrgs, searchTerm } = useMapFilter();
  const { selectedOrg, selectedLandmark, setHoveredOrgId, setHoveredLandmarkId } = useMapInteraction();
  const { mapViewMode } = useMapUI();
  const { historicalLandmarks } = useMapData();
  const { handleSelectOrg, handleSelectLandmark } = useMapActions();

  // Hide content when an organization or landmark is selected, but keep hooks running
  if (selectedOrg || selectedLandmark) {
    return <div className="flex-1 overflow-y-auto p-3 space-y-2" style={{ display: 'none' }} />;
  }

  const itemsToDisplay =
    mapViewMode === 'organizations' ? filteredAndSortedOrgs || [] : historicalLandmarks || [];

  return (
    <div className="flex-1 overflow-y-auto p-4 space-y-3">
      {itemsToDisplay && itemsToDisplay.length > 0 ? (
        mapViewMode === 'organizations' ? (
          (filteredAndSortedOrgs || []).map((org) => (
            <OrganizationListItem
              key={org.ID}
              org={org}
              isSelected={selectedOrg?.ID === org.ID}
              onSelectOrg={handleSelectOrg}
              onHoverOrg={setHoveredOrgId}
              searchTerm={searchTerm}
            />
          ))
        ) : (
          (historicalLandmarks || []).map((landmark) => (
            <div
              key={landmark.id}
              onMouseEnter={() => setHoveredLandmarkId(landmark.id)}
              onMouseLeave={() => setHoveredLandmarkId(null)}
              onClick={() => handleSelectLandmark(landmark)}
              className={`p-3 rounded-lg cursor-pointer transition-colors ${selectedLandmark?.id === landmark.id ? 'bg-primary/10' : 'hover:bg-muted'}`}
            >
              <p className="font-medium">{landmark.name}</p>
              <p className="text-sm text-muted-foreground">{landmark.period}</p>
            </div>
          ))
        )
      ) : (
        <div className="flex flex-col items-center justify-center py-16 px-4">
          <p className="text-center text-muted-foreground text-base font-medium">
            {t('mapSidebar.noResults')}
          </p>
        </div>
      )}
    </div>
  );
};

export default React.memo(SidebarList);
