(function(){
// vehicles-screen.jsx — Step /vehicles — Clear theme
// Teal brand #11978f · Ink #042828 · Muted #5B7A82 · Cream bg #F4F2EC

const T_TEAL    = '#11978f';
const T_INK     = '#042828';
const T_MUTED   = '#5B7A82';
const T_CREAM   = '#F4F2EC';
const T_SURFACE = '#FFFFFF';
const T_BORDER  = 'rgba(4,40,40,0.08)';
const T_BORDER_STRONG = 'rgba(4,40,40,0.14)';
const T_DANGER  = '#C0392B';

const MOCK_AGENCIES = [
  { id: 1, public_name: 'Van-Away Bordeaux',  city: 'Bordeaux' },
  { id: 2, public_name: 'Van-Away Lyon',      city: 'Lyon' },
  { id: 3, public_name: 'Van-Away Marseille', city: 'Marseille' },
  { id: 4, public_name: 'Van-Away Paris',     city: 'Paris' },
  { id: 5, public_name: 'Van-Away Toulouse',  city: 'Toulouse' },
  { id: 6, public_name: 'Van-Away Nantes',    city: 'Nantes' },
  { id: 7, public_name: 'Van-Away Rennes',    city: 'Rennes' },
];

const MOCK_VEHICLES = [
  {
    id: 1, display_name: 'Camper Van California', category_name: 'VAN',
    tagline: 'Van aménagé Volkswagen, pour voyager en couple ou en famille jusqu’à 4.',
    brand: 'Volkswagen', model: 'California', nb_places: 4, nb_doors: 4,
    gearbox: 'Automatique', energy: 'Diesel',
    specificities: { cooling: true, gps: true, bluetooth: true },
    custom_equipments: [{ icon: 'bed', text: '2 couchages' }, { icon: 'kitchen', text: 'Cuisine équipée' }],
    photo_hue: 180,
    description: "Le Camper Van California est le compagnon idéal pour partir à l'aventure en couple ou en famille. Compact en ville, confortable sur la route, il offre tout le nécessaire pour des escapades nature : cuisine équipée, lit double électrique en toiture, et un espace de vie chaleureux.",
    equipments: ['Climatisation', 'GPS', 'Bluetooth', 'Cuisine', 'Réfrigérateur', 'Chauffage stationnaire', 'Auvent', 'Régulateur de vitesse'],
    mileage_levels: [
      { id: 'm1', mileage: 200, amount: 0, unlimited: false },
      { id: 'm2', mileage: 300, amount: 8, unlimited: false },
      { id: 'm3', mileage: 0, amount: 18, unlimited: true },
    ],
    included_options: [
      { option_id: 'i1', name: 'Lit double aménagé' }, { option_id: 'i2', name: 'Vaisselle 4 personnes' }, { option_id: 'i3', name: 'Kit de cuisine' }, { option_id: 'i4', name: 'Linge de lit' },
    ],
    paid_options: [
      { option_id: 'p1', name: 'Tente de toit', amount: 12, pricing_type: 'per_day' },
      { option_id: 'p2', name: 'Porte-vélos (2 vélos)', amount: 8, pricing_type: 'per_day' },
      { option_id: 'p3', name: 'Siège bébé', amount: 5, pricing_type: 'per_day' },
      { option_id: 'p4', name: 'Pack vaisselle premium', amount: 25, pricing_type: 'per_rental' },
    ],
  },
  {
    id: 2, display_name: 'Camper Van Nugget', category_name: 'VAN',
    tagline: 'Van aménagé Ford Transit, idéal pour 4 personnes avec douche extérieure.',
    brand: 'Ford', model: 'Nugget', nb_places: 4, nb_doors: 4,
    gearbox: 'Automatique', energy: 'Diesel',
    specificities: { cooling: true, gps: true },
    custom_equipments: [{ icon: 'bed', text: '4 couchages' }, { icon: 'shower', text: 'Douche extérieure' }],
    photo_hue: 30,
    description: "Le Ford Nugget est un van aménagé spacieux et polyvalent, parfait pour les familles ou les groupes d'amis. Avec sa douche extérieure et son toit relevable, il combine confort et liberté pour des road-trips au long cours.",
    equipments: ['Climatisation', 'GPS', 'Cuisine', 'Réfrigérateur', 'Douche', 'Auvent', 'Régulateur de vitesse', 'USB'],
    mileage_levels: [
      { id: 'm1', mileage: 200, amount: 0, unlimited: false },
      { id: 'm2', mileage: 300, amount: 8, unlimited: false },
      { id: 'm3', mileage: 0, amount: 18, unlimited: true },
    ],
    included_options: [
      { option_id: 'i1', name: 'Toit relevable' }, { option_id: 'i2', name: 'Vaisselle 4 personnes' }, { option_id: 'i3', name: 'Kit de cuisine' },
    ],
    paid_options: [
      { option_id: 'p1', name: 'Auvent latéral', amount: 10, pricing_type: 'per_day' },
      { option_id: 'p2', name: 'Porte-vélos (2 vélos)', amount: 8, pricing_type: 'per_day' },
      { option_id: 'p3', name: 'Pack literie supplémentaire', amount: 35, pricing_type: 'per_rental' },
    ],
  },
];

const UNAVAIL_VEHICLES = [
  {
    id: 101, display_name: 'Fourgon Grand California 600', category_name: 'FOURGON',
    tagline: 'Fourgon Volkswagen haut de gamme, 4 places, WC et douche intérieure.',
    brand: 'Volkswagen', model: 'Grand California', nb_places: 4, nb_doors: 4,
    gearbox: 'Automatique', energy: 'Diesel',
    custom_equipments: [{ icon: 'bed', text: '4 couchages' }, { icon: 'toilet', text: 'WC + douche' }],
    photo_hue: 260,
    description: "Le Grand California 600 est le fourgon haut de gamme de Volkswagen. Spacieux, équipé d'une vraie salle d'eau (WC + douche) et d'une cuisine complète, il offre tout le confort d'un camping-car dans un véhicule conduisible avec un permis B.",
    equipments: ['Climatisation', 'GPS', 'Bluetooth', 'Cuisine', 'Réfrigérateur', 'Chauffage stationnaire', 'Douche', 'Toilettes', 'Panneau solaire', 'Auvent'],
    mileage_levels: [
      { id: 'm1', mileage: 200, amount: 0, unlimited: false },
      { id: 'm2', mileage: 300, amount: 10, unlimited: false },
      { id: 'm3', mileage: 0, amount: 22, unlimited: true },
    ],
    included_options: [
      { option_id: 'i1', name: 'Lit double électrique' }, { option_id: 'i2', name: 'Vaisselle 4 personnes' }, { option_id: 'i3', name: 'Kit de cuisine' },
    ],
    paid_options: [
      { option_id: 'p1', name: 'Porte-vélos (2 vélos)', amount: 8, pricing_type: 'per_day' },
      { option_id: 'p2', name: 'Siège bébé', amount: 5, pricing_type: 'per_day' },
    ],
  },
];

// ─── Photo placeholder ─────────────────────────────────────────
const PHOTO_URL = 'https://www.van-away.com/wp-content/uploads/malaga-2p-1600x923-1-1024x591.png';
function PhotoPlaceholder({ hue = 180, label = 'VAN PHOTO' }) {
  return (
    <img src={PHOTO_URL} alt={label} loading="lazy"
      style={{ display:'block', width:'100%', height:'100%', objectFit:'cover' }}/>
  );
}

function CatIcon({ kind, size = 14 }) {
  const sp = { width:size, height:size, viewBox:'0 0 24 24', fill:'none', stroke:'currentColor', strokeWidth:1.8, strokeLinecap:'round', strokeLinejoin:'round' };
  if (kind === 'VAN')        return <svg {...sp}><path d="M3 17V9a2 2 0 012-2h9l5 5v5"/><circle cx="7.5" cy="17.5" r="1.8"/><circle cx="16.5" cy="17.5" r="1.8"/><path d="M9 17h5"/></svg>;
  if (kind === 'FOURGON')    return <svg {...sp}><rect x="2" y="7" width="15" height="10" rx="1.5"/><path d="M17 11h3l2 3v3h-5"/><circle cx="6" cy="18.5" r="1.8"/><circle cx="18" cy="18.5" r="1.8"/></svg>;
  if (kind === 'ÉQUIPEMENT') return <svg {...sp}><path d="M3 21h18M5 21V9l7-6 7 6v12"/></svg>;
  return null;
}

// ─── Vehicle card ──────────────────────────────────────────────
function VehicleCard({ vehicle, days, startDate, index = 0, unavailable = false, onSelect, onShowDetails }) {
  const [visible, setVisible] = React.useState(false);
  const [photoIdx, setPhotoIdx] = React.useState(0);
  React.useEffect(() => {
    const t = setTimeout(() => setVisible(true), index * 80);
    return () => clearTimeout(t);
  }, [index]);

  const pricing = {
    '1-10':  { basse: 90, moyenne: 120, haute: 150 },
    '11-30': { basse: 85, moyenne: 100, haute: 140 },
    '31+':   { basse: 70, moyenne: 75,  haute: 120 },
  };
  const bracket = days >= 31 ? pricing['31+'] : days >= 11 ? pricing['11-30'] : pricing['1-10'];
  const month = startDate ? new Date(startDate).getMonth() + 1 : 5;
  const season = (month >= 7 && month <= 8) ? 'haute' : ((month >= 4 && month <= 6) || month === 9) ? 'moyenne' : 'basse';
  const dailyPrice = bracket[season];

  const specs = [];
  if (vehicle.nb_places) specs.push({ icon: 'seats', text: `Jusqu’à ${vehicle.nb_places}` });
  for (const e of (vehicle.custom_equipments || [])) specs.push({ icon: `custom_${e.icon}`, text: e.text });
  if (vehicle.specificities?.cooling)   specs.push({ icon: 'clim', text: 'Climatisation' });
  if (vehicle.specificities?.gps)       specs.push({ icon: 'gps', text: 'GPS' });
  if (vehicle.gearbox)                  specs.push({ icon: 'gearbox', text: vehicle.gearbox });

  const photos = [vehicle.photo_hue ?? 180, (vehicle.photo_hue ?? 180) + 40, (vehicle.photo_hue ?? 180) - 40];
  const catLabel = vehicle.category_name === 'VAN' ? 'Campervans'
                 : vehicle.category_name === 'FOURGON' ? 'Fourgons'
                 : 'Équipements';

  return (
    <div className={`va-vcard ${visible ? 'is-visible' : ''} ${unavailable ? 'is-unavail' : ''}`}>
      <div className="va-vcard-carousel" onClick={() => !unavailable && setPhotoIdx((photoIdx + 1) % photos.length)}>
        {unavailable && (
          <div className="va-vcard-unavail-overlay">
            <span>Non disponible</span>
          </div>
        )}
        <div className="va-vcard-slide">
          <PhotoPlaceholder hue={photos[photoIdx]} label={`${vehicle.brand || vehicle.model || 'VAN'} · photo ${photoIdx+1}`}/>
        </div>

        {/* Category pill — top-left of photo */}
        <div className="va-vcard-cat-badge">
          <CatIcon kind={vehicle.category_name} size={16}/>
          <span>{catLabel}</span>
        </div>

        {photos.length > 1 && !unavailable && (
          <>
            <button className="va-vcard-cbtn prev" onClick={(e)=>{e.stopPropagation(); setPhotoIdx((photoIdx - 1 + photos.length) % photos.length);}}>
              <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5" d="M15 19l-7-7 7-7"/>
              </svg>
            </button>
            <button className="va-vcard-cbtn next" onClick={(e)=>{e.stopPropagation(); setPhotoIdx((photoIdx + 1) % photos.length);}}>
              <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5" d="M9 5l7 7-7 7"/>
              </svg>
            </button>
            <div className="va-vcard-dots">
              {photos.map((_, i) => <span key={i} className={`va-vcard-dot ${i === photoIdx ? 'active' : ''}`}/>)}
            </div>
          </>
        )}
      </div>

      <div className="va-vcard-info">
        <h3 className="va-vcard-title">{vehicle.display_name}</h3>
        {vehicle.tagline && <p className="va-vcard-tagline">{vehicle.tagline}</p>}

        <ul className="va-vcard-specs">
          {specs.map((s, i) => (
            <li key={i} className="va-vcard-spec">
              <SpecIcon kind={s.icon}/>
              <span>{s.text}</span>
            </li>
          ))}
        </ul>

        {!unavailable && (
          <>
            <div className="va-vcard-price-block">
              <span className="va-vcard-price-from">À partir de</span>
              <div className="va-vcard-price-row">
                <span className="va-vcard-price-num">{dailyPrice} €</span>
                <span className="va-vcard-price-per">/jour</span>
              </div>
              <span className="va-vcard-price-total">Soit <strong>{dailyPrice * days} €</strong> pour {days} jours</span>
              <span className="va-vcard-price-note">Assurance comprise · hors options</span>
            </div>

            <div className="va-vcard-links-row">
              <a href="#" className="va-vcard-details-link" onClick={(e)=>{e.preventDefault(); onShowDetails?.(vehicle.id);}}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/>
                </svg>
                Voir les détails
              </a>
            </div>

            <button className="va-vcard-select-btn" onClick={() => onSelect?.(vehicle.id)}>
              Choisir ce véhicule
            </button>
          </>
        )}
        {unavailable && (
          <div className="va-vcard-links-row" style={{marginTop:'auto'}}>
            <a href="#" className="va-vcard-details-link" onClick={(e)=>e.preventDefault()}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/>
              </svg>
              Voir les détails
            </a>
          </div>
        )}
      </div>

      <style>{`
        .va-vcard{background:${T_SURFACE};border-radius:20px;overflow:hidden;box-shadow:0 1px 2px rgba(4,40,40,.04),0 4px 20px rgba(4,40,40,.06);transition:all .4s cubic-bezier(.4,0,.2,1);border:1px solid ${T_BORDER};display:flex;flex-direction:column;position:relative;opacity:0;transform:translateY(20px)}
        .va-vcard.is-visible{opacity:1;transform:translateY(0)}
        .va-vcard:hover{box-shadow:0 8px 30px rgba(4,40,40,.10),0 2px 6px rgba(4,40,40,.05);transform:translateY(-4px);border-color:${T_BORDER_STRONG}}
        .va-vcard.is-unavail{opacity:.65}
        .va-vcard.is-unavail:hover{transform:none}

        /* Photo */
        .va-vcard-carousel{position:relative;overflow:hidden;background:${T_CREAM};aspect-ratio:4/3;cursor:pointer;margin:12px 12px 0;border-radius:14px}
        .va-vcard-slide{width:100%;height:100%}
        .va-vcard-unavail-overlay{position:absolute;inset:0;background:rgba(244,242,236,0.75);display:flex;align-items:center;justify-content:center;z-index:3}
        .va-vcard-unavail-overlay span{background:${T_SURFACE};color:${T_DANGER};padding:8px 20px;border-radius:20px;font-weight:700;font-size:.8rem;text-transform:uppercase;border:1px solid ${T_DANGER};box-shadow:0 4px 12px rgba(4,40,40,.1)}

        /* Category pill badge — top-left overlay on photo */
        .va-vcard-cat-badge{position:absolute;left:12px;top:12px;display:inline-flex;align-items:center;gap:6px;padding:6px 12px;background:${T_SURFACE};color:${T_TEAL};border-radius:999px;font-size:12px;font-weight:600;box-shadow:0 2px 10px rgba(4,40,40,.15);white-space:nowrap;z-index:4;pointer-events:none}
        .va-vcard-cat-badge svg{color:${T_TEAL}}

        /* Carousel controls */
        .va-vcard-cbtn{position:absolute;top:50%;transform:translateY(-50%);width:32px;height:44px;border-radius:10px;background:rgba(255,255,255,.92);border:1px solid ${T_BORDER};display:flex;align-items:center;justify-content:center;cursor:pointer;color:${T_INK};transition:all .3s;z-index:2;opacity:0;backdrop-filter:blur(4px)}
        .va-vcard:hover .va-vcard-cbtn{opacity:1}
        .va-vcard-cbtn:hover{background:${T_TEAL};border-color:${T_TEAL};color:#fff}
        .va-vcard-cbtn.prev{left:10px}.va-vcard-cbtn.next{right:10px}
        .va-vcard-dots{position:absolute;bottom:10px;left:50%;transform:translateX(-50%);display:flex;gap:5px;padding:3px 8px;background:rgba(255,255,255,.8);border-radius:20px;backdrop-filter:blur(4px);z-index:2}
        .va-vcard-dot{width:6px;height:6px;border-radius:50%;background:rgba(4,40,40,.35);transition:all .3s}
        .va-vcard-dot.active{background:${T_TEAL};width:18px;border-radius:4px}

        /* Info block */
        .va-vcard-info{padding:28px 22px 22px;display:flex;flex-direction:column;flex:1;text-align:center}
        .va-vcard-title{font-size:1.25rem;font-weight:700;color:${T_INK};line-height:1.25;margin:0 0 8px;letter-spacing:-0.01em}
        .va-vcard-tagline{font-size:.86rem;font-weight:400;color:${T_MUTED};line-height:1.45;margin:0 0 18px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:100%}

        /* Specs grid */
        .va-vcard-specs{list-style:none;padding:0;margin:0 0 22px;display:grid;grid-template-columns:1fr 1fr;gap:10px 14px;justify-content:center}
        .va-vcard-spec{display:inline-flex;align-items:center;gap:7px;font-size:.83rem;color:${T_TEAL};font-weight:600;padding:0;justify-content:flex-start;min-width:0}
        .va-vcard-spec svg{flex-shrink:0;color:${T_TEAL}}
        .va-vcard-spec span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}

        /* Price block */
        .va-vcard-price-block{display:flex;flex-direction:column;align-items:center;gap:2px;margin-bottom:18px}
        .va-vcard-price-from{font-size:.82rem;font-weight:400;color:${T_MUTED}}
        .va-vcard-price-row{display:flex;align-items:baseline;gap:6px}
        .va-vcard-price-num{font-size:2.6rem;font-weight:900;color:${T_TEAL};line-height:1;letter-spacing:-0.02em}
        .va-vcard-price-per{font-size:1rem;font-weight:400;color:${T_MUTED}}
        .va-vcard-price-note{font-size:11px;color:${T_MUTED};font-weight:400;margin-top:2px}
        .va-vcard-price-total{font-size:12px;color:${T_INK};font-weight:400;margin-top:4px}
        .va-vcard-price-total strong{font-weight:700;color:${T_INK}}

        /* Link row (Descriptif · Fiche technique) */
        .va-vcard-links-row{display:flex;align-items:center;justify-content:center;gap:10px;margin-bottom:16px}
        .va-vcard-links-dot{color:${T_BORDER_STRONG};font-weight:700}
        .va-vcard-details-link{color:${T_TEAL};font-size:.8rem;font-weight:600;text-decoration:none;display:inline-flex;align-items:center;gap:6px;padding:4px 2px;border-bottom:1px solid transparent;transition:all .2s}
        .va-vcard-details-link:hover{border-bottom-color:${T_TEAL}}

        /* CTA — Van-Away pill button */
        .va-vcard-select-btn{margin-top:auto;width:100%;padding:14px 22px;background:${T_TEAL};color:#fff;border:none;border-radius:999px;font-family:inherit;font-size:.95rem;font-weight:600;cursor:pointer;transition:all .25s ease;display:inline-flex;align-items:center;justify-content:center;gap:8px;letter-spacing:0.01em;box-shadow:0 2px 8px rgba(17,151,143,.15)}
        .va-vcard-select-btn:hover{transform:translateY(-1px);box-shadow:0 6px 18px rgba(17,151,143,.30);background:#1c7d77}
      `}</style>
    </div>
  );
}

function SpecIcon({ kind }) {
  const sp = { width:16, height:16, viewBox:'0 0 24 24', fill:'none', stroke:T_TEAL, strokeWidth:2, strokeLinecap:'round' };
  if (kind === 'seats')     return <svg {...sp}><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>;
  if (kind === 'gearbox')   return <svg {...sp}><circle cx="6" cy="6" r="3"/><circle cx="18" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><line x1="6" y1="9" x2="6" y2="15"/><line x1="18" y1="9" x2="18" y2="12"/><line x1="6" y1="12" x2="18" y2="12"/></svg>;
  if (kind === 'fuel')      return <svg {...sp}><path d="M3 22V5a2 2 0 012-2h8a2 2 0 012 2v17"/><path d="M15 10h2a2 2 0 012 2v3a1.5 1.5 0 003 0V9l-3-3"/><path d="M3 22h12"/><rect x="6" y="6" width="6" height="5" rx="1"/></svg>;
  if (kind === 'clim')      return <svg {...sp}><path d="M12 2v20M2 12h20M4.93 4.93l14.14 14.14M19.07 4.93L4.93 19.07"/></svg>;
  if (kind === 'gps')       return <svg {...sp}><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="3"/></svg>;
  if (kind === 'bluetooth') return <svg {...sp}><polyline points="6.5 6.5 17.5 17.5 12 23 12 1 17.5 6.5 6.5 17.5"/></svg>;
  const paths = {
    bed: 'M3 7v10m0-4h18m0 4V11a2 2 0 00-2-2H7a2 2 0 00-2 2v0',
    kitchen: 'M12 2v6m0 0l3-3m-3 3L9 5M3 12h18M5 22V12m14 10V12M9 22v-4a3 3 0 016 0v4',
    shower: 'M12 3v3m0 0a3 3 0 013 3v1M8 22v-6a4 4 0 018 0v6',
    solar: 'M12 3v1m0 16v1M21 12h-1M4 12H3M16 12a4 4 0 11-8 0 4 4 0 018 0z',
    water: 'M12 2c-4 6-7 9-7 13a7 7 0 0014 0c0-4-3-7-7-13z',
    toilet: 'M6 3h12v4a6 6 0 01-12 0V3zm2 10h8l1 8H7l1-8z',
    roof: 'M3 21h18M5 21V9l7-6 7 6v12',
  };
  const key = kind.startsWith('custom_') ? kind.slice(7) : kind;
  return <svg {...sp}><path d={paths[key] || 'M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z'}/></svg>;
}

// ─── Search summary sidebar ────────────────────────────────────
function SearchSidebar({ search, onUpdate, compact = false }) {
  const [editing, setEditing] = React.useState(false);
  const [agencySearch, setAgencySearch] = React.useState(search.agencyName);
  const [showDropdown, setShowDropdown] = React.useState(false);
  const [selectedAgencyId, setSelectedAgencyId] = React.useState(search.startAgencyId);
  const [startDate, setStartDate] = React.useState(search.startDate);
  const [endDate, setEndDate] = React.useState(search.endDate);
  const [error, setError] = React.useState('');

  const filtered = MOCK_AGENCIES.filter(a => {
    if (!agencySearch.trim()) return true;
    const q = agencySearch.toLowerCase();
    return a.public_name.toLowerCase().includes(q) || a.city.toLowerCase().includes(q);
  });

  const days = React.useMemo(() => {
    if (!startDate || !endDate) return 0;
    const s = new Date(startDate), e = new Date(endDate);
    return Math.max(0, Math.ceil((e - s) / 86400000));
  }, [startDate, endDate]);

  const formatFR = (iso) => {
    if (!iso) return '';
    const d = new Date(iso);
    return d.toLocaleDateString('fr-FR', { weekday: 'short', day: 'numeric', month: 'short', year: 'numeric' });
  };

  function selectAgency(a) {
    setSelectedAgencyId(a.id);
    setAgencySearch(`${a.public_name} - ${a.city}`);
    setShowDropdown(false);
  }

  function submit() {
    if (!selectedAgencyId) { setError('Veuillez sélectionner une agence'); return; }
    if (!startDate || !endDate) { setError('Veuillez sélectionner vos dates'); return; }
    if (days < 2) { setError('La durée minimale de location est de 2 jours'); return; }
    const agency = MOCK_AGENCIES.find(a => a.id === selectedAgencyId);
    onUpdate({
      startAgencyId: selectedAgencyId,
      agencyName: `${agency.public_name} - ${agency.city}`,
      startDate, endDate,
    });
    setEditing(false);
    setError('');
  }

  return (
    <aside className={`va-sidebar-wrap ${compact ? 'is-compact' : ''}`}>
      <div className="va-sidebar">
        <div className="va-sidebar-header">
          <svg width="20" height="20" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          <span>Votre recherche</span>
        </div>

        <div className="va-sidebar-body">
          {!editing ? (
            <>
              <div className="va-sidebar-field-label">
                <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                </svg>
                AGENCE
              </div>
              <div className="va-info-row">
                <span style={{color:T_INK,fontWeight:400,fontSize:13}}>{search.agencyName}</span>
              </div>

              <div className="va-sidebar-section-label">
                <div className="va-sidebar-line"/><div className="va-sidebar-section-text">DÉPART</div><div className="va-sidebar-line"/>
              </div>
              <div className="va-info-row">
                <svg width="16" height="16" fill="none" stroke={T_MUTED} viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/>
                </svg>
                <span style={{color:T_INK,fontWeight:400,fontSize:13}}>{formatFR(search.startDate)}</span>
              </div>

              <div className="va-sidebar-section-label">
                <div className="va-sidebar-line"/><div className="va-sidebar-section-text">RETOUR</div><div className="va-sidebar-line"/>
              </div>
              <div className="va-info-row">
                <svg width="16" height="16" fill="none" stroke={T_MUTED} viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/>
                </svg>
                <span style={{color:T_INK,fontWeight:400,fontSize:13}}>{formatFR(search.endDate)}</span>
              </div>

              <div className="va-sidebar-duration">
                <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
                {search.days} jours
              </div>

              <button className="va-sidebar-modify-btn" onClick={() => setEditing(true)}>
                Modifier ma recherche
              </button>
            </>
          ) : (
            <>
              <div className="va-sidebar-field-label">AGENCE</div>
              <div style={{position:'relative'}}>
                <div className="va-field-row">
                  <svg width="18" height="18" fill="none" stroke={T_MUTED} viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"/>
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"/>
                  </svg>
                  <input
                    value={agencySearch}
                    placeholder="Rechercher une agence..."
                    onChange={(e) => { setAgencySearch(e.target.value); setShowDropdown(true); }}
                    onFocus={() => { setAgencySearch(''); setShowDropdown(true); }}
                    onBlur={() => setTimeout(() => setShowDropdown(false), 200)}
                  />
                </div>
                {showDropdown && filtered.length > 0 && (
                  <div className="va-dropdown-menu">
                    {filtered.map(a => (
                      <button key={a.id} className="va-dropdown-option" onMouseDown={(e)=>{e.preventDefault(); selectAgency(a);}}>
                        <span className="va-dropdown-option-name">{a.public_name}</span>
                        <span className="va-dropdown-option-city">{a.city}</span>
                      </button>
                    ))}
                  </div>
                )}
              </div>

              <div className="va-sidebar-section-label">
                <div className="va-sidebar-line"/><div className="va-sidebar-section-text">DÉPART</div><div className="va-sidebar-line"/>
              </div>
              <div className="va-field-row">
                <svg width="18" height="18" fill="none" stroke={T_MUTED} viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/>
                </svg>
                <input type="date" value={startDate} onChange={(e)=>setStartDate(e.target.value)}/>
              </div>

              <div className="va-sidebar-section-label">
                <div className="va-sidebar-line"/><div className="va-sidebar-section-text">RETOUR</div><div className="va-sidebar-line"/>
              </div>
              <div className="va-field-row">
                <svg width="18" height="18" fill="none" stroke={T_MUTED} viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/>
                </svg>
                <input type="date" value={endDate} onChange={(e)=>setEndDate(e.target.value)}/>
              </div>

              {days > 0 && (
                <div className="va-sidebar-duration">
                  <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
                  </svg>
                  {days} {days > 1 ? 'jours' : 'jour'}
                </div>
              )}

              {error && <p className="va-error-msg">{error}</p>}

              <button className="va-sidebar-search-btn" onClick={submit}>
                <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
                Rechercher
              </button>
              <button className="va-sidebar-cancel-btn" onClick={() => setEditing(false)}>Annuler</button>
            </>
          )}
        </div>
      </div>

      {!compact && <ReassuranceBlock/>}

      <style>{`
        .va-sidebar-wrap{flex-shrink:0;width:300px}
        .va-sidebar-wrap.is-compact{width:100%}
        .va-sidebar{background:${T_SURFACE};border-radius:20px;box-shadow:0 1px 2px rgba(4,40,40,.04),0 4px 16px rgba(4,40,40,.06);border:1px solid ${T_BORDER};color:${T_INK}}
        .va-sidebar-wrap:not(.is-compact){position:sticky;top:72px;align-self:flex-start}
        .va-sidebar-header{padding:20px 20px 0;display:flex;align-items:center;gap:10px;color:${T_INK};font-size:16px;font-weight:700}
        .va-sidebar-header svg{color:${T_TEAL}}
        .va-sidebar-body{padding:18px 18px 22px}
        .va-sidebar-field-label{display:flex;align-items:center;gap:6px;font-size:11px;font-weight:700;color:${T_MUTED};text-transform:uppercase;letter-spacing:1px;margin-bottom:8px}
        .va-sidebar-field-label svg{color:${T_TEAL}}
        .va-sidebar-section-label{display:flex;align-items:center;gap:10px;margin:14px 0 8px}
        .va-sidebar-line{flex:1;height:1px;background:linear-gradient(90deg,transparent,${T_BORDER},transparent)}
        .va-sidebar-section-text{font-size:10px;font-weight:900;color:${T_TEAL};letter-spacing:2px}
        .va-info-row{display:flex;align-items:center;gap:10px;padding:10px 14px;border:1.5px solid ${T_BORDER};border-radius:12px;margin-bottom:6px;background:#fafaf6}
        .va-sidebar-duration{display:flex;align-items:center;justify-content:center;gap:7px;font-size:12px;font-weight:700;color:${T_TEAL};background:#e7fcfb;border:1px solid rgba(17,151,143,.18);border-radius:999px;padding:10px 16px;margin-top:8px}
        .va-sidebar-modify-btn{width:100%;padding:12px;margin-top:14px;border:1.5px solid ${T_BORDER_STRONG};border-radius:999px;background:transparent;color:${T_MUTED};font-family:inherit;font-size:13px;font-weight:600;cursor:pointer;transition:all .2s}
        .va-sidebar-modify-btn:hover{border-color:${T_TEAL};color:${T_TEAL};background:rgba(17,151,143,.04)}
        .va-field-row{display:flex;align-items:center;gap:10px;padding:10px 12px;border:1.5px solid ${T_BORDER};border-radius:12px;margin-bottom:8px;background:${T_SURFACE};transition:all .25s ease}
        .va-field-row:focus-within{border-color:${T_TEAL};box-shadow:0 0 0 3px rgba(17,151,143,.12)}
        .va-field-row input{border:none;outline:none;background:transparent;font-family:inherit;font-size:13px;color:${T_INK};width:100%;font-weight:400}
        .va-field-row input::placeholder{color:${T_MUTED}}
        .va-dropdown-menu{position:absolute;top:calc(100% + 4px);left:0;right:0;background:${T_SURFACE};border:1.5px solid ${T_BORDER};border-radius:12px;box-shadow:0 12px 40px rgba(4,40,40,.15);z-index:60;max-height:220px;overflow-y:auto;padding:4px}
        .va-dropdown-option{display:flex;flex-direction:column;width:100%;text-align:left;padding:8px 12px;border:none;background:none;cursor:pointer;border-radius:8px;font-family:inherit}
        .va-dropdown-option:hover{background:${T_CREAM}}
        .va-dropdown-option-name{font-size:13px;font-weight:400;color:${T_INK}}
        .va-dropdown-option-city{font-size:11px;color:${T_MUTED}}
        .va-sidebar-search-btn{display:flex;align-items:center;justify-content:center;gap:6px;width:100%;padding:13px;margin-top:12px;border:none;border-radius:999px;background:${T_TEAL};color:#fff;font-family:inherit;font-size:14px;font-weight:600;cursor:pointer;transition:all .3s;box-shadow:0 2px 8px rgba(17,151,143,.18)}
        .va-sidebar-search-btn:hover{transform:translateY(-1px);box-shadow:0 6px 16px rgba(17,151,143,.35);background:#1c7d77}
        .va-sidebar-cancel-btn{width:100%;padding:10px;margin-top:6px;border:none;border-radius:12px;background:transparent;color:${T_MUTED};font-family:inherit;font-size:12px;font-weight:600;cursor:pointer;transition:all .2s}
        .va-sidebar-cancel-btn:hover{color:${T_INK};background:${T_CREAM}}
        .va-error-msg{display:flex;align-items:center;gap:6px;font-size:12px;color:${T_DANGER};margin-top:8px}
      `}</style>
    </aside>
  );
}

// ─── Main screen ───────────────────────────────────────────────
function VehiclesScreen({ compact = false }) {
  const [search, setSearch] = React.useState({
    startAgencyId: 1,
    agencyName: 'Van-Away Bordeaux - Bordeaux',
    startDate: '2026-06-12',
    endDate: '2026-06-20',
    days: 8,
  });
  const [activeCategory, setActiveCategory] = React.useState('all');
  const [detailVehicleId, setDetailVehicleId] = React.useState(null);

  const updateSearch = (u) => {
    const s = new Date(u.startDate), e = new Date(u.endDate);
    const days = Math.max(0, Math.ceil((e - s) / 86400000));
    setSearch({ ...search, ...u, days });
  };

  const categories = [
    { id: 'all',        name: 'TOUT' },
    { id: 'VAN',        name: 'VANS' },
    { id: 'FOURGON',    name: 'FOURGONS' },
    { id: 'ÉQUIPEMENT', name: 'ÉQUIPEMENTS' },
  ];

  const filteredVehicles = activeCategory === 'all'
    ? MOCK_VEHICLES
    : MOCK_VEHICLES.filter(v => v.category_name === activeCategory);

  const filteredUnavail = activeCategory === 'all'
    ? UNAVAIL_VEHICLES
    : UNAVAIL_VEHICLES.filter(v => v.category_name === activeCategory);

  return (
    <>
    <div className={`va-vehicles ${compact ? 'is-compact' : ''}`}>
      <SearchSidebar search={search} onUpdate={updateSearch} compact={compact}/>

      <main className="va-vehicles-main">
        <div className="va-cat-tabs-wrap">
          <div className="va-cat-tabs-scroll">
            {categories.map(c => (
              <button key={c.id}
                className={`va-cat-tab ${activeCategory === c.id ? 'active' : ''}`}
                onClick={() => setActiveCategory(c.id)}>
                {c.name}
              </button>
            ))}
          </div>
          <div className="va-cat-tabs-count">
            {!compact && <GoogleReviewsBadge compact={compact}/>}
          </div>
        </div>

        {filteredVehicles.length > 0 && (
          <div className="va-avail-banner">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M5 13l4 4L19 7"/>
            </svg>
            <span>Disponibles pour vos dates</span>
          </div>
        )}

        <div className="va-vehicles-grid">
          {filteredVehicles.map((v, i) => (
            <VehicleCard key={v.id} vehicle={v} days={search.days} startDate={search.startDate} index={i}
              onSelect={(id)=>console.log('select', id)} onShowDetails={(id)=>setDetailVehicleId(id)}/>
          ))}
        </div>

        {filteredUnavail.length > 0 && (
          <>
            <div className="va-unavail-separator">
              <span>
                {filteredUnavail.length} {filteredUnavail.length > 1 ? 'autres véhicules ne sont pas disponibles' : "autre véhicule n'est pas disponible"} pour ces dates
              </span>
            </div>
            <div className="va-vehicles-grid">
              {filteredUnavail.map((v, i) => (
                <VehicleCard key={v.id} vehicle={v} days={search.days} startDate={search.startDate} index={i} unavailable
                  onShowDetails={(id)=>setDetailVehicleId(id)}/>
              ))}
            </div>
          </>
        )}
      </main>

      {compact && detailVehicleId !== null && (() => {
        const v = [...MOCK_VEHICLES, ...UNAVAIL_VEHICLES].find(x => x.id === detailVehicleId);
        if (!v) return null;
        const pricing = { '1-10':{basse:90,moyenne:120,haute:150}, '11-30':{basse:85,moyenne:100,haute:140}, '31+':{basse:70,moyenne:75,haute:120} };
        const bracket = search.days <= 10 ? pricing['1-10'] : search.days <= 30 ? pricing['11-30'] : pricing['31+'];
        const month = search.startDate ? new Date(search.startDate).getMonth() + 1 : 5;
        const season = (month >= 7 && month <= 8) ? 'haute' : ((month >= 4 && month <= 6) || month === 9) ? 'moyenne' : 'basse';
        return <VehicleDetailModal vehicle={v} days={search.days} dailyPrice={bracket[season]} compact={true}
          onClose={()=>setDetailVehicleId(null)}
          onSelect={(id)=>{setDetailVehicleId(null); console.log('select', id);}}/>;
      })()}

      <style>{`
        .va-vehicles{display:flex;flex-direction:row;gap:24px;padding:24px;background:#fafaf6;min-height:calc(100vh - 56px - 34px)}
        .va-vehicles.is-compact{flex-direction:column;gap:16px;padding:16px;position:relative}
        .va-vehicles.is-compact .va-sidebar{position:static}
        .va-vehicles-main{flex:1;min-width:0}
        .va-cat-tabs-wrap{display:flex;align-items:center;gap:14px;margin-bottom:20px;padding:0 4px;border-bottom:1px solid ${T_BORDER}}
        .va-cat-tabs-scroll{display:flex;gap:0;flex:1;min-width:0;overflow-x:auto;scrollbar-width:none}
        .va-cat-tabs-scroll::-webkit-scrollbar{display:none}
        .va-cat-tabs-count{flex-shrink:0;white-space:nowrap;padding-bottom:6px;display:flex;align-items:center}
        .va-cat-tab{display:inline-flex;align-items:center;padding:10px 18px;font-family:inherit;font-size:13px;font-weight:600;color:${T_MUTED};background:transparent;border:none;cursor:pointer;transition:all .25s;white-space:nowrap;position:relative}
        .va-cat-tab:hover{color:${T_INK}}
        .va-cat-tab.active{color:${T_TEAL}}
        .va-cat-tab.active::after{content:'';position:absolute;bottom:0;left:0;right:0;height:2px;background:${T_TEAL};border-radius:2px 2px 0 0}
        .va-vehicles-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(320px,100%),1fr));gap:24px}
        .va-vehicles.is-compact .va-vehicles-grid{grid-template-columns:1fr;gap:16px}
        .va-unavail-separator{margin:24px 0 16px;display:flex;align-items:center;gap:12px}
        .va-unavail-separator::before,.va-unavail-separator::after{content:'';flex:1;height:1px;background:${T_BORDER}}
        .va-unavail-separator span{font-size:12px;font-weight:600;color:${T_MUTED};white-space:nowrap;text-transform:uppercase;letter-spacing:.5px}
        .va-avail-banner{display:inline-flex;align-items:center;gap:8px;padding:8px 14px;margin:0 0 18px;background:#e7fcfb;border:1px solid rgba(17,151,143,.25);border-radius:999px;color:${T_TEAL};font-size:13px;font-weight:700;letter-spacing:.01em}
        .va-avail-banner svg{color:${T_TEAL}}
      `}</style>
    </div>
    <HelpBlockV1 search={search} compact={compact}/>
    {!compact && detailVehicleId !== null && (() => {
      const v = [...MOCK_VEHICLES, ...UNAVAIL_VEHICLES].find(x => x.id === detailVehicleId);
      if (!v) return null;
      const pricing = { '1-10':{basse:90,moyenne:120,haute:150}, '11-30':{basse:85,moyenne:100,haute:140}, '31+':{basse:70,moyenne:75,haute:120} };
      const bracket = search.days <= 10 ? pricing['1-10'] : search.days <= 30 ? pricing['11-30'] : pricing['31+'];
      const month = search.startDate ? new Date(search.startDate).getMonth() + 1 : 5;
      const season = (month >= 7 && month <= 8) ? 'haute' : ((month >= 4 && month <= 6) || month === 9) ? 'moyenne' : 'basse';
      return <VehicleDetailModal vehicle={v} days={search.days} dailyPrice={bracket[season]} compact={false}
        onClose={()=>setDetailVehicleId(null)}
        onSelect={(id)=>{setDetailVehicleId(null); console.log('select', id);}}/>;
    })()}
    </>
  );
}

Object.assign(window, { VehiclesScreen, VehicleCard, SearchSidebar });
Object.assign(window, { VehiclesScreenV1: VehiclesScreen, VehicleCardV1: VehicleCard, SearchSidebarV1: SearchSidebar });

})();
