'use client';

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useRouter, useSearchParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { useAuthStore } from '@/lib/auth-store';
import { apiClient } from '@/lib/api-client';
import { useBookingStore } from '@/lib/booking-store';
import { Station } from '@/types';
import {
  Train, MapPin, ArrowRight, ArrowLeftRight, Plus, Minus, Search,
  Users, ChevronDown, Gift, Check, X, ChevronLeft, Clock, Zap,
} from 'lucide-react';
import { useEffect, useRef, useState, useCallback } from 'react';
import ModernDatePicker from '@/components/ModernDatePicker';

const searchSchema = z.object({
  originStationId: z.string().min(1, 'Please select origin station'),
  destinationStationId: z.string().min(1, 'Please select destination station'),
  departureDate: z.string().min(1, 'Please select departure date'),
  adultCount: z.number().min(1).max(9),
  childCount: z.number().min(0).max(9),
  nationality: z.enum(['ETHIOPIAN', 'DJIBOUTIAN', 'OTHER']),
  promoCode: z.string().optional(),
}).refine((d) => d.originStationId !== d.destinationStationId, {
  message: 'Origin and destination must be different',
  path: ['destinationStationId'],
});

type SearchForm = z.infer<typeof searchSchema>;

const POPULAR_ROUTES = [
  { from: 'Sebeta', to: 'Nagad', duration: '12h', icon: '🌆' },
  { from: 'Sebeta', to: 'Diredawa', duration: '8h', icon: '🏔️' },
  { from: 'Diredawa', to: 'Nagad', duration: '4h', icon: '🌊' },
];

// ─── Station Modal ────────────────────────────────────────────────────────────
function StationModal({
  stations,
  title,
  excludeId,
  onSelect,
  onClose,
  recentIds,
}: {
  stations: Station[];
  title: string;
  excludeId?: string;
  onSelect: (s: Station) => void;
  onClose: () => void;
  recentIds: string[];
}) {
  const [query, setQuery] = useState('');
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    setTimeout(() => inputRef.current?.focus(), 100);
  }, []);

  const filtered = query.trim()
    ? stations.filter(
        (s) =>
          s.id !== excludeId &&
          (s.name.toLowerCase().includes(query.toLowerCase()) ||
            s.code?.toLowerCase().includes(query.toLowerCase()))
      )
    : stations.filter((s) => s.id !== excludeId);

  const recentStations = recentIds
    .map((id) => stations.find((s) => s.id === id))
    .filter(Boolean) as Station[];

  return (
    <div className="fixed inset-0 z-[100] bg-white dark:bg-gray-900 flex flex-col md:hidden animate-slide-up">
      {/* Header */}
      <div className="flex items-center gap-3 px-4 py-4 border-b border-gray-100 dark:border-gray-800 bg-white dark:bg-gray-900">
        <button
          type="button"
          onClick={onClose}
          className="w-10 h-10 flex items-center justify-center rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
        >
          <ChevronLeft className="w-5 h-5 text-gray-600 dark:text-gray-400" />
        </button>
        <h2 className="text-lg font-semibold text-gray-900 dark:text-white">{title}</h2>
      </div>

      {/* Search input */}
      <div className="px-4 py-3 bg-white dark:bg-gray-900">
        <div className="relative">
          <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            ref={inputRef}
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search stations..."
            className="w-full pl-10 pr-10 py-3 bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary text-gray-900 dark:text-white placeholder-gray-400"
          />
          {query && (
            <button
              type="button"
              onClick={() => setQuery('')}
              className="absolute right-3 top-1/2 -translate-y-1/2"
            >
              <X className="w-4 h-4 text-gray-400" />
            </button>
          )}
        </div>
      </div>

      {/* Results */}
      <div className="flex-1 overflow-y-auto px-4 pb-6">
        {!query && recentStations.length > 0 && (
          <div className="mb-4">
            <p className="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-2 mt-2">Recent</p>
            {recentStations.map((s) => (
              <button
                key={s.id}
                type="button"
                onClick={() => onSelect(s)}
                className="w-full flex items-center gap-3 py-3.5 px-3 rounded-xl hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors text-left"
              >
                <div className="w-8 h-8 bg-primary/10 rounded-full flex items-center justify-center flex-shrink-0">
                  <Clock className="w-4 h-4 text-primary" />
                </div>
                <div>
                  <p className="font-medium text-gray-900 dark:text-white text-sm">{s.name}</p>
                  {s.code && <p className="text-xs text-gray-400">{s.code}</p>}
                </div>
              </button>
            ))}
          </div>
        )}

        <p className="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-2 mt-2">
          {query ? 'Results' : 'All Stations'}
        </p>
        {filtered.length === 0 ? (
          <div className="text-center py-10 text-gray-400">
            <MapPin className="w-8 h-8 mx-auto mb-2 opacity-40" />
            <p className="text-sm">No stations found</p>
          </div>
        ) : (
          filtered.map((s) => (
            <button
              key={s.id}
              type="button"
              onClick={() => onSelect(s)}
              className="w-full flex items-center gap-3 py-3.5 px-3 rounded-xl hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors text-left"
            >
              <div className="w-8 h-8 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center flex-shrink-0">
                <MapPin className="w-4 h-4 text-primary" />
              </div>
              <div>
                <p className="font-medium text-gray-900 dark:text-white text-sm">{s.name}</p>
                {s.code && <p className="text-xs text-gray-400">{s.code} • {s.country}</p>}
              </div>
            </button>
          ))
        )}
      </div>
    </div>
  );
}

