(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',
    highlight: { emoji: '👫', text: 'Roadtrip à 2 !' }, lastOne: true,
    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',
    highlight: { emoji: '👨‍👩‍👧‍👦', text: 'Idéal familles !' },
    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' },
    ],
  },
  {
    id: 3, display_name: 'Fourgon Grand Nomade', category_name: 'FOURGON', lastOne: true,
    tagline: 'Fourgon aménagé spacieux, 4 places, cuisine complète et douche intérieure.',
    brand: 'Fiat', model: 'Ducato', nb_places: 4, nb_doors: 3,
    gearbox: 'Manuelle', energy: 'Diesel',
    specificities: { cooling: true, gps: true },
    custom_equipments: [{ icon: 'bed', text: '4 couchages' }, { icon: 'shower', text: 'Douche intérieure' }],
    photo_hue: 220,
    description: "Le Grand Nomade est un fourgon aménagé tout confort : cuisine complète, douche intérieure et vrai lit double à l'arrière pour des road-trips au long cours.",
    equipments: ['Climatisation', 'GPS', 'Cuisine', 'Réfrigérateur', 'Douche', 'Chauffage stationnaire', 'Auvent'],
    mileage_levels: [
      { id: 'm1', mileage: 200, amount: 0, unlimited: false },
      { id: 'm2', mileage: 300, amount: 9, unlimited: false },
      { id: 'm3', mileage: 0, amount: 20, unlimited: true },
    ],
    included_options: [
      { option_id: 'i1', name: 'Vaisselle 4 personnes' }, { option_id: 'i2', name: 'Kit de cuisine' }, { option_id: 'i3', name: 'Linge de lit' },
    ],
    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' },
    ],
  },
  {
    id: 4, display_name: '4x4 Explorer', category_name: '4X4',
    highlight: { emoji: '🏔️', text: 'Aventure hors-piste !' },
    tagline: '4x4 aménagé avec tente de toit, pour sortir des sentiers battus à 2.',
    brand: 'Toyota', model: 'Hilux', nb_places: 2, nb_doors: 4,
    gearbox: 'Manuelle', energy: 'Diesel',
    specificities: { cooling: true, gps: true },
    custom_equipments: [{ icon: 'roof', text: 'Tente de toit' }, { icon: 'kitchen', text: 'Cuisine extérieure' }],
    photo_hue: 90,
    description: "Le 4x4 Explorer est équipé d'une tente de toit et d'une cuisine extérieure : l'outil idéal pour les aventuriers qui veulent camper partout, même hors des sentiers battus.",
    equipments: ['Climatisation', 'GPS', 'Tente de toit', 'Cuisine extérieure', 'Réfrigérateur', 'Treuil'],
    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: 'Tente de toit 2 places' }, { option_id: 'i2', name: 'Kit de cuisine nomade' },
    ],
    paid_options: [
      { option_id: 'p1', name: 'Douche solaire', amount: 4, pricing_type: 'per_day' },
      { option_id: 'p2', name: 'Glacière électrique', amount: 6, pricing_type: 'per_day' },
    ],
  },
  {
    id: 5, display_name: 'Minibus Torino', category_name: 'MINIBUS',
    tagline: 'Minibus 9 places, parfait pour voyager en tribu ou entre amis.',
    brand: 'Renault', model: 'Trafic', nb_places: 9, nb_doors: 4,
    gearbox: 'Automatique', energy: 'Diesel',
    specificities: { cooling: true, gps: true, bluetooth: true },
    custom_equipments: [{ icon: 'bed', text: '9 sièges confort' }],
    photo_hue: 320,
    description: "Le Minibus Torino embarque jusqu'à 9 passagers dans un grand confort : climatisation, sièges modulables et grand coffre pour tous vos bagages.",
    equipments: ['Climatisation', 'GPS', 'Bluetooth', 'Régulateur de vitesse', 'USB', 'Grand coffre'],
    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: 'Sièges modulables' }, { option_id: 'i2', name: 'Kit sécurité' },
    ],
    paid_options: [
      { option_id: 'p1', name: 'Siège bébé', amount: 5, pricing_type: 'per_day' },
      { option_id: 'p2', name: 'Remorque bagages', amount: 12, pricing_type: 'per_day' },
    ],
  },
  {
    id: 6, display_name: 'Tente de toit Nomad', category_name: 'ÉQUIPEMENT',
    tagline: 'Tente de toit 2 places à monter sur votre propre véhicule.',
    brand: 'Naïtup', model: 'Hussarde', nb_places: 2,
    custom_equipments: [{ icon: 'roof', text: 'Montage inclus' }, { icon: 'bed', text: '2 couchages' }],
    photo_hue: 45,
    description: "La tente de toit Nomad transforme votre voiture en mini-camping-car : montage par nos équipes, matelas haute densité et ouverture en moins d'une minute.",
    equipments: ['Matelas haute densité', 'Échelle', 'Housse de protection'],
    mileage_levels: [
      { id: 'm1', mileage: 0, amount: 0, unlimited: true },
    ],
    included_options: [
      { option_id: 'i1', name: 'Montage / démontage' },
    ],
    paid_options: [
      { option_id: 'p1', name: 'Kit literie', amount: 15, 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>;
  if (kind === '4X4')        return <svg {...sp}><path d="M4 16V11l3-4h8l3 4h2v5"/><circle cx="7.5" cy="17" r="1.8"/><circle cx="16.5" cy="17" r="1.8"/><path d="M9.3 17h4.9"/></svg>;
  if (kind === 'MINIBUS')    return <svg {...sp}><rect x="2" y="6" width="20" height="11" rx="2"/><path d="M2 11h20M7 6v5m5-5v5m5-5v5"/><circle cx="7" cy="18.5" r="1.6"/><circle cx="17" cy="18.5" r="1.6"/></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' ? 'Fourgon aménagé'
                 : vehicle.category_name === '4X4' ? '4x4'
                 : vehicle.category_name === 'MINIBUS' ? 'Minibus'
                 : 'É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>

        {/* Highlight pill (marketing) — top-left of photo */}
        {vehicle.highlight && (
          <div className="va-vcard-hl-badge">
            <span className="va-vcard-hl-emoji">{vehicle.highlight.emoji}</span>
            <span>{vehicle.highlight.text}</span>
          </div>
        )}

        {/* Category pill — à cheval sur le bas de la photo */}
        <div className="va-vcard-cat-badge">
          <CatIcon kind={vehicle.category_name} size={16}/>
          <span>{catLabel}</span>
        </div>

        {/* Available / Dernier disponible — top-right of photo */}
        {!unavailable && (vehicle.lastOne ? (
          <div className="va-vcard-last-badge">Dernier disponible !</div>
        ) : (
          <div className="va-vcard-avail-badge">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
              <path d="M5 13l4 4L19 7"/>
            </svg>
            <span>Disponible</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>

      <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-card">
              <div className="va-vcard-price-left">
                <span className="va-vcard-price-total-num">{dailyPrice * days} €</span>
                <span className="va-vcard-price-total-sub">total · {days} {days > 1 ? 'jours' : 'jour'}</span>
              </div>
              <div className="va-vcard-price-right">
                <span className="va-vcard-price-daily">{dailyPrice} €<span className="va-vcard-price-daily-per">/jour</span></span>
                <span className="va-vcard-price-insurance">Assurance comprise</span>
              </div>
            </div>

            <div className="va-vcard-btn-row">
              <button className="va-vcard-view-btn" onClick={() => onShowDetails?.(vehicle.id)}>
                Détails
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" style={{marginLeft:8}}>
                  <line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/>
                </svg>
              </button>
              <button className="va-vcard-select-btn" onClick={() => onSelect?.(vehicle.id)}>
                Sélectionner
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" style={{marginLeft:8}}>
                  <line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/>
                </svg>
              </button>
            </div>
          </>
        )}
        {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:visible;background:${T_CREAM};aspect-ratio:4/3;cursor:pointer;margin:12px 12px 0;border-radius:14px}
        .va-vcard-slide{width:100%;height:100%;border-radius:14px;overflow:hidden}
        .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;border-radius:14px}
        .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 — à cheval sur le bas de la photo (style site) */
        .va-vcard-cat-badge{position:absolute;left:50%;bottom:0;transform:translate(-50%,50%);display:inline-flex;align-items:center;gap:7px;padding:8px 18px;background:#e7fcfb;border:2px solid #fff;color:${T_TEAL};border-radius:999px;font-size:13px;font-weight:600;box-shadow:0 2px 12px rgba(4,40,40,.14);white-space:nowrap;z-index:5;pointer-events:none}
        .va-vcard-cat-badge svg{color:${T_TEAL}}

        /* Highlight pill — marketing badge top-left on photo */
        .va-vcard-hl-badge{position:absolute;left:12px;top:12px;display:inline-flex;align-items:center;gap:8px;padding:5px 14px 5px 5px;background:${T_TEAL};color:#fff;border-radius:999px;font-size:12.5px;font-weight:700;letter-spacing:.01em;box-shadow:0 2px 12px rgba(4,40,40,.18);white-space:nowrap;z-index:4;pointer-events:none}
        .va-vcard-hl-emoji{display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;border-radius:999px;background:#fff;font-size:13px;line-height:1}

        /* Dernier disponible — badge alerte top-right */
        .va-vcard-last-badge{position:absolute;right:12px;top:12px;padding:7px 14px;background:#E8740C;color:#fff;border-radius:999px;font-size:12.5px;font-weight:700;letter-spacing:.01em;box-shadow:0 2px 12px rgba(4,40,40,.22);white-space:nowrap;z-index:4;pointer-events:none}

        /* Available pill — top-right overlay on photo (same style as avail-banner) */
        .va-vcard-avail-badge{position:absolute;right:12px;top:12px;display:inline-flex;align-items:center;gap:7px;padding:7px 14px;background:#e7fcfb;border:1px solid rgba(17,151,143,.25);color:${T_TEAL};border-radius:999px;font-size:12.5px;font-weight:700;letter-spacing:.01em;white-space:nowrap;z-index:4;pointer-events:none;box-shadow:0 2px 12px rgba(4,40,40,.14)}
        .va-vcard-avail-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:34px 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 card (v2 redesign) */
        .va-vcard-price-card{display:flex;align-items:center;justify-content:space-between;background:#e7fcfb;border-radius:14px;padding:16px 20px;margin-bottom:18px;gap:12px}
        .va-vcard-price-left{display:flex;flex-direction:column;align-items:flex-start;gap:2px}
        .va-vcard-price-total-num{font-size:2.4rem;font-weight:700;color:${T_TEAL};line-height:1;letter-spacing:-0.02em}
        .va-vcard-price-total-sub{font-size:.85rem;font-weight:400;color:${T_MUTED}}
        .va-vcard-price-right{display:flex;flex-direction:column;align-items:flex-end;gap:2px}
        .va-vcard-price-daily{font-size:1.05rem;font-weight:700;color:${T_INK};line-height:1.1}
        .va-vcard-price-daily-per{font-size:.85rem;font-weight:400;color:${T_INK};margin-left:2px}
        .va-vcard-price-insurance{font-size:.82rem;font-weight:400;color:${T_MUTED}}

        /* 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-btn-row{margin-top:auto;display:flex;gap:10px;align-items:stretch}
        .va-vcard-view-btn{flex:1 1 0;padding:14px 20px;background:#fff;color:${T_TEAL};border:1.5px solid ${T_BORDER_STRONG};border-radius:999px;font-family:inherit;font-size:.95rem;font-weight:600;cursor:pointer;transition:all .25s cubic-bezier(.4,0,.2,1);white-space:nowrap;display:inline-flex;align-items:center;justify-content:center;gap:6px}
        .va-vcard-view-btn:hover{border-color:${T_TEAL};background:#e7fcfb;transform:translateY(-1px)}
        .va-vcard-select-btn{flex:1 1 0;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 cubic-bezier(.4,0,.2,1);display:inline-flex;align-items:center;justify-content:center;gap:6px;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 sidebar (formulaire + calendrier inline) ──────────────
const SS_TIMES = ['08:00','08:30','09:00','09:30','10:00','10:30','11:00','11:30','12:00','14:00','14:30','15:00','15:30','16:00','16:30','17:00','17:30','18:00'];
function SearchSidebar({ search, onUpdate, compact = false, variant = 'default' }) {
  const pad = (n) => String(n).padStart(2, '0');
  const isoOf = (y, m, d) => `${y}-${pad(m + 1)}-${pad(d)}`;
  const TODAY = new Date(); TODAY.setHours(0, 0, 0, 0);

  const init = search.startDate ? new Date(search.startDate) : TODAY;
  const [viewYear, setViewYear] = React.useState(init.getFullYear());
  const [viewMonth, setViewMonth] = React.useState(init.getMonth());
  const [startDate, setStartDate] = React.useState(search.startDate);
  const [endDate, setEndDate] = React.useState(search.endDate);
  const [startTime, setStartTime] = React.useState('09:00');
  const [endTime, setEndTime] = React.useState('17:00');
  const [agencyId, setAgencyId] = React.useState(search.startAgencyId);
  const [agencyName, setAgencyName] = React.useState(search.agencyName);
  const [agencyOpen, setAgencyOpen] = React.useState(false);
  const [error, setError] = React.useState('');

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

  // Grille du mois affiché — semaines lun→dim, avec débordements mois adjacents
  const grid = React.useMemo(() => {
    const first = new Date(viewYear, viewMonth, 1);
    const offset = (first.getDay() + 6) % 7; // lundi = 0
    const cells = [];
    const gridStart = new Date(viewYear, viewMonth, 1 - offset);
    for (let i = 0; i < 42; i++) {
      const d = new Date(gridStart); d.setDate(gridStart.getDate() + i);
      cells.push(d);
    }
    // coupe la derniere semaine si entierement hors mois
    while (cells.length > 35 && cells[35].getMonth() !== viewMonth) cells.splice(35, 7);
    return cells;
  }, [viewYear, viewMonth]);

  const isDisabled = (d) => d < TODAY || d.getDay() === 0; // passé ou dimanche (agence fermée)
  const isOtherMonth = (d) => d.getMonth() !== viewMonth;

  function pickDay(d) {
    if (isDisabled(d)) return;
    const iso = isoOf(d.getFullYear(), d.getMonth(), d.getDate());
    if (!startDate || (startDate && endDate) || iso < startDate) {
      setStartDate(iso); setEndDate('');
    } else if (iso === startDate) {
      setStartDate(''); setEndDate('');
    } else {
      setEndDate(iso);
      onUpdate({ startAgencyId: agencyId, agencyName, startDate, endDate: iso });
    }
    setError('');
  }

  function navMonth(delta) {
    const d = new Date(viewYear, viewMonth + delta, 1);
    setViewYear(d.getFullYear()); setViewMonth(d.getMonth());
  }

  function selectAgency(a) {
    setAgencyId(a.id);
    setAgencyName(`${a.public_name} - ${a.city}`);
    setAgencyOpen(false);
    if (startDate && endDate) onUpdate({ startAgencyId: a.id, agencyName: `${a.public_name} - ${a.city}`, startDate, endDate });
  }

  function submit() {
    if (!agencyId) { 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; }
    onUpdate({ startAgencyId: agencyId, agencyName, startDate, endDate });
    setError('');
  }

  const monthLabelRaw = new Date(viewYear, viewMonth, 1).toLocaleDateString('fr-FR', { month: 'long', year: 'numeric' });
  const monthLabel = monthLabelRaw.charAt(0).toUpperCase() + monthLabelRaw.slice(1);

  return (
    <aside className={`va-sidebar-wrap ${compact ? 'is-compact' : ''}`}>
      <div className="va-sidebar" data-variant={variant}>
        <div className="va-ss-header">
          <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.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-ss-body">
          <div style={{position:'relative'}}>
            <button type="button" className="va-ss-agency" onClick={() => setAgencyOpen(o => !o)}>
              <span className="va-ss-agency-name">{agencyName}</span>
              <svg width="15" height="15" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>
              </svg>
            </button>
            {agencyOpen && (
              <div className="va-dropdown-menu">
                {MOCK_AGENCIES.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-ss-cal">
            <div className="va-ss-cal-nav">
              <button type="button" className="va-ss-cal-btn" onClick={()=>navMonth(-1)} aria-label="Mois précédent">
                <svg width="13" height="13" 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>
              <span className="va-ss-cal-month">{monthLabel}</span>
              <button type="button" className="va-ss-cal-btn" onClick={()=>navMonth(1)} aria-label="Mois suivant">
                <svg width="13" height="13" 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>
            <div className="va-ss-cal-grid">
              {['LUN','MAR','MER','JEU','VEN','SAM','DIM'].map(d => <span key={d} className="va-ss-cal-dow">{d}</span>)}
              {grid.map((d, i) => {
                const iso = isoOf(d.getFullYear(), d.getMonth(), d.getDate());
                const disabled = isDisabled(d) || isOtherMonth(d);
                const isStart = iso === startDate, isEnd = iso === endDate;
                const inRange = startDate && endDate && iso > startDate && iso < endDate;
                return (
                  <button key={i} type="button"
                    className={`va-ss-cal-day ${disabled?'is-off':''} ${isStart||isEnd?'is-sel':''} ${inRange?'is-range':''}`}
                    disabled={disabled} onClick={()=>pickDay(d)}>
                    {d.getDate()}
                  </button>
                );
              })}
            </div>
          </div>

          <div className="va-ss-times">
            <div className="va-ss-time">
              <div className="va-ss-label" style={{marginBottom:6}}>Heure de départ</div>
              <div className="va-ss-select">
                <select value={startTime} onChange={(e)=>setStartTime(e.target.value)}>
                  {SS_TIMES.map(t => <option key={t} value={t}>{t}</option>)}
                </select>
              </div>
            </div>
            <div className="va-ss-time">
              <div className="va-ss-label" style={{marginBottom:6}}>Heure de retour</div>
              <div className="va-ss-select">
                <select value={endTime} onChange={(e)=>setEndTime(e.target.value)}>
                  {SS_TIMES.map(t => <option key={t} value={t}>{t}</option>)}
                </select>
              </div>
            </div>
          </div>
          <p className="va-ss-note">Pour tout autre horaire de départ hors horaire agence, merci de contacter votre agence.</p>

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

      {!compact && <ReassuranceBlock variant={window.__vaReassVariant || 'default'}/>}
      {compact && <ReassAccordion/>}

      <style>{`
        .va-sidebar-wrap{flex-shrink:0;width:320px}
        .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};overflow:hidden}
        .va-sidebar-wrap:not(.is-compact){position:sticky;top:72px;align-self:flex-start}
        .va-ss-header{background:${T_TEAL};color:#fff;padding:15px 20px;display:flex;align-items:center;gap:10px;font-size:13px;font-weight:900;text-transform:uppercase;letter-spacing:.8px}
        .va-ss-body{padding:18px 18px 22px}
        .va-ss-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-ss-label svg{color:${T_TEAL}}
        .va-ss-agency{display:flex;align-items:center;justify-content:space-between;gap:10px;width:100%;padding:12px 14px;border:1.5px solid ${T_BORDER};border-radius:12px;background:#fafaf6;font-family:inherit;font-size:13.5px;font-weight:600;color:${T_INK};cursor:pointer;transition:all .2s;text-align:left}
        .va-ss-agency:hover{border-color:${T_TEAL}}
        .va-ss-agency svg{color:${T_MUTED};flex-shrink:0}
        .va-ss-agency-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
        .va-ss-cal{margin-top:16px}
        .va-ss-cal-nav{display:flex;align-items:center;justify-content:space-between;margin-bottom:10px}
        .va-ss-cal-btn{width:32px;height:32px;border-radius:999px;border:1.5px solid ${T_BORDER_STRONG};background:#fff;color:${T_INK};display:flex;align-items:center;justify-content:center;cursor:pointer;transition:all .2s}
        .va-ss-cal-btn:hover{border-color:${T_TEAL};color:${T_TEAL}}
        .va-ss-cal-month{font-size:16px;font-weight:900;color:${T_INK}}
        .va-ss-cal-grid{display:grid;grid-template-columns:repeat(7,1fr);gap:2px 0}
        .va-ss-cal-dow{font-size:10.5px;font-weight:700;color:${T_MUTED};text-align:center;letter-spacing:.5px;padding:6px 0}
        .va-ss-cal-day{aspect-ratio:1;border:none;background:none;font-family:inherit;font-size:13.5px;font-weight:700;color:${T_INK};cursor:pointer;border-radius:999px;transition:all .15s;display:flex;align-items:center;justify-content:center}
        .va-ss-cal-day:hover:not(:disabled){background:#e7fcfb;color:${T_TEAL}}
        .va-ss-cal-day.is-off{color:rgba(4,40,40,.22);font-weight:400;cursor:default}
        .va-ss-cal-day.is-sel{background:${T_TEAL};color:#fff}
        .va-ss-cal-day.is-sel:hover{background:${T_TEAL};color:#fff}
        .va-ss-cal-day.is-range{background:#e7fcfb;color:${T_TEAL};border-radius:0}
        .va-ss-times{display:flex;gap:10px;margin-top:16px}
        .va-ss-time{flex:1;min-width:0}
        .va-ss-select{position:relative}
        .va-ss-select select{width:100%;padding:11px 12px;border:1.5px solid ${T_BORDER};border-radius:12px;background:#fff;font-family:inherit;font-size:14px;font-weight:700;color:${T_INK};cursor:pointer;appearance:auto;transition:all .2s}
        .va-ss-select select:focus{outline:none;border-color:${T_TEAL};box-shadow:0 0 0 3px rgba(17,151,143,.12)}
        .va-ss-note{font-size:12px;font-weight:400;color:${T_MUTED};line-height:1.45;margin:10px 0 0}
        .va-ss-duration{display:flex;align-items:center;justify-content:center;gap:7px;font-size:14px;font-weight:700;color:${T_TEAL};padding:12px 0 0}
        .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:14px;margin-top:14px;border:none;border-radius:999px;background:${T_TEAL};color:#fff;font-family:inherit;font-size:14.5px;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-error-msg{display:flex;align-items:center;gap:6px;font-size:12px;color:${T_DANGER};margin-top:8px}
      `}</style>
    </aside>
  );
}

// ─── Bloc agence à proximité ────────────────────────────
function NearbyAgencyBlock({ search, compact = false }) {
  const city = (search.agencyName || '').split(' - ').pop() || 'Toulouse';
  return (
    <section className={`va-nearby ${compact ? 'is-compact' : ''}`}>
      <div className="va-nearby-icon" aria-hidden="true">
        <svg width="46" height="46" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
          <path 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"/>
          <circle cx="12" cy="11" r="3"/>
        </svg>
      </div>
      <div className="va-nearby-content">
        <h3 className="va-nearby-title">Vous n'avez pas trouvé le van idéal ?</h3>
        <p className="va-nearby-text">Une autre agence Van-Away à moins de 300 km de <strong>{city}</strong> propose d'autres modèles disponibles pour ces dates. Cliquez sur sa ville pour voir ses véhicules.</p>
        <button type="button" className="va-nearby-btn" onClick={()=>console.log('nearby agency')}>
          <strong>Bordeaux</strong> (212 km)
        </button>
        <p className="va-nearby-note">La distance affichée est depuis <strong>{city}</strong>.</p>
      </div>
      <style>{`
        .va-nearby{display:flex;gap:24px;align-items:flex-start;background:${T_SURFACE};border:1px solid ${T_BORDER};border-radius:20px;box-shadow:0 1px 2px rgba(4,40,40,.04),0 4px 20px rgba(4,40,40,.06);padding:28px 30px;margin-top:28px}
        .va-nearby-icon{flex-shrink:0;color:${T_TEAL};padding-top:4px}
        .va-nearby-content{flex:1;min-width:0}
        .va-nearby-title{margin:0 0 8px;font-size:1.1rem;font-weight:700;color:${T_INK}}
        .va-nearby-text{margin:0 0 18px;font-size:.92rem;font-weight:400;color:${T_MUTED};line-height:1.55}
        .va-nearby-text strong{color:${T_INK};font-weight:700}
        .va-nearby-btn{display:inline-flex;align-items:center;gap:5px;padding:13px 22px;background:${T_TEAL};color:#fff;border:none;border-radius:999px;font-family:inherit;font-size:.95rem;font-weight:400;cursor:pointer;transition:all .25s cubic-bezier(.4,0,.2,1);box-shadow:0 2px 8px rgba(17,151,143,.15)}
        .va-nearby-btn strong{font-weight:700}
        .va-nearby-btn:hover{background:#1c7d77;transform:translateY(-1px);box-shadow:0 6px 18px rgba(17,151,143,.30)}
        .va-nearby-note{margin:16px 0 0;font-size:.85rem;color:${T_MUTED};text-align:center}
        .va-nearby-note strong{color:${T_INK};font-weight:700}
        .va-nearby.is-compact{flex-direction:column;align-items:center;text-align:center;gap:10px;padding:24px 20px}
        .va-nearby.is-compact .va-nearby-note{text-align:center}
      `}</style>
    </section>
  );
}

// ─── Accordion réassurance (mobile) — fermé par défaut ──────────────
function ReassAccordion() {
  const [open, setOpen] = React.useState(false);
  return (
    <div className={`va-reass-acc ${open ? 'is-open' : ''}`}>
      <button type="button" className="va-reass-acc-head" onClick={()=>setOpen(o=>!o)} aria-expanded={open}>
        <span className="va-reass-acc-title">
          <svg width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2.4" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7"/>
          </svg>
          Faites confiance à Van-Away
        </span>
        <span className="va-reass-acc-chevron" aria-hidden="true">
          <svg width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7"/></svg>
        </span>
      </button>
      {open && <div className="va-reass-acc-body"><ReassuranceBlock variant={window.__vaReassVariant || 'default'}/></div>}
      <style>{`
        .va-reass-acc{margin-top:14px;background:${T_SURFACE};border:1px solid ${T_BORDER};border-radius:20px;box-shadow:0 1px 2px rgba(4,40,40,.04),0 4px 16px rgba(4,40,40,.06);overflow:hidden}
        .va-reass-acc-head{display:flex;align-items:center;justify-content:space-between;gap:10px;width:100%;padding:15px 20px;border:none;background:${T_TEAL};cursor:pointer;font-family:inherit}
        .va-reass-acc-title{display:flex;align-items:center;gap:8px;font-size:12px;font-weight:900;color:#fff;text-transform:uppercase;letter-spacing:.8px}
        .va-reass-acc-chevron{display:inline-flex;color:rgba(255,255,255,.85);transition:transform .25s cubic-bezier(.4,0,.2,1)}
        .va-reass-acc.is-open .va-reass-acc-chevron{transform:rotate(180deg)}
        .va-reass-acc-body{padding:4px 14px 14px}
        .va-reass-acc-body .va-reass-block{margin-top:0;border:none;box-shadow:none;border-radius:0;padding:0 4px}
        .va-reass-acc-body .va-reass-block-header{display:none}
      `}</style>
    </div>
  );
}

// ─── Main screen ───────────────────────────────────────────────
function VehiclesScreen({ compact = false }) {
  const [search, setSearch] = React.useState({
    startAgencyId: 5,
    agencyName: 'Van-Away Toulouse - Toulouse',
    startDate: '2026-07-24',
    endDate: '2026-07-27',
    days: 3,
  });
  const [activeCategory, setActiveCategory] = React.useState('all');
  const [activeTravelers, setActiveTravelers] = 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 ALL_VEHICLES = [...MOCK_VEHICLES, ...UNAVAIL_VEHICLES];
  const CAT_ORDER = ['VAN', 'FOURGON', '4X4', 'ÉQUIPEMENT', 'MINIBUS'];
  const catCount = (id) => ALL_VEHICLES.filter(v => v.category_name === id).length;
  const categories = [
    { id: 'all', name: 'TOUT', count: null },
    ...CAT_ORDER.filter(c => catCount(c) > 0).map(c => ({
      id: c,
      name: c === 'VAN' ? 'VAN' : c === 'FOURGON' ? 'FOURGON' : c,
      count: catCount(c),
    })),
  ];
  const travelerOptions = ['all', 2, 3, 4, 5];

  const byFilters = (v) =>
    (activeCategory === 'all' || v.category_name === activeCategory) &&
    (activeTravelers === 'all' || (v.nb_places || 0) >= activeTravelers);

  const filteredVehicles = MOCK_VEHICLES.filter(byFilters);
  const filteredUnavail = UNAVAIL_VEHICLES.filter(byFilters);

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

      <main className="va-vehicles-main">
        <div className="va-filters-bar">
          <div className="va-filters-rows">
            <div className="va-filter-row">
              <span className="va-tabs-icon" aria-hidden="true">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><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>
              </span>
              {categories.map(c => (
                <button key={c.id}
                  className={`va-cat-tab ${activeCategory === c.id ? 'active' : ''}`}
                  onClick={() => setActiveCategory(c.id)}>
                  {c.name}
                  {c.count != null && <span className="va-cat-tab-count">{c.count}</span>}
                </button>
              ))}
            </div>
            <div className="va-filter-row">
              <span className="va-tabs-icon" aria-hidden="true">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><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>
              </span>
              {travelerOptions.map(t => (
                <button key={t}
                  className={`va-cat-tab ${activeTravelers === t ? 'active' : ''}`}
                  onClick={() => setActiveTravelers(t)}>
                  {t === 'all' ? 'TOUT' : t}
                </button>
              ))}
            </div>
          </div>
          {!compact && <div className="va-filters-badge"><GoogleReviewsBadge compact={compact}/></div>}
        </div>

        {filteredVehicles.length > 0 && (
          <div className="va-vehicles-grid">
            {filteredVehicles.flatMap((v, i) => {
              const card = (
                <VehicleCard key={v.id} vehicle={v} days={search.days} startDate={search.startDate} index={i}
                  onSelect={(id)=>console.log('select', id)} onShowDetails={(id)=>setDetailVehicleId(id)}/>
              );
              if (compact && i === 1) return [card];
              return [card];
            })}
          </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>
          </>
        )}

        <NearbyAgencyBlock search={search} compact={compact}/>
      </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 >= 31 ? pricing['31+'] : search.days >= 11 ? pricing['11-30'] : pricing['1-10'];
        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);}}/>;
      })()}
    </div>
    {!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 >= 31 ? pricing['31+'] : search.days >= 11 ? pricing['11-30'] : pricing['1-10'];
      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);}}/>;
    })()}

      <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-filters-bar{display:flex;align-items:flex-start;justify-content:space-between;gap:14px;margin-bottom:20px;padding:0 4px}
        .va-filters-rows{display:flex;flex-direction:column;gap:10px;flex:1;min-width:0}
        .va-filter-row{display:flex;align-items:center;gap:0;overflow-x:auto;scrollbar-width:none}
        .va-filter-row::-webkit-scrollbar{display:none}
        .va-filters-badge{flex-shrink:0}
        .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-tab{display:inline-flex;align-items:center;gap:7px;padding:8px 18px 10px;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:14px;right:14px;height:2px;background:${T_TEAL};border-radius:2px}
        .va-cat-tab-count{display:inline-flex;align-items:center;justify-content:center;min-width:20px;height:20px;padding:0 5px;border-radius:999px;background:#e7fcfb;color:${T_TEAL};font-size:11px;font-weight:700}
        .va-tabs-icon{display:inline-flex;align-items:center;justify-content:flex-start;color:${T_MUTED};width:28px;flex-shrink: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>
    <HelpBlockV2 search={search} compact={compact}/>
    </>
  );
}

Object.assign(window, { VehiclesScreen, VehicleCard, SearchSidebar });
Object.assign(window, { VehiclesScreenV2: VehiclesScreen, VehicleCardV2: VehicleCard, SearchSidebarV2: SearchSidebar });

})();
