'use client';

export const dynamic = 'force-dynamic';

import { useRouter } from 'next/navigation';
import { useBookingStore } from '@/lib/booking-store';
import { useQuery, useMutation } from '@tanstack/react-query';
import { apiClient } from '@/lib/api-client';
import { useState, useEffect, useCallback, useMemo, memo } from 'react';
import { Armchair, Bed, ChevronLeft } from 'lucide-react';

import CustomModal from '@/components/CustomModal';

const SeatButton = memo(({ seat, isSelected, onToggle, isBedCoach, bedLabel, coachSeatClass }: any) => {
  const seatLabel = seat.number || seat.label || seat.seatNumber || '?';
  const bedWidth = 'w-24';
  const width = isBedCoach ? bedWidth : 'w-10';
  
  return (
    <div className="flex flex-col items-center">
      <button
        onClick={() => onToggle(seat.id)}
        disabled={seat.status !== 'AVAILABLE'}
        className={`${width} h-11 rounded flex items-center justify-center transition-all ${
          isSelected
            ? 'bg-[rgb(20_113_76)] text-white shadow-md scale-105'
            : seat.status === 'AVAILABLE'
            ? 'bg-green-500 hover:bg-green-600 text-white cursor-pointer hover:shadow-md'
            : seat.status === 'HELD'
            ? 'bg-yellow-500 text-white cursor-not-allowed opacity-75'
            : 'bg-gray-500 text-white cursor-not-allowed opacity-60'
        }`}
        title={`Seat ${seatLabel}${bedLabel} - ${seat.status} - ${coachSeatClass}`}
        style={isBedCoach ? (seat.row % 2 === 1 ? { transform: 'scaleY(-1)' } : undefined) : (seat.row % 2 === 0 ? { transform: 'scaleY(-1)' } : undefined)}
      >
        {isBedCoach ? (
          <Bed className="w-7 h-7" />
        ) : (
          <Armchair className="w-7 h-7" />
        )}
      </button>
    </div>
  );
});

SeatButton.displayName = 'SeatButton';

