'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, outboundSchedule, inboundSchedule, passengers, setSeatHold, setPassengers, searchCriteria, bookingId } = useBookingStore();
  const [selectedSeats, setSelectedSeats] = useState<string[]>([]);
  const [selectedCoach, setSelectedCoach] = useState<string | null>(null);
  const [currentJourneyType, setCurrentJourneyType] = useState<'outbound' | 'inbound'>('outbound');
  const [modalState, setModalState] = useState({
    isOpen: false,
    title: '',
    message: '',
    type: 'info' as 'warning' | 'error' | 'success' | 'info',
  });

  const isRoundTrip = searchCriteria?.tripType === 'ROUND_TRIP';
  const currentSchedule = isRoundTrip && currentJourneyType === 'inbound' ? inboundSchedule : (isRoundTrip ? outboundSchedule : selectedSchedule);
  const coachId = (currentSchedule as any)?.selectedCoachId;
  const coachTypeCode = (currentSchedule as any)?.selectedCoachTypeCode;

  const { data: seatMapData, isLoading, error } = useQuery({
    queryKey: ['seatmap', currentSchedule?.id, coachId, currentJourneyType],
    queryFn: async () => {
      const endpoint = `/seats/seatmap/${currentSchedule?.id}?coachId=${coachId}`;
      console.log('🪑 Seatmap Request:', {
        endpoint,
        scheduleId: currentSchedule?.id,
        coachId,
        coachTypeCode,
        currentJourneyType,
      });
      
      const response = await apiClient.get(endpoint);
      
      console.log('✅ Seatmap Response:', {
        endpoint,
        fullResponse: response,
        dataCoaches: (response as any)?.data?.coaches?.length || 0,
        rootCoaches: (response as any)?.coaches?.length || 0,
      });
      
      const finalData = (response as any)?.data || response;
      console.log('🎯 Final data structure:', finalData);
      return finalData;
    },
    enabled: !!currentSchedule?.id && !!coachId,
  });

  const holdMutation = useMutation({
    mutationFn: async (seatIds: string[]) => {
      const passengersForHold = passengers.slice(0, seatIds.length).map((_, i) => ({
        passengerId: `temp-${Date.now()}-${i}`,
        seatId: seatIds[i],
      }));
      
      // For round trip inbound, swap origin and destination
      const isInbound = isRoundTrip && currentJourneyType === 'inbound';
      const originId = isInbound ? searchCriteria?.destinationStationId : searchCriteria?.originStationId;
      const destinationId = isInbound ? searchCriteria?.originStationId : searchCriteria?.destinationStationId;
      
      return apiClient.post(`/seats/hold`, {
        scheduleId: currentSchedule?.id,
        originStationId: originId,
        destinationStationId: destinationId,
        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(() => {
    const rawCoaches = (seatMapData as any)?.coaches || (seatMapData as any)?.data?.coaches || [];
    console.log('📦 Raw coaches data:', {
      fromRoot: (seatMapData as any)?.coaches?.length || 0,
      fromData: (seatMapData as any)?.data?.coaches?.length || 0,
      using: rawCoaches.length,
      seatMapData
    });
    return rawCoaches;
  }, [seatMapData]);
  
  const filteredCoaches = useMemo(() => {
    console.log('🔍 Filtering coaches:', {
      totalCoaches: coaches.length,
      selectedSeatClass: currentSchedule?.selectedSeatClass,
      coachesData: coaches.map((c: any) => ({
        id: c.id,
        name: c.name,
        label: c.label,
        seatClass: c.seatClass,
        seatClasses: c.seatClasses,
        seatsCount: c.seats?.length || 0
      }))
    });

    const coachesWithSeats = coaches.filter((c: any) => c.seats && c.seats.length > 0);
    
    if (!currentSchedule?.selectedSeatClass) {
      console.log('✅ No filter applied, returning all coaches:', coachesWithSeats.length);
      return coachesWithSeats;
    }
    
    console.log('✅ No seat class filter - returning all coaches with seats:', coachesWithSeats.length);
    return coachesWithSeats;
  }, [coaches, currentSchedule?.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) => {
      const seatLabel = s.label || s.number || s.seatNumber || '';
      return seatLabel && !seatLabel.startsWith('-');
    });
    const isBedCoach = selectedCoachData?.seatClass?.toLowerCase().includes('bed') || selectedCoachData?.mode?.toLowerCase().includes('bed');
    
    if (isBedCoach && currentSchedule?.selectedSeatClass) {
      const selectedBedPosition = getBedPosition(currentSchedule.selectedSeatClass);
      if (selectedBedPosition) {
        seats = seats.filter((s: any) => s.bedPosition === selectedBedPosition);
      }
    }
    
    return seats;
  }, [allSeats, selectedCoachData, currentSchedule?.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 (isRoundTrip && currentJourneyType === 'outbound') {
      if (selectedSeats.length > 0) {
        try {
          await holdMutation.mutateAsync(selectedSeats);
          const updatedPassengers = passengers.map((p, i) => {
            const seatData = validSeats?.find((s: any) => s.id === selectedSeats[i]);
            return {
              ...p,
              outboundSeatId: selectedSeats[i],
              outboundSeatNumber: seatData?.number || seatData?.label || seatData?.seatNumber || '',
            };
          });
          setPassengers(updatedPassengers);
        } catch (error: any) {
          setModalState({
            isOpen: true,
            title: 'Seat Hold Failed',
            message: error?.response?.data?.message || 'Failed to hold seats. Please try again.',
            type: 'error',
          });
          return;
        }
      }
      setCurrentJourneyType('inbound');
      setSelectedSeats([]);
      setSelectedCoach(null);
      return;
    }

    if (selectedSeats.length > 0) {
      try {
        await holdMutation.mutateAsync(selectedSeats);
        const updatedPassengers = passengers.map((p, i) => {
          const seatData = validSeats?.find((s: any) => s.id === selectedSeats[i]);
          if (isRoundTrip && currentJourneyType === 'inbound') {
            return {
              ...p,
              inboundSeatId: selectedSeats[i],
              inboundSeatNumber: seatData?.number || seatData?.label || seatData?.seatNumber || '',
            };
          }
          return {
            ...p,
            seatId: selectedSeats[i],
            seatNumber: seatData?.number || seatData?.label || seatData?.seatNumber || '',
          };
        });
        setPassengers(updatedPassengers);
      } catch (error: any) {
        setModalState({
          isOpen: true,
          title: 'Seat Hold Failed',
          message: error?.response?.data?.message || 'Failed to hold seats. Please try again.',
          type: 'error',
        });
        return;
      }
    }
    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 (isRoundTrip) {
      if (!outboundSchedule || !inboundSchedule || !passengers.length) {
        router.push('/booking/search');
      }
    } else {
      if (!selectedSchedule || !passengers.length) {
        router.push('/booking/search');
      }
    }
  }, [isRoundTrip, selectedSchedule, outboundSchedule, inboundSchedule, 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, seatClasses?: string[]): number[] => {
    if (!arrangement) return [2, 2];
    
    // Check if this is a bed coach based on seat classes
    const isBedCoach = seatClasses?.some(sc => sc?.toLowerCase().includes('bed'));
    
    if (isBedCoach) {
      // For bed coaches, arrangement like "3+0" means 3 beds stacked vertically
      // We want to render them as single column, so return [1]
      const parts = arrangement.split('+').map(p => parseInt(p.trim())).filter(n => !isNaN(n) && n > 0);
      return parts.length > 0 ? [Math.max(...parts)] : [3];
    }
    
    // For regular seats, parse normally (e.g., "3+2" -> [3, 2])
    const parts = arrangement.split('+').map(p => parseInt(p.trim())).filter(n => !isNaN(n) && n > 0);
    return parts.length >= 2 ? parts : parts.length === 1 ? [parts[0]] : [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, coach.seatClasses || [coach.seatClass]);

    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 || '');

    // Bed coach with bed positions (Upper, Middle, Lower)
    if (isBedCoach && hasBedPositionData) {
      // Group by the base seat number (column), not by row
      // For beds, seats with same number but different positions should be grouped together
      const seatGroups = new Map<string, any[]>();
      
      for (const seat of validSeats) {
        const baseNumber = seat.seatNumber || seat.number || seat.label || '';
        if (!seatGroups.has(baseNumber)) {
          seatGroups.set(baseNumber, []);
        }
        seatGroups.get(baseNumber)!.push(seat);
      }

      // Sort groups by seat number
      const sortedGroups = Array.from(seatGroups.entries())
        .sort(([a], [b]) => {
          const numA = parseInt(a) || 0;
          const numB = parseInt(b) || 0;
          return numA - numB;
        });

      return (
        <div className="space-y-4">
          {sortedGroups.map(([seatNumber, beds], idx) => {
            const shouldFlipIcon = idx % 2 === 0;
            
            // Order: lower, middle, upper (bottom to top)
            const orderedBeds = ['lower', 'middle', 'upper']
              .map(pos => beds.find(seat => seat.bedPosition === pos))
              .filter(seat => seat !== undefined);
            
            if (orderedBeds.length === 0) return null;
            
            return (
              <div key={`bed-group-${seatNumber}`} className="pb-4 border-b-2 border-dashed border-gray-300 dark:border-gray-600 last:border-b-0">
                <div className="flex items-center gap-3">
                  {shouldFlipIcon && (
                    <div className="flex flex-col gap-3">
                      {orderedBeds.map((seat: any) => {
                        const seatLabel = seat.seatNumber || seat.number || seat.label || '';
                        const bedLabelFull = seat.bedPosition ? (
                          seat.bedPosition === 'upper' ? 'Upper' :
                          seat.bedPosition === 'middle' ? 'Middle' : 'Lower'
                        ) : '';
                        return (
                          <div key={seat.id} className="w-20 text-xs font-bold text-foreground text-right">
                            {seatLabel ? `${seatLabel} ${bedLabelFull}` : ''}
                          </div>
                        );
                      })}
                    </div>
                  )}
                  
                  <div className="flex flex-col gap-3">
                    {orderedBeds.map((seat: any) => (
                      <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="flex flex-col gap-3">
                      {orderedBeds.map((seat: any) => {
                        const seatLabel = seat.seatNumber || seat.number || seat.label || '';
                        const bedLabelFull = seat.bedPosition ? (
                          seat.bedPosition === 'upper' ? 'Upper' :
                          seat.bedPosition === 'middle' ? 'Middle' : 'Lower'
                        ) : '';
                        return (
                          <div key={seat.id} className="w-20 text-xs font-bold text-foreground">
                            {seatLabel ? `${seatLabel} ${bedLabelFull}` : ''}
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      );
    }

    // Regular seats with row/column arrangement
    const rowMap = new Map<number, any[]>();
    for (const seat of validSeats) {
      if (!rowMap.has(seat.row)) {
        rowMap.set(seat.row, []);
      }
      rowMap.get(seat.row)!.push(seat);
    }

    const rows = Array.from(rowMap.entries())
      .sort(([a], [b]) => a - b)
      .map(([_, seats]) => seats.sort((a, b) => a.col.localeCompare(b.col)));

    return (
      <div className="space-y-0">
        {rows.map((rowSeats: any[], rowIdx: number) => {
          const groups: any[][] = [];
          
          // Split seats into groups based on arrangement
          if (arrangement.length === 1) {
            // Single group (all seats together)
            groups.push(rowSeats);
          } else {
            // Multiple groups with aisle separation
            arrangement.forEach((_groupSize, groupIdx) => {
              const startIdx = arrangement.slice(0, groupIdx).reduce((sum, size) => sum + size, 0);
              const endIdx = arrangement.slice(0, groupIdx + 1).reduce((sum, size) => sum + size, 0);
              const currentGroup = rowSeats.slice(startIdx, endIdx);
              if (currentGroup.length > 0) groups.push(currentGroup);
            });
          }

          const rowNumber = rowSeats[0]?.row || 1;
          const shouldFlipArmchair = rowNumber % 2 === 0;
          const showSpacing = rowIdx % 2 === 1;

          return (
            <div key={`row-${rowNumber}-${rowSeats[0]?.id}`}>
              {shouldFlipArmchair && (
                <div className="flex gap-3 justify-start text-xs text-muted-foreground mb-1">
                  {groups.map((group, gIdx) => (
                    <div key={`num-before-group-${gIdx}`} className="flex gap-0.5">
                      {group.map((seat: any) => {
                        const seatLabel = seat.label || seat.number || seat.seatNumber || '';
                        return (
                          <div key={`num-${seat.id}`} className="w-10 h-4 flex items-center justify-center text-xs font-bold leading-3 text-foreground">
                            {seatLabel}
                          </div>
                        );
                      })}
                    </div>
                  ))}
                </div>
              )}
              <div className="flex gap-3 justify-start">
                {groups.map((group, gIdx) => (
                  <div key={`group-${gIdx}`} className="flex gap-0.5">
                    {group.map((seat: any) => (
                      <SeatButton
                        key={seat.id}
                        seat={seat}
                        isSelected={selectedSeats.includes(seat.id)}
                        onToggle={handleSeatClick}
                        isBedCoach={false}
                        bedLabel=""
                        coachSeatClass={seatClassStr}
                      />
                    ))}
                  </div>
                ))}
              </div>

              {!shouldFlipArmchair && (
                <div className="flex gap-3 justify-start text-xs text-muted-foreground mb-1">
                  {groups.map((group, gIdx) => (
                    <div key={`num-after-group-${gIdx}`} className="flex gap-0.5">
                      {group.map((seat: any) => {
                        const seatLabel = seat.label || seat.number || seat.seatNumber || '';
                        return (
                          <div key={`num-${seat.id}`} className="w-10 h-4 flex items-center justify-center text-xs font-bold leading-3 text-foreground">
                            {seatLabel}
                          </div>
                        );
                      })}
                    </div>
                  ))}
                </div>
              )}

              {showSpacing && <div className="h-3 border-b border-gray-200 dark:border-gray-700" />}
            </div>
          );
        })}
      </div>
    );
  };

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

  if (!coachId) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center p-4">
        <div className="bg-white dark:bg-gray-800 rounded-2xl p-8 text-center max-w-md">
          <p className="text-red-500 font-medium mb-2">No coach selected</p>
          <p className="text-sm text-gray-500 dark:text-gray-400 mb-4">Please go back and select a coach type</p>
          <button
            onClick={() => router.push('/booking/results')}
            className="btn-primary"
          >
            Back to Results
          </button>
        </div>
      </div>
    );
  }

  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...' 
          : isRoundTrip && currentJourneyType === 'outbound'
          ? 'Continue to Return 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">
                {isRoundTrip 
                  ? (currentJourneyType === 'outbound' ? 'Select Outbound Seats' : 'Select Return Seats')
                  : '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 && currentSchedule?.selectedSeatClass) {
                            const bedPos = getBedPosition(currentSchedule.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>
    </>
  );
}