// ─── Passenger Modal (mobile bottom-sheet) ───────────────────────────────────
function PassengerModal({
  adultCount,
  childCount,
  onChangeAdult,
  onChangeChild,
  onClose,
}: {
  adultCount: number;
  childCount: number;
  onChangeAdult: (n: number) => void;
  onChangeChild: (n: number) => void;
  onClose: () => void;
}) {
  const rows = [
    { label: 'Adults', sub: '≥ 5 years', val: adultCount, min: 1, max: 9, onChange: onChangeAdult },
    { label: 'Children', sub: '< 5 years • First child free', val: childCount, min: 0, max: 9, onChange: onChangeChild },
  ];

  return (
    <>
      {/* Backdrop */}
      <div className="fixed inset-0 z-[99] bg-black/40" onClick={onClose} />
      {/* Bottom sheet */}
      <div
        className="fixed inset-x-0 bottom-0 z-[100] bg-white dark:bg-gray-900 rounded-t-2xl shadow-2xl"
        style={{ animation: 'pax-slide-up 0.25s cubic-bezier(0.32,0.72,0,1)' }}
      >
        {/* Handle */}
        <div className="flex justify-center pt-3 pb-1">
          <div className="w-10 h-1 rounded-full bg-gray-300 dark:bg-gray-600" />
        </div>
        {/* Header */}
        <div className="flex items-center justify-between px-5 py-3 border-b border-gray-100 dark:border-gray-800">
          <div className="flex items-center gap-2">
            <Users className="w-4 h-4 text-primary" />
            <h2 className="text-base font-bold text-gray-900 dark:text-white">Passengers</h2>
          </div>
          <button type="button" onClick={onClose} className="w-9 h-9 flex items-center justify-center rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors">
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>
        {/* Rows */}
        <div className="px-5 py-4 space-y-5">
          {rows.map(({ label, sub, val, min, max, onChange }, i) => (
            <div key={label}>
              {i > 0 && <div className="border-t border-gray-100 dark:border-gray-800 -mx-5 mb-5" />}
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-semibold text-gray-900 dark:text-white">{label}</p>
                  <p className="text-xs text-gray-400 mt-0.5">{sub}</p>
                </div>
                <div className="flex items-center gap-4">
                  <button
                    type="button"
                    onClick={() => val > min && onChange(val - 1)}
                    disabled={val <= min}
                    className="w-10 h-10 rounded-full border-2 border-gray-200 dark:border-gray-700 flex items-center justify-center hover:border-primary hover:text-primary transition-colors disabled:opacity-30"
                  >
                    <Minus className="w-4 h-4" />
                  </button>
                  <span className="w-6 text-center text-lg font-bold text-gray-900 dark:text-white tabular-nums">{val}</span>
                  <button
                    type="button"
                    onClick={() => val < max && onChange(val + 1)}
                    disabled={val >= max}
                    className="w-10 h-10 rounded-full border-2 border-gray-200 dark:border-gray-700 flex items-center justify-center hover:border-primary hover:text-primary transition-colors disabled:opacity-30"
                  >
                    <Plus className="w-4 h-4" />
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
        {/* Done */}
        <div className="px-5 pb-8 pt-2">
          <button
            type="button"
            onClick={onClose}
            className="w-full py-3.5 bg-[rgb(20,113,76)] text-white font-bold text-sm rounded-xl"
          >
            Done — {adultCount + childCount} Passenger{adultCount + childCount !== 1 ? 's' : ''}
          </button>
        </div>
        <style>{`@keyframes pax-slide-up{from{transform:translateY(100%);opacity:0}to{transform:translateY(0);opacity:1}}`}</style>
      </div>
    </>
  );
}

// ─── Station Autocomplete (Desktop dropdown) ──────────────────────────────────
function StationDropdown({
  stations,
  value,
  excludeId,
  placeholder,
  onSelect,
  error,
  recentIds,
}: {
  stations: Station[];
  value: string;
  excludeId?: string;
  placeholder: string;
  onSelect: (s: Station) => void;
  error?: string;
  recentIds: string[];
}) {
  const [query, setQuery] = useState('');
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const selectedStation = stations.find((s) => s.id === value);

  useEffect(() => {
    if (selectedStation && !open) setQuery('');
  }, [selectedStation, open]);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const filtered = query.trim()
    ? stations.filter(
        (s) =>
          s.id !== excludeId &&
          (s.name.toLowerCase().includes(query.toLowerCase()) ||
            s.code?.toLowerCase().includes(query.toLowerCase()))
      )
    : stations.filter((s) => s.id !== excludeId).slice(0, 8);

  const displayValue = open ? query : (selectedStation?.name ?? '');

  return (
    <div ref={ref} className="relative">
      <div
        className={`relative flex items-center border-2 rounded-xl transition-all duration-200 bg-white dark:bg-gray-800 ${
          error ? 'border-red-400' : open ? 'border-primary ring-2 ring-primary/20' : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
        }`}
      >
        <MapPin className="absolute left-3.5 w-4 h-4 text-primary flex-shrink-0" />
        <input
          ref={inputRef}
          value={displayValue}
          onChange={(e) => { setQuery(e.target.value); setOpen(true); }}
          onFocus={() => { setQuery(''); setOpen(true); }}
          placeholder={placeholder}
          className="w-full pl-10 pr-8 py-3.5 bg-transparent rounded-xl focus:outline-none text-sm text-gray-900 dark:text-white placeholder-gray-400"
        />
        {value && (
          <button
            type="button"
            onClick={() => { onSelect({ id: '', name: '', code: '', country: '' }); setQuery(''); }}
            className="absolute right-3 p-0.5"
          >
            <X className="w-3.5 h-3.5 text-gray-400 hover:text-gray-600" />
          </button>
        )}
      </div>

      {open && (
        <div className="absolute top-full left-0 right-0 mt-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl shadow-xl z-50 max-h-56 overflow-y-auto overflow-x-hidden scrollbar-hide">
          {!query && recentIds.length > 0 && (
            <div className="px-3 pt-2 pb-1">
              <p className="text-[10px] font-semibold text-gray-400 uppercase tracking-wide mb-1">Recent</p>
              {recentIds
                .map((id) => stations.find((s) => s.id === id))
                .filter(Boolean)
                .map((s) => (
                  <button
                    key={s!.id}
                    type="button"
                    onMouseDown={() => { onSelect(s!); setOpen(false); setQuery(''); }}
                    className="w-full flex items-center gap-2 px-2 py-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 text-left"
                  >
                    <Clock className="w-3.5 h-3.5 text-primary flex-shrink-0" />
                    <span className="text-sm text-gray-800 dark:text-gray-200">{s!.name}</span>
                  </button>
                ))}
              <div className="border-t border-gray-100 dark:border-gray-700 mt-1 mb-1" />
            </div>
          )}
          {filtered.length === 0 ? (
            <p className="text-sm text-gray-400 text-center py-4">No stations found</p>
          ) : (
            filtered.map((s) => (
              <button
                key={s.id}
                type="button"
                onMouseDown={() => { onSelect(s); setOpen(false); setQuery(''); }}
                className="w-full flex items-center gap-2 px-3 py-2.5 hover:bg-gray-50 dark:hover:bg-gray-700 text-left transition-colors"
              >
                <MapPin className="w-3.5 h-3.5 text-primary flex-shrink-0" />
                <div>
                  <span className="text-sm font-medium text-gray-900 dark:text-white">{s.name}</span>
                  {s.code && <span className="text-xs text-gray-400 ml-1.5">{s.code}</span>}
                </div>
              </button>
            ))
          )}
        </div>
      )}
    </div>
  );
}

// ─── Main Page ────────────────────────────────────────────────────────────────
export default function SearchPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const setSearchCriteria = useBookingStore((s) => s.setSearchCriteria);
  const { user, isAuthenticated } = useAuthStore();

  const [isPassengerOpen, setIsPassengerOpen] = useState(false);
  const [passengerModalOpen, setPassengerModalOpen] = useState(false);
  const [promoVisible, setPromoVisible] = useState(false);
  const [promoCode, setPromoCode] = useState('');
  const [promoValidation, setPromoValidation] = useState<{ valid: boolean; message: string } | null>(null);
  const [promoLoading, setPromoLoading] = useState(false);
  const [swapping, setSwapping] = useState(false);
  const [stationModal, setStationModal] = useState<'origin' | 'destination' | null>(null);
  const [recentStationIds, setRecentStationIds] = useState<string[]>(() => {
    try { return JSON.parse(localStorage.getItem('edr_recent_stations') || '[]'); } catch { return []; }
  });
  const passengerRef = useRef<HTMLDivElement>(null);

  const { data: stations = [], isLoading, error } = useQuery<Station[]>({
    queryKey: ['stations'],
    queryFn: async () => await apiClient.get('/stations') as Station[],
  });

  const { register, handleSubmit, watch, setValue, formState: { errors } } = useForm<SearchForm>({
    resolver: zodResolver(searchSchema as any),
    defaultValues: {
      adultCount: 1,
      childCount: 0,
      nationality: 'ETHIOPIAN',
      departureDate: new Date().toISOString().split('T')[0],
      promoCode: '',
    },
  });

  useEffect(() => {
    if (isAuthenticated && user?.nationality) {
      const n = user.nationality.toUpperCase().trim();
      setValue('nationality', n.includes('DJIBOUTIAN') ? 'DJIBOUTIAN' : n.includes('ETHIOPIAN') ? 'ETHIOPIAN' : 'OTHER');
    }
  }, [isAuthenticated, user?.nationality, setValue]);

  useEffect(() => {
    const o = searchParams.get('origin');
    const d = searchParams.get('destination');
    const date = searchParams.get('date');
    const adults = searchParams.get('adults');
    const children = searchParams.get('children');
    const nat = searchParams.get('nationality');
    if (o) setValue('originStationId', o);
    if (d) setValue('destinationStationId', d);
    if (date) setValue('departureDate', date);
    if (adults) setValue('adultCount', parseInt(adults));
    if (children) setValue('childCount', parseInt(children));
    if (nat) setValue('nationality', nat as 'ETHIOPIAN' | 'DJIBOUTIAN' | 'OTHER');
  }, [searchParams, setValue]);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (passengerRef.current && !passengerRef.current.contains(e.target as Node)) {
        setIsPassengerOpen(false);
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const originId = watch('originStationId');
  const destId = watch('destinationStationId');
  const adultCount = watch('adultCount');
  const childCount = watch('childCount');
  const departureDate = watch('departureDate');
  const totalPassengers = (adultCount || 1) + (childCount || 0);

  const saveRecent = useCallback((id: string) => {
    setRecentStationIds((prev) => {
      const next = [id, ...prev.filter((x) => x !== id)].slice(0, 5);
      localStorage.setItem('edr_recent_stations', JSON.stringify(next));
      return next;
    });
  }, []);

  const handleSwap = () => {
    if (!originId || !destId) return;
    setSwapping(true);
    setTimeout(() => {
      setValue('originStationId', destId);
      setValue('destinationStationId', originId);
      setSwapping(false);
    }, 300);
  };

  const handleValidatePromo = async () => {
    if (!promoCode.trim()) return setPromoValidation(null);
    setPromoLoading(true);
    try {
      const res = await apiClient.post('/promos/validate', { code: promoCode }) as any;
      const valid = res.applicable || res.valid;
      setPromoValidation({ valid, message: res.message || (valid ? 'Promo applied!' : 'Invalid promo code') });
      if (valid) setValue('promoCode', promoCode);
      else setPromoCode('');
    } catch (err: any) {
      setPromoValidation({ valid: false, message: err?.response?.data?.message || 'Promo code is invalid or expired' });
      setPromoCode('');
    } finally {
      setPromoLoading(false);
    }
  };

  const onSubmit = (data: SearchForm) => {
    setSearchCriteria(data);
    if (data.originStationId) saveRecent(data.originStationId);
    if (data.destinationStationId) saveRecent(data.destinationStationId);
    const params = new URLSearchParams({
      origin: data.originStationId,
      destination: data.destinationStationId,
      date: data.departureDate,
      adults: data.adultCount.toString(),
      children: data.childCount.toString(),
      nationality: data.nationality,
      ...(data.promoCode && { promoCode: data.promoCode }),
    });
    router.push(`/booking/results?${params}`);
  };

  const getStationById = (id: string) => stations.find((s) => s.id === id);
  const originStation = getStationById(originId);
  const destStation = getStationById(destId);

  const handlePopularRoute = (fromName: string, toName: string) => {
    const origin = stations.find((s) => s.name.toLowerCase().includes(fromName.toLowerCase()));
    const dest = stations.find((s) => s.name.toLowerCase().includes(toName.toLowerCase()));
    if (origin && dest) {
      setValue('originStationId', origin.id);
      setValue('destinationStationId', dest.id);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-950">
      {/* Passenger modal (mobile) */}
      {passengerModalOpen && (
        <PassengerModal
          adultCount={adultCount || 1}
          childCount={childCount || 0}
          onChangeAdult={(n) => setValue('adultCount', n)}
          onChangeChild={(n) => setValue('childCount', n)}
          onClose={() => setPassengerModalOpen(false)}
        />
      )}

      {/* Station modals (mobile) */}
      {stationModal === 'origin' && (
        <StationModal
          stations={stations}
          title="From — Departure"
          excludeId={destId}
          recentIds={recentStationIds}
          onSelect={(s) => {
            if (s.id) { setValue('originStationId', s.id); saveRecent(s.id); }
            setStationModal(null);
          }}
          onClose={() => setStationModal(null)}
        />
      )}
      {stationModal === 'destination' && (
        <StationModal
          stations={stations}
          title="To — Destination"
          excludeId={originId}
          recentIds={recentStationIds}
          onSelect={(s) => {
            if (s.id) { setValue('destinationStationId', s.id); saveRecent(s.id); }
            setStationModal(null);
          }}
          onClose={() => setStationModal(null)}
        />
      )}

      {/* Hero Banner */}
      <div className="relative bg-gradient-to-br from-[rgb(14,80,54)] via-[rgb(20,113,76)] to-[rgb(16,140,90)] overflow-hidden">
        <div className="absolute inset-0 opacity-10">
          <div className="absolute top-4 right-8 w-32 h-32 border-2 border-white rounded-full" />
          <div className="absolute top-12 right-20 w-20 h-20 border border-white rounded-full" />
          <div className="absolute -bottom-6 left-10 w-40 h-40 border border-white rounded-full" />
        </div>
        <div className="container mx-auto px-4 pt-8 pb-20 md:pt-10 md:pb-24 relative z-10">
          <div className="max-w-6xl mx-auto">
            <h1 className="text-3xl md:text-4xl lg:text-5xl font-bold text-white leading-tight">
              Where are you headed?
            </h1>
            <p className="text-white/70 text-sm md:text-base mt-2">Search and book train tickets fast &amp; easy</p>
          </div>
        </div>
      </div>

      {/* Search Card — pulled up over the hero */}
      <div className="container mx-auto px-4 -mt-14 relative z-20 pb-8">
        <div className="max-w-6xl mx-auto">
          <form onSubmit={handleSubmit(onSubmit)}>
            <div className="bg-white dark:bg-gray-900 rounded-2xl shadow-2xl border border-gray-100 dark:border-gray-800 overflow-visible">

              {/* Error banner */}
              {error && (
                <div className="flex items-center gap-2 px-5 py-3 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 text-sm border-b border-red-100 dark:border-red-900/30 rounded-t-2xl">
                  <span>⚠️</span>
                  <span>Unable to load stations. Please check your connection.</span>
                </div>
              )}

              <div className="p-5 md:p-6 space-y-3">

                {/* ── Row 1 (mobile stacked): Stations + Date ── */}

                {/* Mobile station fields */}
                <div className="flex flex-col gap-3 md:hidden">
                  <div className="space-y-1.5">
                    <label className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide">From</label>
                    <button type="button" onClick={() => setStationModal('origin')} className="w-full">
                      <div className={`flex items-center gap-2.5 px-3.5 py-3.5 border-2 rounded-xl transition-all ${
                        errors.originStationId ? 'border-red-400' : originId ? 'border-primary bg-primary/5' : 'border-gray-200 dark:border-gray-700'
                      }`}>
                        <MapPin className="w-4 h-4 text-primary flex-shrink-0" />
                        <span className={`text-sm ${originStation ? 'font-semibold text-gray-900 dark:text-white' : 'text-gray-400'}`}>
                          {originStation?.name ?? 'Select departure'}
                        </span>
                      </div>
                    </button>
                    {errors.originStationId && <p className="text-xs text-red-500">{errors.originStationId.message}</p>}
                  </div>
                  <div className="space-y-1.5">
                    <div className="flex items-center justify-between">
                      <label className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide">To</label>
                      <button type="button" onClick={handleSwap} disabled={!originId || !destId} className="flex items-center gap-1 text-xs text-primary font-medium disabled:opacity-30">
                        <ArrowLeftRight className={`w-3.5 h-3.5 transition-transform duration-300 ${swapping ? 'rotate-180' : ''}`} />
                        Swap
                      </button>
                    </div>
                    <button type="button" onClick={() => setStationModal('destination')} className="w-full">
                      <div className={`flex items-center gap-2.5 px-3.5 py-3.5 border-2 rounded-xl transition-all ${
                        errors.destinationStationId ? 'border-red-400' : destId ? 'border-primary bg-primary/5' : 'border-gray-200 dark:border-gray-700'
                      }`}>
                        <MapPin className="w-4 h-4 text-primary flex-shrink-0" />
                        <span className={`text-sm ${destStation ? 'font-semibold text-gray-900 dark:text-white' : 'text-gray-400'}`}>
                          {destStation?.name ?? 'Select destination'}
                        </span>
                      </div>
                    </button>
                    {errors.destinationStationId && <p className="text-xs text-red-500">{errors.destinationStationId.message}</p>}
                  </div>
                  {/* Date (mobile) */}
                  <div className="space-y-1.5">
                    <label className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide">Departure Date</label>
                    <div className="relative z-30">
                      <ModernDatePicker
                        value={departureDate ? new Date(departureDate + 'T00:00:00') : undefined}
                        onChange={(date) => setValue('departureDate', `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`)}
                        minDate={new Date()}
                        placeholder="Select date"
                      />
                    </div>
                    {errors.departureDate && <p className="text-xs text-red-500">{errors.departureDate.message}</p>}
                  </div>
                </div>

                {/* Desktop Row 1: From [swap] To + Date (3 equal cols) */}
                <div className="hidden md:grid md:grid-cols-3 gap-3 items-end">
                  {/* From + To with swap */}
                  <div className="col-span-2 flex items-end gap-2">
                    <div className="flex-1 space-y-1.5">
                      <label className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide">From</label>
                      <StationDropdown stations={stations} value={originId} excludeId={destId} placeholder="Select departure" recentIds={recentStationIds} onSelect={(s) => { setValue('originStationId', s.id); if (s.id) saveRecent(s.id); }} error={errors.originStationId?.message} />
                      {errors.originStationId && <p className="text-xs text-red-500">{errors.originStationId.message}</p>}
                    </div>
                    <button
                      type="button"
                      onClick={handleSwap}
                      disabled={!originId || !destId}
                      className={`flex-shrink-0 mb-0.5 w-9 h-9 bg-gray-50 dark:bg-gray-800 border-2 border-gray-200 dark:border-gray-700 rounded-full flex items-center justify-center hover:border-primary hover:bg-primary/5 transition-all duration-200 disabled:opacity-30 ${swapping ? 'rotate-180' : ''}`}
                      title="Swap stations"
                    >
                      <ArrowLeftRight className="w-4 h-4 text-gray-500" />
                    </button>
                    <div className="flex-1 space-y-1.5">
                      <label className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide">To</label>
                      <StationDropdown stations={stations} value={destId} excludeId={originId} placeholder="Select destination" recentIds={recentStationIds} onSelect={(s) => { setValue('destinationStationId', s.id); if (s.id) saveRecent(s.id); }} error={errors.destinationStationId?.message} />
                      {errors.destinationStationId && <p className="text-xs text-red-500">{errors.destinationStationId.message}</p>}
                    </div>
                  </div>
                  {/* Date */}
                  <div className="space-y-1.5">
                    <label className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide">Departure Date</label>
                    <div className="relative z-30">
                      <ModernDatePicker
                        value={departureDate ? new Date(departureDate + 'T00:00:00') : undefined}
                        onChange={(date) => setValue('departureDate', `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`)}
                        minDate={new Date()}
                        placeholder="Select date"
                      />
                    </div>
                    {errors.departureDate && <p className="text-xs text-red-500">{errors.departureDate.message}</p>}
                  </div>
                </div>

                {/* Route preview pill */}
                {originStation && destStation && (
                  <div className="flex items-center gap-2 px-3 py-2 bg-primary/5 dark:bg-primary/10 rounded-lg text-xs text-primary font-medium animate-bounce-in">
                    <Train className="w-3.5 h-3.5" />
                    <span>{originStation.name}</span>
                    <ArrowRight className="w-3 h-3" />
                    <span>{destStation.name}</span>
                  </div>
                )}

                {/* ── Row 2: Passengers | Nationality | Search Button ── */}
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 items-end">

                  {/* Passengers */}
                  <div className="space-y-1.5" ref={passengerRef}>
                    <label className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide">Passengers</label>

                    {/* Mobile: opens bottom-sheet modal */}
                    <button
                      type="button"
                      onClick={() => setPassengerModalOpen(true)}
                      className="sm:hidden w-full flex items-center justify-between px-3.5 py-3.5 border-2 border-gray-200 dark:border-gray-700 rounded-xl bg-white dark:bg-gray-800"
                    >
                      <span className="flex items-center gap-2 text-sm font-medium text-gray-900 dark:text-white">
                        <Users className="w-4 h-4 text-primary" />
                        {totalPassengers} Passenger{totalPassengers !== 1 ? 's' : ''}
                        {childCount > 0 && <span className="text-xs bg-primary/10 text-primary px-1.5 py-0.5 rounded-md">{childCount} child</span>}
                      </span>
                      <ChevronDown className="w-4 h-4 text-primary" />
                    </button>

                    {/* sm+: inline dropdown */}
                    <div className="hidden sm:block relative z-20">
                      <button
                        type="button"
                        onClick={() => setIsPassengerOpen(!isPassengerOpen)}
                        className={`w-full flex items-center justify-between px-3.5 py-3.5 border-2 rounded-xl transition-all duration-200 bg-white dark:bg-gray-800 ${
                          isPassengerOpen ? 'border-primary ring-2 ring-primary/20' : 'border-gray-200 dark:border-gray-700 hover:border-gray-300'
                        }`}
                      >
                        <span className="flex items-center gap-2 text-sm font-medium text-gray-900 dark:text-white">
                          <Users className="w-4 h-4 text-primary" />
                          {totalPassengers} Pax
                          {childCount > 0 && <span className="text-xs bg-primary/10 text-primary px-1.5 py-0.5 rounded-md">{childCount} child</span>}
                        </span>
                        <ChevronDown className={`w-4 h-4 text-primary transition-transform duration-200 ${isPassengerOpen ? 'rotate-180' : ''}`} />
                      </button>
                      {isPassengerOpen && (
                        <div className="absolute top-full left-0 right-0 mt-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl shadow-xl z-50 p-4 space-y-4">
                          {[
                            { label: 'Adults', sub: '≥ 5 years', key: 'adultCount' as const, val: adultCount || 1, min: 1, max: 9 },
                            { label: 'Children', sub: '< 5 years • First free', key: 'childCount' as const, val: childCount || 0, min: 0, max: 9 },
                          ].map(({ label, sub, key, val, min, max }, i) => (
                            <div key={key}>
                              {i > 0 && <div className="border-t border-gray-100 dark:border-gray-700 -mx-4 mb-4" />}
                              <div className="flex items-center justify-between">
                                <div>
                                  <p className="text-sm font-semibold text-gray-900 dark:text-white">{label}</p>
                                  <p className="text-xs text-gray-400 mt-0.5">{sub}</p>
                                </div>
                                <div className="flex items-center gap-3">
                                  <button type="button" onClick={() => val > min && setValue(key, val - 1)} disabled={val <= min} className="w-8 h-8 rounded-full border-2 border-gray-200 dark:border-gray-600 flex items-center justify-center hover:border-primary hover:text-primary transition-colors disabled:opacity-30"><Minus className="w-3.5 h-3.5" /></button>
                                  <span className="w-6 text-center font-bold text-gray-900 dark:text-white tabular-nums">{val}</span>
                                  <button type="button" onClick={() => val < max && setValue(key, val + 1)} disabled={val >= max} className="w-8 h-8 rounded-full border-2 border-gray-200 dark:border-gray-600 flex items-center justify-center hover:border-primary hover:text-primary transition-colors disabled:opacity-30"><Plus className="w-3.5 h-3.5" /></button>
                                </div>
                              </div>
                            </div>
                          ))}
                          <button type="button" onClick={() => setIsPassengerOpen(false)} className="w-full py-2.5 bg-primary text-white text-sm font-semibold rounded-lg">Done</button>
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Nationality */}
                  <div className="space-y-1.5">
                    <label className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide">Nationality</label>
                    <select
                      {...register('nationality')}
                      className="w-full px-3.5 py-3.5 border-2 border-gray-200 dark:border-gray-700 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary text-sm bg-white dark:bg-gray-800 text-gray-900 dark:text-white transition-all"
                    >
                      <option value="ETHIOPIAN">🇪🇹 Ethiopian</option>
                      <option value="DJIBOUTIAN">🇩🇯 Djiboutian</option>
                      <option value="OTHER">🌍 Other</option>
                    </select>
                  </div>

                  {/* Search Button */}
                  <button
                    type="submit"
                    disabled={isLoading}
                    className="w-full flex items-center justify-center gap-2.5 py-3.5 bg-[rgb(20,113,76)] hover:bg-[rgb(16,89,60)] text-white font-bold text-sm rounded-xl transition-all duration-200 shadow-lg hover:shadow-xl hover:-translate-y-0.5 active:translate-y-0 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <Search className="w-5 h-5" />
                    Search
                  </button>
                </div>

                {/* ── Promo Code (collapsed by default) ── */}
                <div>
                  {!promoVisible ? (
                    <button
                      type="button"
                      onClick={() => setPromoVisible(true)}
                      className="flex items-center gap-1.5 text-xs text-primary font-medium hover:underline transition-colors"
                    >
                      <Gift className="w-3.5 h-3.5" />
                      Apply Promo Code
                    </button>
                  ) : (
                    <div className="flex flex-col gap-1.5 animate-bounce-in">
                      <div className="flex gap-2">
                        <div className="flex-1 relative">
                          <Gift className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-primary" />
                          <input
                            type="text"
                            value={promoCode}
                            onChange={(e) => { setPromoCode(e.target.value.toUpperCase()); if (promoValidation) setPromoValidation(null); }}
                            placeholder="Enter promo code"
                            onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), handleValidatePromo())}
                            className="w-full pl-9 pr-3 py-2.5 border-2 border-gray-200 dark:border-gray-700 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary text-sm bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder-gray-400 transition-all"
                            autoFocus
                          />
                        </div>
                        <button
                          type="button"
                          onClick={handleValidatePromo}
                          disabled={!promoCode || promoLoading}
                          className="px-4 py-2.5 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-xl hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors disabled:opacity-40 text-sm font-semibold"
                        >
                          {promoLoading ? '...' : 'Apply'}
                        </button>
                        <button
                          type="button"
                          onClick={() => { setPromoVisible(false); setPromoCode(''); setPromoValidation(null); }}
                          className="p-2.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-xl hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
                        >
                          <X className="w-4 h-4" />
                        </button>
                      </div>
                      {promoValidation && (
                        <div className={`flex items-center gap-1.5 text-xs ${promoValidation.valid ? 'text-green-600' : 'text-red-500'}`}>
                          {promoValidation.valid && <Check className="w-3.5 h-3.5" />}
                          {promoValidation.message}
                        </div>
                      )}
                    </div>
                  )}
                </div>

              </div>
            </div>
          </form>

          {/* ── Popular Routes ── */}
          <div className="mt-8">
            <div className="flex items-center gap-2 mb-4">
              <Zap className="w-4 h-4 text-primary" />
              <h2 className="text-base font-bold text-gray-900 dark:text-white">Popular Routes</h2>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
              {POPULAR_ROUTES.map((route, idx) => (
                <button
                  key={idx}
                  type="button"
                  onClick={() => handlePopularRoute(route.from, route.to)}
                  className="bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-xl p-4 hover:border-primary hover:shadow-md transition-all text-left group active:scale-95"
                >
                  <div className="text-xl mb-2">{route.icon}</div>
                  <div className="flex items-center gap-1.5 text-sm font-semibold text-gray-900 dark:text-white">
                    <span>{route.from}</span>
                    <ArrowRight className="w-3.5 h-3.5 text-primary flex-shrink-0" />
                    <span>{route.to}</span>
                  </div>
                  <div className="text-xs text-gray-400 mt-1 flex items-center gap-1">
                    <Clock className="w-3 h-3" />
                    {route.duration} journey
                  </div>
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>

      <style jsx>{`
        @keyframes slide-up {
          from { transform: translateY(100%); opacity: 0; }
          to { transform: translateY(0); opacity: 1; }
        }
        .animate-slide-up {
          animation: slide-up 0.25s cubic-bezier(0.32, 0.72, 0, 1);
        }
      `}</style>
    </div>
  );
}