export default function SeatsPage() {
  const router = useRouter();
  const { selectedSchedule, passengers, setSeatHold, setPassengers, searchCriteria, bookingId } = useBookingStore();
  const [selectedSeats, setSelectedSeats] = useState<string[]>([]);
  const [selectedCoach, setSelectedCoach] = useState<string | null>(null);
  const [modalState, setModalState] = useState({
    isOpen: false,
    title: '',
    message: '',
    type: 'info' as 'warning' | 'error' | 'success' | 'info',
  });

  const { data: seatMapData, isLoading, error } = useQuery({
    queryKey: ['seatmap', selectedSchedule?.id],
    queryFn: () => apiClient.get(`/seats/seatmap/${selectedSchedule?.id}`),
    enabled: !!selectedSchedule?.id,
  });

  const holdMutation = useMutation({
    mutationFn: async (seatIds: string[]) => {
      const passengersForHold = passengers.slice(0, seatIds.length).map((_, i) => ({
        passengerId: `temp-${Date.now()}-${i}`,
        seatId: seatIds[i],
      }));
      
      return apiClient.post(`/seats/hold`, {
        scheduleId: selectedSchedule?.id,
        originStationId: searchCriteria?.originStationId,
        destinationStationId: searchCriteria?.destinationStationId,
        passengers: passengersForHold,
      });
    },
    onSuccess: (data: any) => {
      setSeatHold({
        holdId: data.holdId || data.id,
        expiresAt: data.expiresAt,
      });
    },
  });

  const bookSeatsMutation = useMutation({
    mutationFn: async (seatIds: string[]) => {
      return Promise.all(
        seatIds.map((seatId) =>
          apiClient.patch(`/seats/${seatId}`, {
            status: 'BOOKED',
          }).catch(() => null)
        )
      );
    },
  });

  const coaches = useMemo(() => (seatMapData as any)?.coaches || [], [seatMapData]);
  
  const filteredCoaches = useMemo(() => {
    if (!selectedSchedule?.selectedSeatClass) {
      return coaches.filter((c: any) => c.seats && c.seats.length > 0);
    }
    
    let filtered = coaches.filter((c: any) => {
      const seatClasses = c.seatClasses || [c.seatClass] || [];
      return seatClasses.some((seatClassName: string) => 
        seatClassName === selectedSchedule.selectedSeatClass || 
        seatClassName.replace(/_/g, ' ').toLowerCase() === selectedSchedule.selectedSeatClass?.toLowerCase() ||
        seatClassName.toLowerCase() === selectedSchedule.selectedSeatClass?.toLowerCase()
      );
    });
    return filtered.filter((c: any) => c.seats && c.seats.length > 0);
  }, [coaches, selectedSchedule?.selectedSeatClass]);

  useEffect(() => {
    if (filteredCoaches.length > 0 && !selectedCoach) {
      setSelectedCoach(filteredCoaches[0].id);
    }
  }, [filteredCoaches, selectedCoach]);

  const selectedCoachData = useMemo(() => filteredCoaches.find((c: any) => c.id === selectedCoach), [filteredCoaches, selectedCoach]);
  const allSeats = useMemo(() => selectedCoachData?.seats || [], [selectedCoachData]);
  
  const getBedPosition = (selectedClass: string): string | null => {
    const lowerClass = selectedClass.toLowerCase();
    if (lowerClass.includes('upper')) return 'upper';
    if (lowerClass.includes('middle')) return 'middle';
    if (lowerClass.includes('lower')) return 'lower';
    return null;
  };

  const validSeats = useMemo(() => {
    let seats = allSeats.filter((s: any) => s.seatNumber && !s.seatNumber.startsWith('-'));
    const isBedCoach = selectedCoachData?.seatClass?.toLowerCase().includes('bed') || selectedCoachData?.mode?.toLowerCase().includes('bed');
    
    if (isBedCoach && selectedSchedule?.selectedSeatClass) {
      const selectedBedPosition = getBedPosition(selectedSchedule.selectedSeatClass);
      if (selectedBedPosition) {
        seats = seats.filter((s: any) => s.bedPosition === selectedBedPosition);
      }
    }
    
    return seats;
  }, [allSeats, selectedCoachData, selectedSchedule?.selectedSeatClass]);

  const handleSeatClick = useCallback((seatId: string) => {
    setSelectedSeats(prev => {
      if (prev.length < passengers.length) {
        return [...prev, seatId];
      } else {
        return [seatId];
      }
    });
  }, [passengers.length]);

  const handleContinue = async () => {
    if (selectedSeats.length > 0) {
      await holdMutation.mutateAsync(selectedSeats);
      const updatedPassengers = passengers.map((p, i) => {
        const seatData = validSeats?.find((s: any) => s.id === selectedSeats[i]);
        return {
          ...p,
          seatId: selectedSeats[i],
          seatNumber: seatData?.number || seatData?.label || seatData?.seatNumber || '',
        };
      });
      setPassengers(updatedPassengers);
    }
    router.push('/booking/review');
  };

  const handleAutoAssign = async () => {
    const availableSeats = validSeats?.filter((s: any) => s.status === 'AVAILABLE') || [];
    if (availableSeats.length < passengers.length) {
      setModalState({
        isOpen: true,
        title: 'Not Enough Seats',
        message: `Only ${availableSeats.length} seat(s) available in this coach, but you need ${passengers.length} seat(s). Please select another coach.`,
        type: 'warning',
      });
      return;
    }
    
    const autoSelectedSeats = availableSeats.slice(0, passengers.length).map((s: any) => s.id);
    setSelectedSeats(autoSelectedSeats);
    
    try {
      await holdMutation.mutateAsync(autoSelectedSeats);
      const updatedPassengers = passengers.map((p, i) => {
        const seatData = availableSeats[i];
        return {
          ...p,
          seatId: autoSelectedSeats[i],
          seatNumber: seatData?.number || seatData?.label || seatData?.seatNumber || '',
        };
      });
      setPassengers(updatedPassengers);
      router.push('/booking/review');
    } catch (error: any) {
      console.error('Failed to hold seats:', error);
      setModalState({
        isOpen: true,
        title: 'Seat Hold Failed',
        message: error?.response?.data?.message || 'Failed to hold seats. Please try again.',
        type: 'error',
      });
    }
  };

  const handleBackToPassengers = () => {
    router.push('/booking/passengers');
  };

  useEffect(() => {
    if (!selectedSchedule || !passengers.length) {
      router.push('/booking/search');
    }
  }, [selectedSchedule, passengers.length, router]);

  useEffect(() => {
    if (bookingId && selectedSeats.length > 0) {
      bookSeatsMutation.mutate(selectedSeats);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [bookingId]);

  const parseSeatArrangement = (arrangement: string | null): number[] => {
    if (!arrangement) return [2, 2];
    const parts = arrangement.split('+').map(p => parseInt(p.trim()));
    return parts.length === 2 ? parts : [2, 2];
  };

  const getBedLabel = (bedPosition: string | null): string => {
    if (bedPosition === 'upper') return 'U';
    if (bedPosition === 'middle') return 'M';
    if (bedPosition === 'lower') return 'L';
    return '';
  };

  const renderCoachSeats = (coach: any, isBedCoach: boolean) => {
    const arrangement = parseSeatArrangement(coach.seatArrangement);
    const leftCount = arrangement[0];

    if (validSeats.length === 0) {
      return <div className="text-xs text-muted-foreground">No seats</div>;
    }

    const hasBedPositionData = validSeats.some((s: any) => s.bedPosition);
    const seatClassStr = typeof selectedCoachData?.seatClass === 'string' ? selectedCoachData.seatClass : (selectedCoachData?.seatClass?.name || '');

    if (isBedCoach && hasBedPositionData) {
      return (
        <div className="space-y-2 w-40">
          {validSeats.map((seat: any) => {
            const rowNumber = seat.row || 1;
            const shouldFlipIcon = rowNumber % 2 === 0;
            
            return (
              <div key={seat.id}>
                {shouldFlipIcon && (
                  <div className="w-24 h-4 flex items-center justify-center text-xs font-bold mb-0.5 leading-3 text-foreground">
                    {seat.seatNumber && !seat.seatNumber.startsWith('-') ? `${seat.seatNumber}${getBedLabel(seat.bedPosition)}` : ''}
                  </div>
                )}
                <div className="flex">
                  <SeatButton
                    key={seat.id}
                    seat={seat}
                    isSelected={selectedSeats.includes(seat.id)}
                    onToggle={handleSeatClick}
                    isBedCoach={true}
                    bedLabel={getBedLabel(seat.bedPosition)}
                    coachSeatClass={seatClassStr}
                  />
                </div>
                {!shouldFlipIcon && (
                  <div className="w-24 h-4 flex items-center justify-center text-xs font-bold mb-0.5 leading-3 text-foreground">
                    {seat.seatNumber && !seat.seatNumber.startsWith('-') ? `${seat.seatNumber}${getBedLabel(seat.bedPosition)}` : ''}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      );
    }

    const rows = [];
    const processedRows = new Set();
    for (const seat of validSeats) {
      if (!processedRows.has(seat.row)) {
        rows.push(validSeats.filter((s: any) => s.row === seat.row).sort((a: any, b: any) => {
          const colA = a.col.charCodeAt(0);
          const colB = b.col.charCodeAt(0);
          return colA - colB;
        }));
        processedRows.add(seat.row);
      }
    }

    return (
      <div className="space-y-0">
        {rows.map((rowSeats: any[], rowIdx: number) => {
          const leftSeats = rowSeats.slice(0, leftCount);
          const rightSeats = rowSeats.slice(leftCount);
          const rowNumber = rowSeats[0]?.row || 1;
          const shouldFlipArmchair = rowNumber % 2 === 0;
          const showSpacing = rowIdx % 2 === 1;

          return (
            <div key={`row-${rowSeats[0]?.id}`}>
              {shouldFlipArmchair && (
                <div className="flex gap-0.5 justify-start text-xs text-muted-foreground mb-1">
                  <div className="flex gap-0.5">
                    {leftSeats.map((seat: any) => (
                      <div key={`num-before-left-${seat.id}`} className="w-10 h-4 flex items-center justify-center text-xs font-bold mb-0.5 leading-3 text-foreground">
                        {seat.seatNumber && !seat.seatNumber.startsWith('-') ? seat.seatNumber : ''}
                      </div>
                    ))}
                  </div>
                  {rightSeats.length > 0 && <div className="w-3" />}
                  {rightSeats.length > 0 && (
                    <div className="flex gap-0.5">
                      {rightSeats.map((seat: any) => (
                        <div key={`num-before-right-${seat.id}`} className="w-10 h-4 flex items-center justify-center text-xs font-bold mb-0.5 leading-3 text-foreground">
                          {seat.seatNumber && !seat.seatNumber.startsWith('-') ? seat.seatNumber : ''}
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}
              <div className="flex gap-0.5 justify-start">
                <div className="flex gap-0.5">
                  {leftSeats.map((seat: any) => (
                    <SeatButton
                      key={seat.id}
                      seat={seat}
                      isSelected={selectedSeats.includes(seat.id)}
                      onToggle={handleSeatClick}
                      isBedCoach={false}
                      bedLabel=""
                    />
                  ))}
                </div>
                {rightSeats.length > 0 && <div className="w-3" />}
                {rightSeats.length > 0 && (
                  <div className="flex gap-0.5">
                    {rightSeats.map((seat: any) => (
                      <SeatButton
                        key={seat.id}
                        seat={seat}
                        isSelected={selectedSeats.includes(seat.id)}
                        onToggle={handleSeatClick}
                        isBedCoach={false}
                        bedLabel=""
                      />
                    ))}
                  </div>
                )}
              </div>

              {!shouldFlipArmchair && (
                <div className="flex gap-0.5 justify-start text-xs text-muted-foreground mb-1">
                  <div className="flex gap-0.5">
                    {leftSeats.map((seat: any) => (
                      <div key={`num-left-${seat.id}`} className="w-10 h-4 flex items-center justify-center text-xs font-bold mb-0.5 leading-3 text-foreground">
                        {seat.seatNumber && !seat.seatNumber.startsWith('-') ? seat.seatNumber : ''}
                      </div>
                    ))}
                  </div>
                  {rightSeats.length > 0 && <div className="w-3" />}
                  {rightSeats.length > 0 && (
                    <div className="flex gap-0.5">
                      {rightSeats.map((seat: any) => (
                        <div key={`num-right-${seat.id}`} className="w-10 h-4 flex items-center justify-center text-xs font-bold mb-0.5 leading-3 text-foreground">
                          {seat.seatNumber && !seat.seatNumber.startsWith('-') ? seat.seatNumber : ''}
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}

              {showSpacing && <div className="h-2" />}
            </div>
          );
        })}
      </div>
    );
  };

  if (!selectedSchedule || !passengers.length) return null;

  const allSelected = selectedSeats.length === passengers.length;
  const isBedCoach = selectedCoachData?.seatClass?.toLowerCase().includes('bed') || selectedCoachData?.mode?.toLowerCase().includes('bed');

  // Summary card content — shared between sidebar and mobile modal
  const SummaryContent = () => (
    <>
      <div className="flex items-center justify-between mb-1">
        <h3 className="font-bold text-gray-900 dark:text-white">Selection Summary</h3>
        <span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${
          allSelected ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' : 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400'
        }`}>
          {selectedSeats.length}/{passengers.length} selected
        </span>
      </div>
      <p className="text-xs text-gray-500 dark:text-gray-400 mb-4">
        {allSelected ? 'All seats selected — ready to continue' : `Select ${passengers.length - selectedSeats.length} more seat(s)`}
      </p>

      {/* Progress bar */}
      <div className="h-1.5 bg-gray-100 dark:bg-gray-700 rounded-full mb-4 overflow-hidden">
        <div
          className="h-full bg-[rgb(20,113,76)] rounded-full transition-all duration-300"
          style={{ width: `${(selectedSeats.length / passengers.length) * 100}%` }}
        />
      </div>

      <div className="space-y-2 mb-5">
        {passengers.map((p, i) => {
          const assignedSeat = selectedSeats[i] ? validSeats?.find((s: any) => s.id === selectedSeats[i]) : null;
          const seatLabel = assignedSeat ? (assignedSeat.number || assignedSeat.label || assignedSeat.seatNumber || '—') : '—';
          const bedLabel = assignedSeat ? getBedLabel(assignedSeat.bedPosition) : '';
          return (
            <div key={i} className="flex items-center justify-between py-2 border-b border-gray-100 dark:border-gray-800 last:border-0">
              <div className="flex items-center gap-2">
                <div className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0 ${
                  assignedSeat ? 'bg-[rgb(20,113,76)] text-white' : 'bg-gray-200 dark:bg-gray-700 text-gray-500'
                }`}>{i + 1}</div>
                <span className="text-sm text-gray-700 dark:text-gray-300 truncate max-w-[120px]">{p.name}</span>
              </div>
              <span className={`text-sm font-semibold ${
                assignedSeat ? 'text-[rgb(20,113,76)]' : 'text-gray-400'
              }`}>
                {assignedSeat ? `${seatLabel}${bedLabel}` : 'Not selected'}
              </span>
            </div>
          );
        })}
      </div>

      <button
        onClick={handleContinue}
        disabled={selectedSeats.length === 0 || holdMutation.isPending}
        className="w-full py-3 bg-[rgb(20,113,76)] hover:bg-[rgb(16,89,60)] disabled:opacity-40 disabled:cursor-not-allowed text-white font-bold text-sm rounded-xl transition-all shadow-lg"
      >
        {holdMutation.isPending ? 'Holding seats...' : allSelected ? 'Continue' : 'Continue with partial selection'}
      </button>
      <button
        onClick={handleAutoAssign}
        disabled={holdMutation.isPending}
        className="w-full mt-2 py-2.5 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 disabled:opacity-40 text-gray-700 dark:text-gray-300 font-semibold text-sm rounded-xl transition-all"
      >
        Auto-assign seats
      </button>
    </>
  );

  return (
    <>
      <CustomModal
        isOpen={modalState.isOpen}
        onClose={() => setModalState({ ...modalState, isOpen: false })}
        title={modalState.title}
        message={modalState.message}
        type={modalState.type}
      />

      {/* Mobile summary bottom-sheet */}
      {selectedSeats.length > 0 && (
        <>
          <div className="fixed inset-x-0 bottom-0 z-50 lg:hidden bg-white dark:bg-gray-900 rounded-t-2xl shadow-2xl p-5"
            style={{ animation: 'seats-slide-up 0.25s cubic-bezier(0.32,0.72,0,1)' }}
          >
            <div className="w-10 h-1 bg-gray-300 dark:bg-gray-600 rounded-full mx-auto mb-4" />
            <SummaryContent />
          </div>
          <style>{`@keyframes seats-slide-up{from{transform:translateY(100%)}to{transform:translateY(0)}}`}</style>
        </>
      )}

      <div className="min-h-screen bg-gray-50 dark:bg-gray-900">
        {/* Header */}
        <div className="bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800 sticky top-0 z-30">
          <div className="container mx-auto px-4">
            <div className="max-w-6xl mx-auto flex items-center justify-between h-14">
              <button
                onClick={handleBackToPassengers}
                className="flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-primary transition-colors font-medium"
              >
                <ChevronLeft className="w-4 h-4" />
                Back
              </button>
              <h1 className="text-base font-bold text-gray-900 dark:text-white">Select Seats</h1>
              <div className="text-sm font-semibold text-[rgb(20,113,76)]">
                {selectedSeats.length}/{passengers.length}
              </div>
            </div>
          </div>
        </div>

        <div className="container mx-auto px-4 py-5">
          <div className="max-w-6xl mx-auto">
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">

              {/* ── Seat map panel ── */}
              <div className="lg:col-span-2 space-y-4">
                {isLoading ? (
                  <div className="bg-white dark:bg-gray-800 rounded-2xl p-8 text-center">
                    <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-3" />
                    <p className="text-sm text-gray-500 dark:text-gray-400">Loading seat map...</p>
                  </div>
                ) : error ? (
                  <div className="bg-white dark:bg-gray-800 rounded-2xl p-8 text-center">
                    <p className="text-red-500 font-medium">Error loading seats</p>
                    <p className="text-sm text-gray-400 mt-1">{(error as any)?.message || 'Please try again'}</p>
                  </div>
                ) : filteredCoaches.length === 0 ? (
                  <div className="bg-white dark:bg-gray-800 rounded-2xl p-8 text-center">
                    <p className="text-gray-500 dark:text-gray-400">No coaches available for {selectedSchedule?.selectedSeatClass}</p>
                  </div>
                ) : (
                  <>
                    {/* Coach selector */}
                    <div className="bg-white dark:bg-gray-800 rounded-2xl p-4 border border-gray-100 dark:border-gray-700">
                      <h3 className="text-sm font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-3">Coach</h3>
                      <div className="flex flex-wrap gap-2">
                        {filteredCoaches.map((coach: any) => {
                          const coachSeats = coach.seats?.filter((s: any) => s.seatNumber && !s.seatNumber.startsWith('-')) || [];
                          const isBed = coach.seatClass?.toLowerCase().includes('bed') || coach.mode?.toLowerCase().includes('bed');
                          let fSeats = coachSeats;
                          if (isBed && selectedSchedule?.selectedSeatClass) {
                            const bedPos = getBedPosition(selectedSchedule.selectedSeatClass);
                            if (bedPos) fSeats = coachSeats.filter((s: any) => s.bedPosition === bedPos);
                          }
                          const available = fSeats.filter((s: any) => s.status === 'AVAILABLE').length;
                          const isActive = selectedCoach === coach.id;
                          return (
                            <button
                              key={coach.id}
                              onClick={() => setSelectedCoach(coach.id)}
                              className={`px-4 py-2.5 rounded-xl text-sm font-semibold transition-all ${
                                isActive
                                  ? 'bg-[rgb(20,113,76)] text-white shadow-md'
                                  : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
                              }`}
                            >
                              <div>{coach.label || coach.name || coach.coachNumber}</div>
                              <div className={`text-xs mt-0.5 ${isActive ? 'text-white/70' : 'text-gray-400'}`}>{available} free</div>
                            </button>
                          );
                        })}
                      </div>
                    </div>

                    {/* Seat map */}
                    <div className="bg-white dark:bg-gray-800 rounded-2xl p-4 border border-gray-100 dark:border-gray-700">
                      <div className="flex items-center justify-between mb-3">
                        <h3 className="text-sm font-semibold text-gray-900 dark:text-white">
                          {selectedCoachData?.name || selectedCoachData?.label || selectedCoachData?.coachNumber}
                        </h3>
                        <span className="text-xs text-gray-400">{selectedCoachData?.seatArrangement}</span>
                      </div>

                      {/* Legend */}
                      <div className="flex flex-wrap gap-3 mb-4">
                        {[
                          { color: 'bg-green-500', label: 'Available' },
                          { color: 'bg-[rgb(20,113,76)]', label: 'Selected' },
                          { color: 'bg-yellow-500', label: 'Held' },
                          { color: 'bg-gray-400', label: 'Booked' },
                        ].map(({ color, label }) => (
                          <div key={label} className="flex items-center gap-1.5">
                            <div className={`w-3 h-3 ${color} rounded-sm`} />
                            <span className="text-xs text-gray-500 dark:text-gray-400">{label}</span>
                          </div>
                        ))}
                      </div>

                      <div className="overflow-x-auto">
                        <div className="inline-block bg-gray-50 dark:bg-gray-700/30 rounded-xl p-4 border border-gray-200 dark:border-gray-700">
                          {validSeats.length === 0 ? (
                            <p className="text-sm text-gray-400 py-4">No seats in this coach</p>
                          ) : (
                            renderCoachSeats(selectedCoachData, isBedCoach)
                          )}
                        </div>
                      </div>
                    </div>
                  </>
                )}
              </div>

              {/* ── Sidebar summary (desktop only) ── */}
              <div className="hidden lg:block lg:col-span-1">
                <div className="bg-white dark:bg-gray-800 rounded-2xl p-5 border border-gray-100 dark:border-gray-700 sticky top-20">
                  <SummaryContent />
                </div>
              </div>

            </div>

            {/* Mobile spacer so bottom-sheet doesn't cover last seat */}
            <div className="h-48 lg:hidden" />
          </div>
        </div>
      </div>
    </>
  );
}
