// ============================================================================
// RichRateCard — shared premium rate card.
//
// Single source of truth used by:
//   • Homepage hero quote widget (components/HeroAnimated.jsx → ResultsGlass)
//   • International-moving landing (landing/calculator.jsx)
//   • Vehicle-shipping landing (landing/vehicle-shipping-sections{,-es}.jsx)
//   • Blog calculators (planned — blogs/*.html load this file the same way)
//
// What this file exposes on window:
//   • window.RichRateCard        — the card component itself
//   • window.__abgsRateHelpers   — pure functions consumers need:
//        rateTotalOf(r)              — total $ from any of the 4 endpoint shapes
//        collectBreakdown(r)         — itemized line list
//        buildRateOffersForFirestore(rates)  — Firestore-safe offer summary
//        rateTransitDays(r)          — [min, max] transit days or null
//        getRateTranslator()         — returns the t(key, vars) the card uses
//
// i18n strategy — i18n-system-agnostic:
//   1. Card bundles all `rate.*` strings (EN + ES) in RATE_STRINGS below.
//   2. On load, it merges them into window.__translations (homepage path,
//      so window.__i18n.t() picks them up the same as any other key).
//   3. If window.__i18n is missing (landings), the card uses its own t()
//      which reads from RATE_STRINGS keyed on window.LANG || 'en'.
//
// All other dependencies (Walio carrier catalog, Icon set, FCL container
// titles) are self-contained inside this IIFE so the file Just Works wherever
// it's loaded — as long as React 18 + window.Icon (Primitives.jsx) are on
// the page before this file runs.
// ============================================================================

(function () {
  const { useState, useEffect } = React;

  // ────────────────────────────────────────────────────────────────────────
  // Mobile-safe grid overrides.
  //
  // Homepage.html (and a few other pages) ships a blanket mobile CSS rule:
  //   @media (max-width:768px) {
  //     [style*="grid-template-columns"] { grid-template-columns: 1fr !important; }
  //   }
  // That rule is helpful for old marketing sections but flattens every
  // inline-styled grid in this card on mobile — the hero band (carrier chip /
  // name / price), the quick-stats strip, and NoRatesGlass's metadata and
  // contact grids all collapse to a single column.
  //
  // Inject a class-targeted override so the card stays multi-column on
  // mobile regardless of the page-level rule. Uses higher specificity
  // (the class + the inline style attribute) and `!important` to win over
  // the blanket rule's `!important`. CSS variables let the quick-stats
  // strip preserve its dynamic 1–3 column count, and let the NoRatesGlass
  // metadata grid switch 4-col ↔ 2-col based on its own wide/narrow state.
  // ────────────────────────────────────────────────────────────────────────
  if (typeof document !== 'undefined' && !document.getElementById('rrc-mobile-fix')) {
    const style = document.createElement('style');
    style.id = 'rrc-mobile-fix';
    style.textContent = `
      .rrc-hero-row { grid-template-columns: auto 1fr auto !important; gap: 14px !important; }
      .rrc-quick-stats {
        grid-template-columns: repeat(var(--rrc-stats-cols, 3), minmax(0, 1fr)) !important;
        gap: 8px !important;
      }
      .nrg-metadata-grid {
        grid-template-columns: repeat(var(--nrg-metadata-cols, 4), minmax(0, 1fr)) !important;
        gap: 8px !important;
      }
      .nrg-contact-grid {
        grid-template-columns: repeat(var(--nrg-contact-cols, 2), minmax(0, 1fr)) !important;
        gap: 8px 16px !important;
      }
      /* On very narrow viewports, tighten the hero band so the price column
         doesn't get squeezed against the carrier name. The dynamic price
         font-size + 56px brand chip stay readable down to ~340px. */
      @media (max-width: 380px) {
        .rrc-hero-row { gap: 10px !important; }
      }
    `;
    document.head.appendChild(style);
  }

  // ────────────────────────────────────────────────────────────────────────
  // i18n — bundle all rate.* keys with EN + ES translations and expose a
  // unified t() that works whether window.__i18n exists (homepage) or only
  // window.LANG is set (landings).
  // ────────────────────────────────────────────────────────────────────────

  const RATE_STRINGS = {
    'rate.allin':                    { en: 'All-in',                es: 'Total' },
    'rate.show_breakdown':           { en: 'Show breakdown',        es: 'Ver desglose' },
    'rate.hide_breakdown':           { en: 'Hide breakdown',        es: 'Ocultar desglose' },
    'rate.section.breakdown':        { en: 'Price breakdown',       es: 'Desglose del precio' },
    'rate.section.export_charges':   { en: 'Export charges',        es: 'Cargos de exportación' },
    'rate.section.origin_pickup':    { en: 'Origin pickup',         es: 'Recolección en origen' },
    'rate.total_allin':              { en: 'Total all-in',          es: 'Total con todo incluido' },
    'rate.section.basis':            { en: 'Chargeable basis',      es: 'Base facturable' },
    'rate.section.route':            { en: 'Route & validity',      es: 'Ruta y validez' },
    'rate.section.sailings':         { en: 'Sailings',              es: 'Salidas' },
    'rate.section.pickup':           { en: 'Pickup, delivery & drayage', es: 'Recolección, entrega y drayage' },
    'rate.section.inclusions':       { en: 'Inclusions',            es: 'Inclusiones' },
    'rate.restrictions':             { en: 'Restrictions',          es: 'Restricciones' },
    'rate.lbl.actual_volume':        { en: 'Actual volume',         es: 'Volumen real' },
    'rate.lbl.volumetric_volume':    { en: 'Volumetric volume',     es: 'Volumen volumétrico' },
    'rate.lbl.chargeable_volume':    { en: 'Chargeable volume',     es: 'Volumen facturable' },
    'rate.lbl.rate_cbm':             { en: 'Rate / cbm',            es: 'Tarifa / cbm' },
    'rate.lbl.min_charge':           { en: 'Minimum charge',        es: 'Cargo mínimo' },
    'rate.lbl.actual_weight':        { en: 'Actual weight',         es: 'Peso real' },
    'rate.lbl.volumetric_weight':    { en: 'Volumetric weight',     es: 'Peso volumétrico' },
    'rate.lbl.chargeable_weight':    { en: 'Chargeable weight',     es: 'Peso facturable' },
    'rate.lbl.rate_kg':              { en: 'Rate / kg',             es: 'Tarifa / kg' },
    'rate.lbl.min_air':              { en: 'Minimum air',           es: 'Mínimo aéreo' },
    'rate.lbl.min_applied':          { en: 'Minimum applied',       es: 'Mínimo aplicado' },
    'rate.lbl.yes':                  { en: 'Yes',                   es: 'Sí' },
    'rate.lbl.no':                   { en: 'No',                    es: 'No' },
    'rate.lbl.origin_dist':          { en: 'Origin port dist.',     es: 'Dist. al puerto de origen' },
    'rate.lbl.dest_dist':            { en: 'Dest. port dist.',      es: 'Dist. al puerto de destino' },
    'rate.lbl.rail_leg':             { en: 'Rail leg',              es: 'Tramo ferroviario' },
    'rate.lbl.original_port':        { en: 'Original port',         es: 'Puerto original' },
    'rate.lbl.ocean_transit':        { en: 'Ocean transit',         es: 'Tránsito marítimo' },
    'rate.lbl.rail_transit':         { en: 'Rail transit',          es: 'Tránsito ferroviario' },
    'rate.lbl.valid':                { en: 'Valid',                 es: 'Válido' },
    'rate.lbl.through':              { en: 'through {date}',        es: 'hasta {date}' },
    'rate.lbl.cutoff':               { en: 'Booking cutoff',        es: 'Cierre de reserva' },
    'rate.lbl.sailing':              { en: 'Sailing date',          es: 'Fecha de salida' },
    'rate.lbl.next_sailing':         { en: 'Next sailing',          es: 'Próxima salida' },
    'rate.lbl.schedules':            { en: 'Schedules',             es: 'Horarios' },
    'rate.lbl.weekly':               { en: '{n} weekly',            es: '{n} semanales' },
    'rate.lbl.pickup':               { en: 'Pickup',                es: 'Recolección' },
    'rate.lbl.delivery':             { en: 'Delivery',              es: 'Entrega' },
    'rate.lbl.drayage':              { en: 'Drayage',               es: 'Drayage' },
    'rate.lbl.included':             { en: 'Included',              es: 'Incluido' },
    'rate.lbl.note':                 { en: 'Note:',                 es: 'Nota:' },
    'rate.lbl.port_fees':            { en: 'Port fees',             es: 'Cargos portuarios' },
    'rate.lbl.transit':              { en: 'Transit',               es: 'Tránsito' },
    'rate.lbl.etd':                  { en: 'ETD',                   es: 'ETD' },
    'rate.lbl.free_time':            { en: 'Free time',             es: 'Tiempo libre' },
    'rate.lbl.containers':           { en: 'Containers',            es: 'Contenedores' },
    'rate.lbl.transit_time':         { en: 'transit time',          es: 'tiempo de tránsito' },
    'rate.bookable':                 { en: 'Bookable',              es: 'Reservable' },
    'rate.quote_only':               { en: 'Quote only',            es: 'Solo cotización' },
    'rate.via':                      { en: 'via {p}',               es: 'vía {p}' },
    'rate.days':                     { en: '{n} days',              es: '{n} días' },
    'rate.days_range':               { en: '{min}–{max} days', es: '{min}–{max} días' },
    'rate.transit.estimate':         { en: '(est.)',                es: '(est.)' },
    'rate.badge.best_price':         { en: 'Best price',            es: 'Mejor precio' },
    'rate.badge.fastest':            { en: 'Fastest',               es: 'El más rápido' },
    'rate.badge.direct':             { en: 'Direct service',        es: 'Servicio directo' },
    'rate.badge.d2d':                { en: 'Door-to-door',          es: 'Puerta a puerta' },
    'rate.badge.free_time':          { en: '{n} days free',         es: '{n} días libres' },
    'rate.badge.urgent':             { en: 'Expires soon',          es: 'Expira pronto' },
    'rate.badge.customs':            { en: 'Customs included',      es: 'Aduanas incluidas' },
    'rate.air.trucking_required':    {
      en: 'Cargo must be trucked from your origin to this airport. Contact us for door pickup pricing.',
      es: 'La carga debe trasladarse por camión desde su origen hasta este aeropuerto. Contáctenos para cotizar la recolección a domicilio.',
    },
    'rate.air.trucking_short':       { en: 'trucking req.',         es: 'requiere camión' },
    'rate.air.distance_away':        { en: '{n} {unit} away',       es: 'a {n} {unit}' },
    'rate.air.connection':           { en: 'Connection',            es: 'Conexión' },
    'rate.warn.no_ltl':              {
      en: 'No LTL coverage at this airport — pickup quoted to Miami CFS instead. Cargo will be trucked cross-country to Miami before flying.',
      es: 'Sin cobertura LTL en este aeropuerto — recolección cotizada hasta CFS Miami. La carga será transportada por camión hasta Miami antes de volar.',
    },
    'rate.lbl.pickup_pending':       { en: 'Pickup pending',        es: 'Recolección pendiente' },
    'rate.lbl.delivery_pending':     { en: 'Delivery pending',      es: 'Entrega pendiente' },
    'rate.lbl.port_to_port':         { en: 'Port-to-port',          es: 'Puerto a puerto' },
    'rate.info.port_to_port':        {
      en: 'You asked for port-to-port service. This rate covers the ocean leg only — you\'ll drop the cargo at the origin port and pick it up at the destination port.',
      es: 'Solicitaste servicio puerto a puerto. Esta tarifa cubre solo el tramo marítimo — entregarás la carga en el puerto de origen y la recogerás en el puerto de destino.',
    },
    'rate.lbl.from_origin':          { en: 'from origin',           es: 'desde origen' },
    'rate.lbl.to_destination':       { en: 'to destination',        es: 'al destino' },
    'rate.warn.pickup_pending':      {
      en: 'You asked for door pickup but this carrier didn\'t include a pickup leg in the live rate. A dedicated agent will confirm the door-pickup surcharge by email within 1 business day.',
      es: 'Solicitaste recolección a domicilio, pero esta naviera no incluyó la recolección en la tarifa en vivo. Un asesor te confirmará el cargo de recolección por correo en menos de 1 día hábil.',
    },
    'rate.warn.delivery_pending':    {
      en: 'You asked for door delivery but this carrier didn\'t include a delivery leg in the live rate. A dedicated agent will confirm the door-delivery surcharge by email within 1 business day.',
      es: 'Solicitaste entrega a domicilio, pero esta naviera no incluyó la entrega en la tarifa en vivo. Un asesor te confirmará el cargo de entrega por correo en menos de 1 día hábil.',
    },

    // ─── NoRatesGlass (premium custom-quote fallback) strings ───────────
    'common.close':                    { en: 'Close',                            es: 'Cerrar' },
    'common.private':                  { en: 'Quote stays private',              es: 'Tu cotización es privada' },
    'q.step_x_of_y':                   { en: 'Step {n} of {total}',              es: 'Paso {n} de {total}' },
    'q.results.edit_search':           { en: 'Edit search',                      es: 'Editar búsqueda' },
    'q.results.aria.edit':             { en: 'Edit search',                      es: 'Editar búsqueda' },
    'q.results.footer.allin':          { en: 'All-in pricing',                   es: 'Precio total' },
    'q.norates.title':                 { en: 'AB Group Smart Quote',             es: 'Cotización Inteligente AB Group' },
    'q.norates.subtitle.confirmed':    { en: 'Rate request confirmed',           es: 'Solicitud de tarifa confirmada' },
    'q.norates.status.analyzing':      { en: 'Analyzing global carrier routes…', es: 'Analizando rutas globales de transportistas…' },
    'q.norates.status.negotiating':    { en: 'Negotiating spot rates…',          es: 'Negociando tarifas spot…' },
    'q.norates.status.checking':       { en: 'Checking capacity…',               es: 'Verificando capacidad…' },
    'q.norates.status.finalizing':     { en: 'Finalizing priority request…',     es: 'Finalizando solicitud prioritaria…' },
    'q.norates.status.pending':        { en: 'Pending',                          es: 'Pendiente' },
    'q.norates.route.origin':          { en: 'Origin',                           es: 'Origen' },
    'q.norates.route.destination':     { en: 'Destination',                      es: 'Destino' },
    'q.norates.message.title':         { en: "We're calculating your custom rate", es: 'Estamos calculando tu tarifa personalizada' },
    'q.norates.message.body':          {
      en: 'This specific lane needs manual optimization to guarantee the best price. Our logistics team has the full request and will reach out shortly with a tailored quote.',
      es: 'Esta ruta específica requiere optimización manual para garantizar el mejor precio. Nuestro equipo de logística ya tiene la solicitud completa y te contactará en breve con una cotización personalizada.',
    },
    'q.norates.metadata.transit':      { en: 'Transit',          es: 'Tránsito' },
    'q.norates.metadata.service':      { en: 'Service',          es: 'Servicio' },
    'q.norates.metadata.mode':         { en: 'Mode',             es: 'Modo' },
    'q.norates.metadata.rate':         { en: 'Rate',             es: 'Tarifa' },
    'q.norates.metadata.priority':     { en: 'Priority',         es: 'Prioritaria' },
    'q.norates.metadata.multimodal':   { en: 'Multi-Modal',      es: 'Multimodal' },
    'q.norates.metadata.custom':       { en: 'Custom',           es: 'Personalizada' },
    'q.norates.contact.title':         { en: 'Contact information', es: 'Información de contacto' },
    'q.norates.success':               { en: 'Request successfully queued',                       es: 'Solicitud enviada con éxito' },
    'q.norates.expert_assigned':       { en: 'Expert assigned',  es: 'Experto asignado' },
    'q.norates.button.new_search':     { en: 'Start new search', es: 'Iniciar nueva búsqueda' },
    'q.norates.connecting':            { en: 'Connecting to specialized carrier network…',         es: 'Conectando con red de transportistas especializada…' },
    'q.norates.ref':                   { en: 'REF',              es: 'REF' },
    'q.norates.chip.custom':           { en: 'Custom quote',     es: 'Cotización personalizada' },
  };

  // Merge into __translations so homepage's __i18n.t() resolves rate.* keys
  // (lets us delete the duplicate block from i18n-strings.js later, single
  // source of truth lives here).
  if (typeof window !== 'undefined') {
    window.__translations = Object.assign(window.__translations || {}, RATE_STRINGS);
  }

  // Standalone fallback used on landings that don't load homepage's i18n.
  function fallbackT(key, vars) {
    const lang = (typeof window !== 'undefined' && window.LANG) || 'en';
    const entry = RATE_STRINGS[key];
    let val = entry ? (entry[lang] || entry.en || key) : key;
    if (vars && typeof val === 'string') {
      Object.keys(vars).forEach(function (k) {
        val = val.split('{' + k + '}').join(vars[k]);
      });
    }
    return val;
  }

  // React hook that returns { t, lang } and re-renders on language change.
  // Homepage path: subscribes to __i18n. Landing path: subscribes to a
  // simple "abgs:langChanged" event (i18n.js on landings dispatches this
  // when the toggle flips). Both paths return the SAME shape so the card
  // doesn't care which system it's running under.
  function useRateT() {
    const [, setTick] = useState(0);
    useEffect(function () {
      if (window.__i18n && typeof window.__i18n.subscribe === 'function') {
        return window.__i18n.subscribe(function () { setTick(function (x) { return x + 1; }); });
      }
      const handler = function () { setTick(function (x) { return x + 1; }); };
      window.addEventListener('abgs:langChanged', handler);
      return function () { window.removeEventListener('abgs:langChanged', handler); };
    }, []);
    if (window.__i18n) {
      return { t: window.__i18n.t, lang: window.__i18n.lang };
    }
    return { t: fallbackT, lang: (window.LANG || 'en') };
  }

  // ────────────────────────────────────────────────────────────────────────
  // Rate shape helpers — pure functions consumers also need (used to build
  // the breakdown sum, persist offers to Firestore, etc).
  // ────────────────────────────────────────────────────────────────────────

  // Returns null when no recognised total field is present (callers check
  // `== null` to trigger their no-rates fallback path). The homepage uses
  // `rateTotalOf(r) || Infinity` for sort comparisons, which treats null
  // and 0 identically — safe for both call patterns.
  function rateTotalOf(r) {
    if (!r) return null;
    if (r.completeQuote && typeof r.completeQuote.totalCost === 'number') return r.completeQuote.totalCost;
    if (r.pricing && typeof r.pricing.total === 'number') return r.pricing.total;
    if (typeof r.totalPrice === 'number') return r.totalPrice;
    if (typeof r.totalCost === 'number') return r.totalCost;
    return null;
  }

  // Does this rate's price include the door-pickup leg? Walio's response
  // shape varies — most modes set r.hasPickup + r.pickupCost, but FCL
  // commonly puts the door pickup as an "Origin Drayage: Door to PORT X"
  // line inside the breakdown rather than as the dedicated pickup fields.
  // We need to recognize all three so the orange "Pickup pending" banner
  // doesn't fire on a rate that has actually quoted the door leg.
  function isPickupFulfilled(r, breakdown) {
    if (!r) return false;
    if (r.hasPickup) return true;
    if (typeof r.pickupCost === 'number' && r.pickupCost > 0) return true;
    const items = Array.isArray(breakdown) ? breakdown : [];
    return items.some(b => {
      const lbl = String(b && b.label || '').toLowerCase();
      // "Origin pickup", "Door pickup", or "Origin Drayage: Door to PORT X"
      // — the last is the FCL pattern from the screenshot.
      if (/origin\s*pickup|door\s*pickup/i.test(lbl)) return true;
      if (/drayage\b.*\bdoor\s*to\b/i.test(lbl)) return true;
      return false;
    });
  }

  // Does this rate's price include the door-delivery leg? Mirrors the
  // pickup helper — destination drayage often reads "Destination Drayage:
  // PORT X to Door" or similar.
  function isDeliveryFulfilled(r, breakdown) {
    if (!r) return false;
    if (r.hasDelivery) return true;
    if (typeof r.deliveryCost === 'number' && r.deliveryCost > 0) return true;
    const items = Array.isArray(breakdown) ? breakdown : [];
    return items.some(b => {
      const lbl = String(b && b.label || '').toLowerCase();
      if (/destination\s*delivery|door\s*delivery/i.test(lbl)) return true;
      if (/drayage\b.*\bto\s*door\b/i.test(lbl)) return true;
      return false;
    });
  }

  // Transit days come on different fields per mode. Returns [min, max] or null.
  function rateTransitDays(r) {
    if (!r) return null;
    if (Array.isArray(r.transitDays) && r.transitDays.length === 2) return r.transitDays;
    if (r.transit && r.transit.minDays != null) {
      return [r.transit.minDays, r.transit.maxDays || r.transit.minDays];
    }
    if (typeof r.transitDays === 'number') return [r.transitDays, r.transitDays];
    if (typeof r.transit === 'number') return [r.transit, r.transit];
    if (typeof r.combinedTransitDays === 'number') return [r.combinedTransitDays, r.combinedTransitDays];
    return null;
  }

  // ────────────────────────────────────────────────────────────────────────
  // Formatters — locale-stable, USD by default.
  // ────────────────────────────────────────────────────────────────────────

  const fmtMoney = (v, ccy) => {
    if (typeof v !== 'number' || !isFinite(v)) return null;
    try {
      return v.toLocaleString('en-US', { style: 'currency', currency: ccy || 'USD',
        maximumFractionDigits: v >= 100 ? 0 : 2 });
    } catch (e) { return '$' + v.toLocaleString('en-US'); }
  };
  const fmtDate = (iso) => {
    if (!iso) return null;
    try {
      const d = new Date(iso);
      if (isNaN(d.getTime())) return iso;
      return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
    } catch (e) { return iso; }
  };
  const fmtShortDate = (iso) => {
    if (!iso) return null;
    try {
      const d = new Date(iso);
      if (isNaN(d.getTime())) return iso;
      return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
    } catch (e) { return iso; }
  };
  const titleCase = (s) => (s || '').toString()
    .replace(/[_-]+/g, ' ')
    .replace(/([a-z])([A-Z])/g, '$1 $2')
    .replace(/\s+/g, ' ')
    .replace(/\b\w/g, c => c.toUpperCase());
  const carrierCode = (c) => (c || '?').toString().toUpperCase()
    .replace(/[^A-Z0-9]/g, '').slice(0, 4) || '?';

  // AIR rates store the origin airport as either a clean IATA code ("ATL")
  // or a code-prefixed string ("MIA Miami"). Mirrors the homepage's extract
  // helper so the chip filter and IATA badge always surface a 3-letter token.
  function extractIataCode(s) {
    if (!s) return null;
    const m = String(s).trim().match(/^([A-Z]{3})\b/);
    return m ? m[1] : null;
  }

  // ────────────────────────────────────────────────────────────────────────
  // Walio carrier catalog — fetched once, cached forever. Used for real
  // carrier logos and brand colors.
  // ────────────────────────────────────────────────────────────────────────

  // Walio public API. `wl_pk_…` is a public key (Stripe-style) — safe to ship
  // in the browser.
  const WALIO_API_KEY = 'wl_pk_VzywFPpAB0xA2TVqtJSOEEmC6WHONtmP';
  const WALIO_AUTH_HEADERS = { Authorization: `Bearer ${WALIO_API_KEY}` };
  const WALIO_CARRIERS_URL = 'https://walio.ai/api/v1/carriers';
  let __walioCarrierIndex = null;
  let __walioCarrierPromise = null;
  const __walioNorm = (s) => (s || '').toString().toLowerCase().replace(/[^a-z0-9]/g, '');

  function loadWalioCarriers() {
    if (__walioCarrierIndex) return Promise.resolve(__walioCarrierIndex);
    if (__walioCarrierPromise) return __walioCarrierPromise;
    __walioCarrierPromise = fetch(WALIO_CARRIERS_URL, { headers: WALIO_AUTH_HEADERS })
      .then(r => r.ok ? r.json() : null)
      .then(json => {
        const idx = new Map();
        const tokens = [];
        const data = json && json.data ? json.data : {};
        Object.keys(data).forEach(group => {
          const arr = Array.isArray(data[group]) ? data[group] : [];
          arr.forEach(c => {
            if (!c || !c.name || !c.logoUrl) return;
            const entry = { name: c.name, logoUrl: c.logoUrl,
              brandColor: c.brandColor || null, group };
            const k = __walioNorm(c.name);
            if (k && !idx.has(k)) idx.set(k, entry);
            tokens.push({ key: k, entry });
          });
        });
        __walioCarrierIndex = { exact: idx, tokens };
        return __walioCarrierIndex;
      })
      .catch(() => {
        __walioCarrierIndex = { exact: new Map(), tokens: [] };
        return __walioCarrierIndex;
      });
    return __walioCarrierPromise;
  }

  function useWalioCarriers() {
    const [idx, setIdx] = useState(__walioCarrierIndex);
    useEffect(() => {
      if (__walioCarrierIndex) { setIdx(__walioCarrierIndex); return; }
      let alive = true;
      loadWalioCarriers().then(v => { if (alive) setIdx(v); });
      return () => { alive = false; };
    }, []);
    return idx;
  }

  // Resolve a rate-response carrier name to a Walio catalog entry. See the
  // homepage's original for the full matching rationale (short codes ≤ 4 chars
  // only accept prefix-starts-with matches; longer inputs fall through to
  // bidirectional prefix + containment).
  function resolveCarrierLogo(idx, name) {
    if (!idx || !name) return null;
    const n = __walioNorm(name);
    if (!n) return null;
    if (idx.exact.has(n)) return idx.exact.get(n);
    for (let len = n.length - 1; len >= 3; len--) {
      if (idx.exact.has(n.slice(0, len))) return idx.exact.get(n.slice(0, len));
    }
    let bestPrefix = null;
    for (const tok of idx.tokens) {
      if (!tok.key || tok.key.length < 3) continue;
      if (tok.key.startsWith(n)) {
        if (!bestPrefix || tok.key.length < bestPrefix.key.length) bestPrefix = tok;
      }
    }
    if (bestPrefix) return bestPrefix.entry;
    for (const tok of idx.tokens) {
      if (!tok.key || tok.key.length < 3) continue;
      if (n.startsWith(tok.key)) return tok.entry;
    }
    if (n.length < 5) return null;
    let best = null;
    for (const tok of idx.tokens) {
      if (!tok.key || tok.key.length < 3) continue;
      if (n.includes(tok.key) || tok.key.includes(n)) {
        if (!best || tok.key.length > best.key.length) best = tok;
      }
    }
    return best ? best.entry : null;
  }

  // Carrier brand registry — fallback brand color + initials when no logo
  // resolves. Same list as the original homepage card.
  const CARRIER_BRANDS = [
    { match: /\bcosco\b/i,                bg: '#E60012', fg: '#fff', label: 'COSCO' },
    { match: /\bmaersk\b/i,                bg: '#42B0D5', fg: '#0B1220', label: 'MAERSK' },
    { match: /\bmsc\b|mediterranean shipping/i, bg: '#FFCB00', fg: '#0B1220', label: 'MSC' },
    { match: /\bcma[\s-]*cgm\b/i,          bg: '#0B66A8', fg: '#fff', label: 'CMA' },
    { match: /\bevergreen\b/i,             bg: '#00853E', fg: '#fff', label: 'EVER' },
    { match: /hapag[-\s]*lloyd/i,          bg: '#FF6600', fg: '#fff', label: 'HAPAG' },
    { match: /\bone\b|ocean network express/i, bg: '#DE0084', fg: '#fff', label: 'ONE' },
    { match: /\bhmm\b|hyundai merchant/i,  bg: '#003C7E', fg: '#fff', label: 'HMM' },
    { match: /yang[\s-]*ming/i,            bg: '#00468C', fg: '#fff', label: 'YML' },
    { match: /\bzim\b/i,                   bg: '#1F3864', fg: '#fff', label: 'ZIM' },
    { match: /\boocl\b/i,                  bg: '#003876', fg: '#fff', label: 'OOCL' },
    { match: /\bpil\b|pacific international/i, bg: '#003E7E', fg: '#fff', label: 'PIL' },
    { match: /\bwan\s*hai\b/i,             bg: '#003B71', fg: '#fff', label: 'WHL' },
    { match: /\bsealand\b/i,               bg: '#005DAA', fg: '#fff', label: 'SEAL' },
    { match: /lufthansa/i,                 bg: '#FFD600', fg: '#0B1220', label: 'LH' },
    { match: /emirates/i,                  bg: '#D71921', fg: '#fff', label: 'EK' },
    { match: /qatar\s*airways/i,           bg: '#5C0632', fg: '#fff', label: 'QR' },
    { match: /cathay\s*pacific/i,          bg: '#006564', fg: '#fff', label: 'CX' },
    { match: /korean\s*air/i,              bg: '#00256C', fg: '#fff', label: 'KE' },
    { match: /singapore\s*airlines/i,      bg: '#19457E', fg: '#fff', label: 'SQ' },
    { match: /turkish\s*airlines/i,        bg: '#C70A0C', fg: '#fff', label: 'TK' },
    { match: /china\s*southern/i,          bg: '#0067B1', fg: '#fff', label: 'CZ' },
    { match: /china\s*airlines/i,          bg: '#C8102E', fg: '#fff', label: 'CI' },
    { match: /etihad/i,                    bg: '#BA9869', fg: '#fff', label: 'EY' },
    { match: /atlas\s*air/i,               bg: '#00467F', fg: '#fff', label: 'ATL' },
    { match: /\bana\b|all nippon/i,        bg: '#13448F', fg: '#fff', label: 'ANA' },
    { match: /jal|japan\s*airlines/i,      bg: '#C8102E', fg: '#fff', label: 'JAL' },
    { match: /\bdhl\b/i,                   bg: '#FFCC00', fg: '#D40511', label: 'DHL' },
    { match: /\bfedex\b/i,                 bg: '#4D148C', fg: '#FF6600', label: 'FX' },
    { match: /\bups\b/i,                   bg: '#351C15', fg: '#FFB500', label: 'UPS' },
    { match: /\busps\b/i,                  bg: '#004B87', fg: '#fff', label: 'USPS' },
    { match: /\bxpo\b/i,                   bg: '#E03C31', fg: '#fff', label: 'XPO' },
    { match: /old\s*dominion|\bodfl\b/i,   bg: '#76232F', fg: '#fff', label: 'ODFL' },
    { match: /estes\b/i,                   bg: '#E03C31', fg: '#fff', label: 'EXLA' },
    { match: /yellow|\byrc\b/i,            bg: '#FFCB00', fg: '#0B1220', label: 'YRC' },
  ];
  const carrierBrand = (name) => {
    const s = (name || '').toString();
    for (const b of CARRIER_BRANDS) if (b.match.test(s)) return b;
    return { bg: 'linear-gradient(180deg, #0B1220 0%, #1f2937 100%)', fg: '#fff',
      label: carrierCode(s) };
  };

  // ────────────────────────────────────────────────────────────────────────
  // Small in-card UI primitives
  // ────────────────────────────────────────────────────────────────────────

  const SPEC_FONT = 'Inter, -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, sans-serif';

  // Inline carrier chip used inside SpecRow values (pickup carrier, drayage
  // carrier). Same logo lookup as the headline rate-card brand chip, but
  // compact: 14px-tall logo + carrier name.
  function PickupCarrierTag({ name }) {
    const idx = useWalioCarriers();
    const [logoFailed, setLogoFailed] = useState(false);
    if (!name) return null;
    const entry = resolveCarrierLogo(idx, name);
    const showLogo = entry && entry.logoUrl && !logoFailed;
    const fallbackBrand = carrierBrand(name);
    const brand = entry && entry.brandColor
      ? { bg: entry.brandColor, fg: '#fff', label: fallbackBrand.label }
      : fallbackBrand;
    return (
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5,
        verticalAlign: 'middle' }}>
        {showLogo ? (
          <img src={entry.logoUrl} alt=""
            onError={() => setLogoFailed(true)}
            style={{ height: 14, maxWidth: 38, width: 'auto', objectFit: 'contain',
              borderRadius: 3, background: '#fff',
              border: '1px solid rgba(16,24,40,0.06)',
              padding: 1, display: 'inline-block' }}/>
        ) : (
          <span style={{ display: 'inline-flex', alignItems: 'center',
            justifyContent: 'center',
            minWidth: 18, height: 14, padding: '0 4px', borderRadius: 3,
            background: brand.bg, color: brand.fg,
            fontSize: 8.5, fontWeight: 800, letterSpacing: '0.04em',
            fontFamily: 'Inter, system-ui, sans-serif',
            boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.18)' }}>
            {brand.label}
          </span>
        )}
        <span>{name}</span>
      </span>
    );
  }

  function QuickStat({ label, value }) {
    return (
      <div style={{ minWidth: 0, textAlign: 'center', padding: '0 4px' }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: '#0B1220',
          letterSpacing: '-0.005em', fontVariantNumeric: 'tabular-nums',
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' }}>
          {value}
        </div>
        <div style={{ fontSize: 9, fontWeight: 700, color: '#98A2B3',
          letterSpacing: '0.08em', textTransform: 'uppercase', marginTop: 3 }}>
          {label}
        </div>
      </div>
    );
  }

  function SpecPanel({ label, children, footer }) {
    const rows = React.Children.toArray(children).filter(Boolean);
    return (
      <div style={{ padding: '0 12px 10px' }}>
        <div style={{ background: '#ffffff',
          border: '1px solid rgba(16,24,40,0.08)',
          borderRadius: 10,
          overflow: 'hidden',
          boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.85)' }}>
          <div style={{ padding: '10px 14px 6px',
            fontSize: 9.5, fontWeight: 700, color: '#98A2B3',
            letterSpacing: '0.14em', textTransform: 'uppercase',
            fontFamily: SPEC_FONT }}>
            {label}
          </div>
          <div>
            {rows.map((child, i) =>
              React.isValidElement(child)
                ? React.cloneElement(child, { _first: i === 0 })
                : child)}
          </div>
          {footer}
        </div>
      </div>
    );
  }

  function SpecRow({ label, value, basis, _first }) {
    if (value == null || value === '') return null;
    return (
      <div style={{ display: 'flex', alignItems: 'flex-start',
        justifyContent: 'space-between', gap: 12,
        padding: '9px 14px',
        borderTop: _first ? 0 : '1px solid rgba(16,24,40,0.05)' }}>
        <div style={{ minWidth: 0, display: 'flex',
          flexDirection: 'column', gap: 2, flex: '1 1 auto' }}>
          <span style={{ color: '#344054', fontWeight: 500,
            fontSize: 12.5, lineHeight: 1.35,
            letterSpacing: '-0.005em',
            fontFamily: SPEC_FONT }}>
            {label}
          </span>
          {basis && (
            <span style={{
              display: 'inline-flex', alignSelf: 'flex-start',
              padding: '1px 6px', borderRadius: 4,
              background: 'rgba(30,87,214,0.06)',
              border: '1px solid rgba(30,87,214,0.16)',
              color: '#1846B0', fontWeight: 600,
              fontSize: 9.5, lineHeight: 1.4,
              letterSpacing: '0.02em',
              fontFeatureSettings: '"tnum" 1',
              fontFamily: SPEC_FONT,
              whiteSpace: 'nowrap', overflow: 'hidden',
              textOverflow: 'ellipsis', maxWidth: '100%' }}>
              {basis}
            </span>
          )}
        </div>
        <span style={{ color: '#0B1220', fontWeight: 600,
          fontSize: 12.5, textAlign: 'right',
          fontVariantNumeric: 'tabular-nums',
          fontFeatureSettings: '"tnum" 1, "cv11" 1',
          fontFamily: SPEC_FONT,
          whiteSpace: 'nowrap', flexShrink: 0,
          paddingTop: 1 }}>
          {value}
        </span>
      </div>
    );
  }

  // ────────────────────────────────────────────────────────────────────────
  // Breakdown extraction — pulls every line item out of a rate's various
  // shapes (completeQuote.* preferred; pricingBreakdown / pricing.breakdown
  // / root additionalServices as fallbacks). Mirrors the original homepage
  // logic exactly so the displayed total always sums to the visible lines.
  // ────────────────────────────────────────────────────────────────────────

  function deriveBasis(s) {
    if (!s || typeof s !== 'object') return null;
    const desc = (s.rateDescription || '').trim();
    if (desc && /\d/.test(desc)) return desc.toLowerCase();
    const unit = (s.unit || '').toString().replace(/_/g, ' ').toLowerCase();
    const qty = typeof s.quantity === 'number' ? s.quantity : null;
    const unitPrice = typeof s.unitPrice === 'number' ? s.unitPrice : null;
    if (qty && qty > 1 && unit) return `${qty}× ${unit.replace(/^per\s+/, 'per ')}`;
    if (unit) return unit.startsWith('per ') ? unit : `per ${unit}`;
    if (unitPrice != null && qty != null) return `${qty}× $${unitPrice}`;
    return null;
  }

  function fmtKgForBasis(n) {
    if (typeof n !== 'number' || !isFinite(n)) return null;
    return Number.isInteger(n) ? String(n) : (Math.round(n * 100) / 100).toFixed(2);
  }

  function deriveAirFreightBasis(r) {
    const cq = r.completeQuote || {};
    const ratePerKg = (typeof r.ratePerKg === 'number' && r.ratePerKg > 0) ? r.ratePerKg
      : (typeof cq.ratePerKg === 'number' && cq.ratePerKg > 0) ? cq.ratePerKg
      : null;
    if (ratePerKg == null) return null;
    const chgKg = fmtKgForBasis(r.chargeableWeightKg);
    const minAir = (typeof r.minAir === 'number' && r.minAir > 0) ? r.minAir
      : (typeof cq.minAir === 'number' && cq.minAir > 0) ? cq.minAir
      : (cq.pricingBreakdown && typeof cq.pricingBreakdown.minimumCharge === 'number'
         && cq.pricingBreakdown.minimumCharge > 0) ? cq.pricingBreakdown.minimumCharge
      : null;
    const minApplied = !!(cq.pricingBreakdown && cq.pricingBreakdown.minimumApplied)
      || !!r.minApplied;
    let basis = chgKg != null
      ? chgKg + ' kg × $' + ratePerKg.toFixed(2) + ' per kg'
      : '$' + ratePerKg.toFixed(2) + ' per kg';
    if (minApplied && minAir != null) {
      basis += ' (min: $' + minAir.toFixed(2) + ' applied)';
    }
    return basis;
  }

  function deriveLinehaulBasis(r) {
    const sl = r.selectedLinehaul || {};
    const lb = (r.completeQuote && r.completeQuote.linehaulBreakdown) || {};
    const ratePerKg = (typeof sl.linehaulRatePerKg === 'number' && sl.linehaulRatePerKg > 0) ? sl.linehaulRatePerKg
      : (typeof lb.ratePerKg === 'number' && lb.ratePerKg > 0) ? lb.ratePerKg
      : null;
    if (ratePerKg == null) return null;
    const chgKg = fmtKgForBasis(r.chargeableWeightKg);
    const minCharge = (typeof sl.linehaulMinCharge === 'number' && sl.linehaulMinCharge > 0) ? sl.linehaulMinCharge
      : (typeof lb.minimumCharge === 'number' && lb.minimumCharge > 0) ? lb.minimumCharge
      : null;
    const minApplied = !!lb.minimumApplied;
    let basis = chgKg != null
      ? chgKg + ' kg × $' + ratePerKg.toFixed(2) + ' per kg'
      : '$' + ratePerKg.toFixed(2) + ' per kg';
    if (minApplied && minCharge != null) {
      basis += ' (min: $' + minCharge.toFixed(2) + ' applied)';
    }
    return basis;
  }

  function collectBreakdown(r) {
    const items = [];
    const cq = r && r.completeQuote;

    if (cq) {
      if (typeof cq.oceanFreight === 'number')
        items.push({ label: 'Ocean freight', amount: cq.oceanFreight });
      if (typeof cq.airFreight === 'number')
        items.push({ label: 'Air freight', amount: cq.airFreight,
          basis: deriveAirFreightBasis(r) });
      if (typeof cq.linehaulCost === 'number' && cq.linehaulCost > 0)
        items.push({ label: 'Linehaul connection', amount: cq.linehaulCost,
          basis: deriveLinehaulBasis(r) });
      else if (cq.breakdown && typeof cq.breakdown.linehaul === 'number' && cq.breakdown.linehaul > 0)
        items.push({ label: 'Linehaul connection', amount: cq.breakdown.linehaul,
          basis: deriveLinehaulBasis(r) });
      if (cq.breakdown) {
        if (typeof cq.breakdown.fuel === 'number' && cq.breakdown.fuel > 0)
          items.push({ label: 'Fuel surcharge', amount: cq.breakdown.fuel });
        if (typeof cq.breakdown.security === 'number' && cq.breakdown.security > 0)
          items.push({ label: 'Security surcharge', amount: cq.breakdown.security });
      }
      if (Array.isArray(cq.extraCosts) && cq.extraCosts.length > 0) {
        cq.extraCosts.forEach(s => {
          if (s && typeof s.amount === 'number')
            items.push({ label: s.name || 'Extra cost', amount: s.amount,
              basis: deriveBasis(s) });
        });
      } else if (cq.breakdown && typeof cq.breakdown.extraCosts === 'number' && cq.breakdown.extraCosts > 0) {
        items.push({ label: 'Carrier extra costs', amount: cq.breakdown.extraCosts });
      }
      let servicesHaveDrayage = false;
      if (Array.isArray(cq.additionalServices)) {
        cq.additionalServices.forEach(s => {
          if (s && typeof s.amount === 'number') {
            if (/drayage/i.test(s.name || '')) servicesHaveDrayage = true;
            items.push({ label: s.name || 'Service', amount: s.amount,
              basis: deriveBasis(s),
              isPortFee: !!s.isPortFee });
          }
        });
      }
      if (typeof cq.drayageCost === 'number' && cq.drayageCost > 0 && !servicesHaveDrayage)
        items.push({ label: 'Drayage', amount: cq.drayageCost });
      if (typeof cq.servicesCost === 'number' && cq.servicesCost > 0
          && !Array.isArray(cq.additionalServices))
        items.push({ label: 'Services', amount: cq.servicesCost });
      if (typeof cq.pickupCost === 'number' && cq.pickupCost > 0)
        items.push({ label: 'Origin pickup', amount: cq.pickupCost });
      if (typeof cq.deliveryCost === 'number' && cq.deliveryCost > 0)
        items.push({ label: 'Destination delivery', amount: cq.deliveryCost });
    }

    if (!cq || typeof cq.pickupCost !== 'number') {
      if (r && typeof r.pickupCost === 'number' && r.pickupCost > 0)
        items.push({ label: 'Origin pickup', amount: r.pickupCost });
    }
    if (!cq || typeof cq.deliveryCost !== 'number') {
      if (r && typeof r.deliveryCost === 'number' && r.deliveryCost > 0)
        items.push({ label: 'Destination delivery', amount: r.deliveryCost });
    }

    if (items.length === 0 && r && Array.isArray(r.pricingBreakdown)) {
      r.pricingBreakdown.forEach(item => {
        if (item && typeof item.amount === 'number')
          items.push({ label: item.name || item.code || 'Charge', amount: item.amount,
            basis: deriveBasis(item) });
      });
    }
    if (items.length === 0 && r && r.pricing && r.pricing.breakdown
        && typeof r.pricing.breakdown === 'object'
        && !Array.isArray(r.pricing.breakdown)) {
      Object.entries(r.pricing.breakdown).forEach(([k, v]) => {
        if (typeof v === 'number' && k !== 'total')
          items.push({ label: titleCase(k), amount: v });
      });
    }
    if (items.length === 0 && r && Array.isArray(r.additionalServices)) {
      r.additionalServices.forEach(s => {
        if (s && typeof s.amount === 'number')
          items.push({ label: s.name || 'Service', amount: s.amount,
            basis: deriveBasis(s) });
      });
    }
    if (r && typeof r.airFreight === 'number' && !items.find(i => /freight/i.test(i.label)))
      items.push({ label: 'Air freight', amount: r.airFreight,
        basis: deriveAirFreightBasis(r) });

    const seen = new Set();
    return items.filter(it => {
      const lbl = it.label.toLowerCase().replace(/\s+/g, '');
      const amt = Math.round(it.amount * 100) / 100;
      const key = lbl + ':' + amt;
      if (seen.has(key)) return false;
      seen.add(key);
      return true;
    });
  }

  // Firestore-safe snapshot of the rate offers shown to the customer. Used
  // by the homepage hero widget to persist "offers shown" alongside the lead.
  // Capped to 12 rates to stay well under the 1 MB doc limit.
  function buildRateOffersForFirestore(rates) {
    const top = (Array.isArray(rates) ? rates : []).slice(0, 12);
    return top.map((r, idx) => {
      const total = rateTotalOf(r);
      const breakdown = collectBreakdown(r);
      const offer = {
        idx,
        carrier: r.displayCarrier || r.shippingLine || r.carrier || r.airline || null,
        carrierLogoUrl: r.carrierLogoUrl || null,
        service: r.service || null,
        serviceDescription: r.serviceDescription || null,
        total: typeof total === 'number' && isFinite(total) ? total : null,
        currency: (r.pricing && r.pricing.currency) || r.currency || 'USD',
        transitDays: (r.transit && r.transit.days) || r.transitDays || r.oceanTransitTime || null,
        transitMinDays: (r.transit && r.transit.minDays) || null,
        transitMaxDays: (r.transit && r.transit.maxDays) || null,
        estimatedDelivery: (r.transit && r.transit.estimatedDelivery) || r.estimatedDelivery || null,
        validFrom: r.validFrom || null,
        validUntil: r.validUntil || r.validTo || r.validTill || null,
        originPort: (r.route && r.route.originPort) || r.originAirport || r.originPort || null,
        destinationPort: (r.route && r.route.destinationPort) || r.destinationAirport || r.destinationPort || null,
        originCountry: (r.route && r.route.originCountry) || r.originCountry || null,
        destinationCountry: (r.route && r.route.destinationCountry) || r.destinationCountry || null,
        breakdown: breakdown.map(b => ({
          label: b.label || 'Charge',
          amount: typeof b.amount === 'number' && isFinite(b.amount) ? b.amount : 0,
        })),
        features: Array.isArray(r.features) ? r.features.filter(Boolean).slice(0, 20) : [],
        restrictions: Array.isArray(r.restrictions) ? r.restrictions.filter(Boolean).slice(0, 20) : [],
        ratePerKg: typeof r.ratePerKg === 'number' ? r.ratePerKg : null,
        ratePerCBM: typeof r.ratePerCBM === 'number' ? r.ratePerCBM : null,
        actualCBM: typeof r.actualCBM === 'number' ? r.actualCBM : null,
        volumetricCBM: typeof r.volumetricCBM === 'number' ? r.volumetricCBM : null,
        chargeableCBM: typeof r.chargeableCBM === 'number' ? r.chargeableCBM : null,
        actualWeightKg: typeof r.actualWeightKg === 'number' ? r.actualWeightKg : null,
        volumetricWeightKg: typeof r.volumetricWeightKg === 'number' ? r.volumetricWeightKg : null,
        chargeableWeightKg: typeof r.chargeableWeightKg === 'number' ? r.chargeableWeightKg : null,
        minCharge: typeof r.minCharge === 'number' ? r.minCharge : null,
        bookable: typeof r.bookable === 'boolean' ? r.bookable : null,
        provider: r.provider || null,
        transportMode: r.transportMode || null,
        rateId: r.rateId || r.id || null,
      };
      Object.keys(offer).forEach(k => { if (offer[k] === null) delete offer[k]; });
      return offer;
    });
  }

  // FCL container catalog — used by the requestedContainers panel to render
  // human-readable titles ("20' STANDARD" instead of just "20"). Same 4
  // shapes Walio's /v1/rates/fcl endpoint accepts.
  const FCL_CONTAINERS = [
    { code: '20',   title: "20' STANDARD",  dims: "20' × 8' × 8.6'" },
    { code: '40',   title: "40' STANDARD",  dims: "40' × 8' × 8.6'" },
    { code: '40HC', title: "40' HIGH CUBE", dims: "40' × 8' × 9.6'" },
    { code: '45',   title: "45' HIGH CUBE", dims: "45' × 8' × 9.6'" },
  ];

  // ────────────────────────────────────────────────────────────────────────
  // RichRateCard — the card itself.
  //
  // Props:
  //   r                    — rate object from the Walio /v1/rates/* response
  //   highlight            — render with the cheapest-card emphasis (border+shadow)
  //   bestPrice            — show the BEST-PRICE chip (suppressed when topBadge.tone='cheapest')
  //   setStats             — { minTransit, maxFree, count } for set-relative badges
  //   topBadge             — { label, tone: 'cheapest'|'fastest'|'nearest' } overrides
  //   requestedContainers  — { '20': n, '40': n, ... } FCL container mix shown above breakdown
  //   originTransport      — optional, when 'abgroup_pickup' filters port-to-port chip
  //   destinationTransport — optional, when 'abgroup_deliver' filters port-to-port chip
  // ────────────────────────────────────────────────────────────────────────

  function RichRateCard({ r, highlight, bestPrice, setStats, topBadge,
                          requestedContainers, originTransport, destinationTransport }) {
    const { t, lang } = useRateT();
    const [expanded, setExpanded] = useState(false);
    const [logoFailed, setLogoFailed] = useState(false);
    const carrierIdx = useWalioCarriers();

    const ccy        = (r.pricing && r.pricing.currency) || r.currency || 'USD';
    const carrierLbl = r.displayCarrier || r.shippingLine || r.carrier || r.airline || 'Carrier';
    const service    = r.service || 'Standard';
    const serviceDes = r.serviceDescription;
    const transit    = (typeof r.combinedTransitDays === 'number' ? r.combinedTransitDays : null)
                    || (r.transit && r.transit.days) || r.transitDays || r.oceanTransitTime;
    const transitMin = r.transit && r.transit.minDays;
    const transitMax = r.transit && r.transit.maxDays;
    const etd        = (r.transit && r.transit.estimatedDelivery) || r.estimatedDelivery;
    const validUntil = r.validUntil || r.validTo || r.validTill;
    const validFrom  = r.validFrom;
    const originPort = (r.route && r.route.originPort) || r.originAirport || r.originPort;
    const destPort   = (r.route && r.route.destinationPort) || r.destinationAirport || r.destinationPort;
    const oCountry   = (r.route && r.route.originCountry) || r.originCountry;
    const dCountry   = (r.route && r.route.destinationCountry) || r.destinationCountry;
    const oDist      = r.originPortDistance != null ? r.originPortDistance
                       : (r.distanceFromOrigin != null ? r.distanceFromOrigin : null);
    const dDist      = r.destinationPortDistance != null ? r.destinationPortDistance
                       : (r.distanceToDestination != null ? r.distanceToDestination : null);
    const distUnit   = r.distanceUnit || 'mi';
    const breakdown  = collectBreakdown(r);

    const tmCode = (r.transportMode || '').toString().toUpperCase();
    const hideBasisChips = tmCode === 'AIR' || tmCode === 'LCL'
      || typeof r.ratePerKg === 'number'
      || typeof r.ratePerCBM === 'number'
      || (r.completeQuote && (typeof r.completeQuote.airFreight === 'number'
                              || typeof r.completeQuote.ratePerKg === 'number'
                              || typeof r.completeQuote.ratePerCBM === 'number'));

    const pdInfo = r.pickupDetails || {};
    const pickupCarrier = pdInfo.carrier || r.pickupCarrier || null;
    const pickupTransitDays = pdInfo.transitDays != null ? pdInfo.transitDays : r.pickupTransitDays;
    const pickupRoute = (() => {
      const fromZip = pdInfo.fromZip || null;
      const toName  = pdInfo.toName || null;
      const toCity  = pdInfo.toCity || null;
      const toState = pdInfo.toState || null;
      const toZip   = pdInfo.toZip || null;
      const dest = toName || [toCity, toState].filter(Boolean).join(', ') || toZip;
      if (fromZip && dest) return fromZip + ' → ' + dest;
      return r.pickupLocation || dest || null;
    })();
    const renderPickupSegments = () => {
      const segs = [
        pickupCarrier ? React.createElement(PickupCarrierTag, { key: 'cr', name: pickupCarrier }) : null,
        pickupTransitDays != null ? React.createElement('span', { key: 't' },
          pickupTransitDays + 'd ',
          React.createElement('span', {
            style: { color: '#98A2B3', fontWeight: 500 }
          }, '(' + t('rate.lbl.transit_time') + ')')
        ) : null,
        pickupRoute ? React.createElement('span', { key: 'r' }, pickupRoute) : null,
        r.pickupCost != null ? React.createElement('span', { key: 'c' }, fmtMoney(r.pickupCost, ccy)) : null,
      ].filter(Boolean);
      return (
        <span style={{ display: 'inline-flex', alignItems: 'center',
          flexWrap: 'wrap', gap: 6 }}>
          {segs.map((seg, i) => (
            <React.Fragment key={i}>
              {i > 0 && <span style={{ color: '#98A2B3' }}>·</span>}
              {seg}
            </React.Fragment>
          ))}
        </span>
      );
    };
    const showRichOriginPickup = hideBasisChips && !!r.hasPickup;

    const breakdownSum = breakdown.reduce((s, it) =>
      s + (typeof it.amount === 'number' && isFinite(it.amount) ? it.amount : 0), 0);
    const apiTotal = rateTotalOf(r);
    const total = breakdown.length > 0 && breakdownSum > 0 ? breakdownSum : apiTotal;

    // Filter out the "Port-to-Port" feature chip when the customer asked
    // for door pickup or door delivery — leaving it would contradict the
    // customer's request even though the carrier's underlying rate IS
    // port-to-port and the door leg is just quoted separately.
    // FCL sends the door token raw ('abgroup_pickup' / 'abgroup_deliver');
    // LCL/AIR builders map it to 'maersk_pickup' / 'maersk_deliver' before
    // POST, so both naming schemes mean "user wants door service."
    const wantsOriginDoor =
      originTransport === 'abgroup_pickup' || originTransport === 'maersk_pickup';
    const wantsDestDoor =
      destinationTransport === 'abgroup_deliver' || destinationTransport === 'maersk_deliver';
    const featuresRaw  = Array.isArray(r.features) ? r.features.filter(Boolean) : [];
    const features = (wantsOriginDoor || wantsDestDoor)
      ? featuresRaw.filter(f => !/^\s*port[\s-]*to[\s-]*port\s*$/i.test(f))
      : featuresRaw;
    const restrictions = Array.isArray(r.restrictions) ? r.restrictions.filter(Boolean) : [];

    const ratePerKg   = r.ratePerKg;
    const ratePerCBM  = r.ratePerCBM;
    const actCBM      = r.actualCBM;
    const volCBM      = r.volumetricCBM;
    const chgCBM      = r.chargeableCBM;
    const minChargeC  = r.minCharge;
    const actW        = r.actualWeightKg;
    const volW        = r.volumetricWeightKg;
    const chgW        = r.chargeableWeightKg;
    const minAir      = r.minAir;

    const walioCarrier =
      resolveCarrierLogo(carrierIdx, r.displayCarrier) ||
      resolveCarrierLogo(carrierIdx, r.shippingLine) ||
      resolveCarrierLogo(carrierIdx, r.carrier) ||
      resolveCarrierLogo(carrierIdx, r.airline);
    const fallbackBrand = carrierBrand(carrierLbl);
    const brand = walioCarrier && walioCarrier.brandColor
      ? { bg: walioCarrier.brandColor, fg: '#fff', label: fallbackBrand.label }
      : fallbackBrand;
    const showRealLogo = walioCarrier && walioCarrier.logoUrl && !logoFailed;

    const airIata    = extractIataCode(r.originAirport)
                     || extractIataCode(r.route && r.route.originPort);
    const isAirRate  = !!airIata;
    const airportName = (() => {
      if (!isAirRate) return null;
      const raw = r.originAirport || (r.route && r.route.originPort) || '';
      const stripped = String(raw).replace(new RegExp('^' + airIata + '\\s*'), '').trim();
      if (stripped) return stripped;
      if (r.route && r.route.origin && r.route.origin.city) return r.route.origin.city;
      return null;
    })();
    const isLinehaul    = r.displayType === 'WITH_LINEHAUL';
    const gatewayIata   = isLinehaul
      ? (extractIataCode(r.gatewayAirport) || r.gatewayAirport || null)
      : null;
    const destIata      = extractIataCode(r.destinationAirport)
                        || extractIataCode(r.route && r.route.destinationPort);
    const routeSegments = (() => {
      if (!isAirRate) return null;
      const segs = [airIata];
      if (gatewayIata) segs.push(gatewayIata);
      if (destIata && destIata !== airIata) segs.push(destIata);
      return segs.length >= 2 ? segs : null;
    })();
    const distancePalette = (() => {
      if (oDist == null || !Number.isFinite(oDist)) return null;
      if (oDist <= 50)  return { bg: 'rgba(18,183,106,0.12)',  fg: '#067647', bd: 'rgba(18,183,106,0.3)',  trucking: false };
      if (oDist <= 200) return { bg: 'rgba(245,158,11,0.12)', fg: '#92400E', bd: 'rgba(245,158,11,0.28)', trucking: false };
      return                    { bg: 'rgba(16,24,40,0.06)',   fg: '#475467', bd: 'rgba(16,24,40,0.14)',   trucking: true };
    })();
    const transitDisplay = transit != null
      ? (transitMin && transitMax && transitMin !== transitMax
          ? t('rate.days_range', { min: transitMin, max: transitMax })
          : t('rate.days', { n: transit }))
      : null;
    const freeTimeDisplay = (r.freeDays != null)
      ? t('rate.days', { n: r.freeDays })
      : (r.freeTime != null ? String(r.freeTime) : null);
    const hasChargeableBasis = (actCBM != null || volCBM != null || chgCBM != null
      || ratePerCBM != null || actW != null || volW != null || chgW != null
      || ratePerKg != null || minAir != null || minChargeC != null);

    // Selling badges — data-driven, max 3 visible.
    const badges = [];
    if (topBadge) {
      const tonePalette = {
        cheapest: { bg: 'rgba(18,183,106,0.12)', fg: '#067647', bd: 'rgba(18,183,106,0.3)' },
        fastest:  { bg: 'rgba(30,87,214,0.1)',   fg: '#1846B0', bd: 'rgba(30,87,214,0.28)' },
        nearest:  { bg: 'rgba(245,158,11,0.12)', fg: '#92400E', bd: 'rgba(245,158,11,0.3)' },
      }[topBadge.tone] || { bg: 'rgba(16,24,40,0.06)', fg: '#0B1220', bd: 'rgba(16,24,40,0.14)' };
      badges.push({ key: 'top-' + topBadge.tone, label: topBadge.label, ...tonePalette });
    }
    if (bestPrice && (!topBadge || topBadge.tone !== 'cheapest')) {
      badges.push({ key: 'best-price', label: t('rate.badge.best_price'),
        bg: 'rgba(18,183,106,0.12)', fg: '#067647',
        bd: 'rgba(18,183,106,0.3)' });
    }
    if (setStats && setStats.minTransit != null && transit === setStats.minTransit
        && setStats.count > 1) {
      badges.push({ key: 'fastest', label: t('rate.badge.fastest'),
        bg: 'rgba(30,87,214,0.1)', fg: '#1846B0',
        bd: 'rgba(30,87,214,0.28)' });
    }
    const isDirect = !r.hasRail
      && (!r.originalOceanPort || !originPort || r.originalOceanPort === originPort);
    if (isDirect && (originPort || destPort)) {
      badges.push({ key: 'direct', label: t('rate.badge.direct'),
        bg: 'rgba(124,58,237,0.1)', fg: '#5B21B6',
        bd: 'rgba(124,58,237,0.28)' });
    }
    if (r.hasPickup && r.hasDelivery) {
      badges.push({ key: 'd2d', label: t('rate.badge.d2d'),
        bg: 'rgba(2,132,199,0.1)', fg: '#075985',
        bd: 'rgba(2,132,199,0.3)' });
    }
    if (setStats && setStats.maxFree != null && r.freeDays != null
        && r.freeDays === setStats.maxFree && r.freeDays >= 7
        && setStats.count > 1) {
      badges.push({ key: 'free-time', label: t('rate.badge.free_time', { n: r.freeDays }),
        bg: 'rgba(245,158,11,0.12)', fg: '#92400E',
        bd: 'rgba(245,158,11,0.3)' });
    }
    if (validUntil) {
      const ms = new Date(validUntil).getTime() - Date.now();
      if (ms > 0 && ms < 3 * 24 * 60 * 60 * 1000) {
        badges.push({ key: 'urgent', label: t('rate.badge.urgent'),
          bg: 'rgba(220,38,38,0.1)', fg: '#991B1B',
          bd: 'rgba(220,38,38,0.28)' });
      }
    }
    const hasCustoms = features.some(f => /customs/i.test(f));
    if (hasCustoms) {
      badges.push({ key: 'customs', label: t('rate.badge.customs'),
        bg: 'rgba(16,24,40,0.06)', fg: '#0B1220',
        bd: 'rgba(16,24,40,0.14)' });
    }
    const visibleBadges = badges.slice(0, 3);

    const Icon = window.Icon;

    return (
      <div style={{ position: 'relative', flexShrink: 0,
        background: '#ffffff',
        border: highlight ? '1px solid rgba(30,87,214,0.32)' : '1px solid rgba(16,24,40,0.08)',
        borderRadius: 16,
        boxShadow: highlight
          ? '0 10px 24px -8px rgba(30,87,214,0.22), 0 2px 4px rgba(16,24,40,0.04), inset 0 1px 0 rgba(255,255,255,0.95)'
          : '0 4px 12px -4px rgba(16,24,40,0.08), 0 1px 2px rgba(16,24,40,0.04), inset 0 1px 0 rgba(255,255,255,0.85)',
        overflow: 'hidden',
        transition: 'transform 220ms cubic-bezier(0.16,1,0.3,1), box-shadow 220ms' }}
        onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateY(-2px)';
          e.currentTarget.style.boxShadow = highlight
            ? '0 16px 32px -8px rgba(30,87,214,0.3), 0 4px 8px rgba(16,24,40,0.06), inset 0 1px 0 rgba(255,255,255,0.95)'
            : '0 12px 24px -8px rgba(16,24,40,0.14), 0 2px 4px rgba(16,24,40,0.06), inset 0 1px 0 rgba(255,255,255,0.85)';
        }}
        onMouseLeave={(e) => { e.currentTarget.style.transform = 'translateY(0)';
          e.currentTarget.style.boxShadow = highlight
            ? '0 10px 24px -8px rgba(30,87,214,0.22), 0 2px 4px rgba(16,24,40,0.04), inset 0 1px 0 rgba(255,255,255,0.95)'
            : '0 4px 12px -4px rgba(16,24,40,0.08), 0 1px 2px rgba(16,24,40,0.04), inset 0 1px 0 rgba(255,255,255,0.85)';
        }}>

        {/* AIR-only header strip — IATA badge + airport name + distance hint */}
        {isAirRate && (
          <div data-rate-row="air-airport" style={{ padding: '10px 16px 0' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
              <span style={{ padding: '4px 10px', borderRadius: 8,
                background: 'linear-gradient(180deg, #2E6AE8 0%, #1E57D6 60%, #1846B0 100%)',
                color: '#fff', fontSize: 13, fontWeight: 800,
                letterSpacing: '0.06em',
                fontFamily: 'JetBrains Mono, ui-monospace, monospace',
                boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.35), 0 2px 6px rgba(30,87,214,0.25)' }}>
                {airIata}
              </span>
              {airportName && (
                <span style={{ fontSize: 12, fontWeight: 700, color: '#0B1220',
                  letterSpacing: '-0.005em', minWidth: 0,
                  overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {airportName}
                </span>
              )}
              {isLinehaul && gatewayIata && (
                <span title={'Connects through ' + gatewayIata}
                  style={{ padding: '3px 8px', borderRadius: 9999,
                    background: 'rgba(124,58,237,0.1)', color: '#5B21B6',
                    border: '1px solid rgba(124,58,237,0.28)',
                    fontSize: 10.5, fontWeight: 700, letterSpacing: '0.02em',
                    fontFamily: 'Inter, system-ui, sans-serif' }}>
                  {t('rate.via', { p: gatewayIata })}
                </span>
              )}
              {distancePalette && (
                <span title={distancePalette.trucking
                  ? t('rate.air.trucking_required')
                  : undefined}
                  style={{ padding: '3px 8px', borderRadius: 9999,
                    background: distancePalette.bg, color: distancePalette.fg,
                    border: '1px solid ' + distancePalette.bd,
                    fontSize: 10.5, fontWeight: 700, letterSpacing: '0.02em',
                    fontFamily: 'Inter, system-ui, sans-serif',
                    display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                  {t('rate.air.distance_away', { n: Math.round(oDist), unit: distUnit })}
                  {distancePalette.trucking && (
                    <span style={{ fontSize: 9.5, fontWeight: 600, opacity: 0.85 }}>
                      · {t('rate.air.trucking_short')}
                    </span>
                  )}
                </span>
              )}
            </div>
            {routeSegments && routeSegments.length >= 2 && (
              <div style={{ marginTop: 6, display: 'inline-flex',
                alignItems: 'center', gap: 5, padding: '2px 8px',
                borderRadius: 6,
                background: 'rgba(247,249,252,0.85)',
                border: '1px solid rgba(16,24,40,0.06)',
                fontSize: 10.5, fontWeight: 600, color: '#475467',
                fontFamily: 'JetBrains Mono, ui-monospace, monospace',
                letterSpacing: '0.04em' }}>
                {routeSegments.map((seg, i) => (
                  <React.Fragment key={i}>
                    {i > 0 && (
                      <span style={{ color: '#98A2B3', opacity: 0.7,
                        fontSize: 9.5 }}>→</span>
                    )}
                    <span style={{
                      color: i === 0 ? '#1E57D6' : (i === routeSegments.length - 1 ? '#0B1220' : '#5B21B6') }}>
                      {seg}
                    </span>
                  </React.Fragment>
                ))}
                {isLinehaul && (
                  <span style={{ marginLeft: 4, padding: '0 5px',
                    borderRadius: 4,
                    background: 'rgba(124,58,237,0.1)',
                    color: '#5B21B6',
                    fontSize: 9, letterSpacing: '0.08em',
                    fontFamily: 'Inter, system-ui, sans-serif',
                    fontWeight: 800, textTransform: 'uppercase' }}>
                    {t('rate.air.connection')}
                  </span>
                )}
              </div>
            )}
          </div>
        )}

        {/* Hero band — carrier brand chip, name, big price.
            className keeps the 3-column layout on mobile (see Homepage.html's
            blanket grid-flatten rule). */}
        <div className="rrc-hero-row"
          style={{ padding: '14px 16px 12px',
            display: 'grid', gridTemplateColumns: 'auto 1fr auto',
            alignItems: 'center', gap: 14 }}>
          {showRealLogo ? (
            <div style={{ width: 56, height: 56, borderRadius: 14,
              background: '#fff',
              border: '1px solid rgba(16,24,40,0.06)',
              display: 'grid', placeItems: 'center',
              padding: 6, flexShrink: 0,
              boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.95), 0 1px 2px rgba(16,24,40,0.06)' }}>
              <img src={walioCarrier.logoUrl}
                alt={`${walioCarrier.name} logo`}
                onError={() => setLogoFailed(true)}
                style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain',
                  display: 'block' }}/>
            </div>
          ) : (
            <div style={{ width: 56, height: 56, borderRadius: 14,
              background: brand.bg, color: brand.fg,
              display: 'grid', placeItems: 'center',
              fontFamily: 'Inter, system-ui, sans-serif', fontSize: 12,
              fontWeight: 800, letterSpacing: '0.02em',
              boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.18), 0 2px 4px rgba(16,24,40,0.1)',
              flexShrink: 0 }}>
              {brand.label}
            </div>
          )}
          <div style={{ minWidth: 0 }}>
            <span style={{ display: 'block', fontSize: 15, fontWeight: 700, color: '#0B1220',
              letterSpacing: '-0.01em', whiteSpace: 'nowrap', overflow: 'hidden',
              textOverflow: 'ellipsis', maxWidth: '100%' }}>{carrierLbl}</span>
            <div style={{ fontSize: 12, color: '#667085', marginTop: 3, lineHeight: 1.3,
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
              {titleCase(service)}{serviceDes ? ` · ${serviceDes}` : ''}
            </div>
            {visibleBadges.length > 0 && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 7 }}>
                {visibleBadges.map(b => (
                  <span key={b.key} style={{
                    padding: '2px 8px', borderRadius: 9999,
                    background: b.bg, color: b.fg,
                    border: `1px solid ${b.bd}`,
                    fontSize: 9.5, fontWeight: 700, letterSpacing: '0.06em',
                    textTransform: 'uppercase', whiteSpace: 'nowrap',
                    fontFamily: 'Inter, system-ui, sans-serif' }}>
                    {b.label}
                  </span>
                ))}
              </div>
            )}
          </div>
          {(() => {
            // Scale the headline price font down for long amounts so a
            // 6-7 digit total ("$155,500" / "$1,550,000") doesn't blow out
            // the price column and squeeze the carrier name on mobile.
            // Common buckets:
            //   ≤6 chars ($3,075)      → 26px  (unchanged from before)
            //    7 chars ($15,500)     → 23px
            //    8 chars ($155,500)    → 20px
            //    9+ chars ($1,550,000) → 18px
            const priceStr = fmtMoney(total, ccy) || '—';
            const priceFs = priceStr.length <= 6 ? 26
                          : priceStr.length === 7 ? 23
                          : priceStr.length === 8 ? 20
                          : 18;
            return (
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: priceFs, fontWeight: 800, color: '#0B1220',
                  letterSpacing: '-0.03em',
                  fontVariantNumeric: 'tabular-nums',
                  fontFeatureSettings: '"tnum" 1, "cv11" 1',
                  fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "SF Pro Display", "Segoe UI", Roboto, sans-serif',
                  lineHeight: 1, whiteSpace: 'nowrap' }}>
                  {priceStr}
                </div>
                <div style={{ fontSize: 9.5, color: '#98A2B3', marginTop: 5,
                  letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 700,
                  fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, sans-serif' }}>
                  {t('rate.allin')} {ccy}
                </div>
              </div>
            );
          })()}
        </div>

        {/* Quick stats strip. className + --rrc-stats-cols CSS variable keep
            the dynamic 1–3 column count on mobile (page-level mobile rule
            would otherwise flatten this to 1 column). */}
        <div style={{ padding: '0 16px 12px' }}>
          <div className="rrc-quick-stats"
            style={{ display: 'grid',
              gridTemplateColumns: `repeat(${[transitDisplay, fmtShortDate(etd), freeTimeDisplay].filter(Boolean).length || 1}, minmax(0, 1fr))`,
              '--rrc-stats-cols': [transitDisplay, fmtShortDate(etd), freeTimeDisplay].filter(Boolean).length || 1,
              gap: 8, padding: '10px 12px',
              background: 'linear-gradient(180deg, rgba(247,249,252,0.7) 0%, rgba(247,249,252,0.4) 100%)',
              borderRadius: 10, border: '1px solid rgba(16,24,40,0.05)' }}>
            {transitDisplay && (
              <QuickStat label={t('rate.lbl.transit')} value={transitDisplay}/>
            )}
            {fmtShortDate(etd) && (
              <QuickStat label={t('rate.lbl.etd')} value={fmtShortDate(etd)}/>
            )}
            {freeTimeDisplay && (
              <QuickStat label={t('rate.lbl.free_time')} value={freeTimeDisplay}/>
            )}
          </div>
        </div>

        {/* Route line — port names + a small distance chip when the API
            returned origin/destination port distance. Skipped for AIR since
            the AIR header strip already shows the distance hint up top. */}
        {(originPort || destPort) && (
          <div style={{ padding: '0 16px 12px' }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6,
              padding: '8px 12px',
              background: '#fff', border: '1px solid rgba(16,24,40,0.06)',
              borderRadius: 10 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8,
                fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', fontSize: 11,
                color: '#0B1220', fontWeight: 600, letterSpacing: '0.02em',
                minWidth: 0 }}>
                <span style={{ overflow: 'hidden', textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap', minWidth: 0 }}>
                  {originPort || '—'}{oCountry ? ` (${oCountry})` : ''}
                </span>
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none"
                  stroke="#1E57D6" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"
                  style={{ flexShrink: 0 }}>
                  <path d="M5 12h14M13 6l6 6-6 6"/>
                </svg>
                <span style={{ overflow: 'hidden', textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap', minWidth: 0 }}>
                  {destPort || '—'}{dCountry ? ` (${dCountry})` : ''}
                </span>
              </div>
              {/* Distance hints — only render the row if at least one side
                  has a known distance. Each side is independent so a rate
                  with origin-distance but no dest-distance still shows. */}
              {!isAirRate && (Number.isFinite(oDist) || Number.isFinite(dDist)) && (
                <div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr',
                  alignItems: 'center', gap: 8, fontSize: 10.5, fontWeight: 600,
                  color: '#667085', letterSpacing: '0.02em',
                  fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' }}>
                  <span style={{ minWidth: 0,
                    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {Number.isFinite(oDist) ? (
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                        <span style={{ width: 4, height: 4, borderRadius: 9999,
                          background: '#1E57D6', flexShrink: 0 }}/>
                        <span style={{ color: '#1E57D6', fontWeight: 700,
                          fontFamily: 'JetBrains Mono, ui-monospace, monospace' }}>
                          {Math.round(oDist)} {distUnit}
                        </span>
                        <span>{t('rate.lbl.from_origin')}</span>
                      </span>
                    ) : null}
                  </span>
                  <span aria-hidden style={{ width: 11, flexShrink: 0 }}/>
                  <span style={{ minWidth: 0,
                    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {Number.isFinite(dDist) ? (
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                        <span style={{ width: 4, height: 4, borderRadius: 9999,
                          background: '#1E57D6', flexShrink: 0 }}/>
                        <span style={{ color: '#1E57D6', fontWeight: 700,
                          fontFamily: 'JetBrains Mono, ui-monospace, monospace' }}>
                          {Math.round(dDist)} {distUnit}
                        </span>
                        <span>{t('rate.lbl.to_destination')}</span>
                      </span>
                    ) : null}
                  </span>
                </div>
              )}
            </div>
          </div>
        )}

        {/* Container mix — FCL only, when caller passed requestedContainers */}
        {(() => {
          if (!requestedContainers) return null;
          const rows = Object.entries(requestedContainers)
            .filter(([, n]) => Number(n) > 0);
          if (rows.length === 0) return null;
          return (
            <div data-rate-row="containers" style={{ padding: '0 16px 12px' }}>
              <div style={{ marginBottom: 6, fontSize: 10, fontWeight: 700,
                color: '#475467', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
                {t('rate.lbl.containers')}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                {rows.map(([code, qty]) => {
                  const spec = FCL_CONTAINERS.find(c => c.code === code);
                  const title = spec ? spec.title : code;
                  return (
                    <div key={code} style={{
                      display: 'flex', alignItems: 'center', gap: 8,
                      padding: '7px 10px', background: '#fff',
                      border: '1px solid rgba(16,24,40,0.06)', borderRadius: 9,
                      fontFamily: 'Inter, system-ui, sans-serif', fontSize: 11.5 }}>
                      <span style={{ width: 22, height: 22, borderRadius: 6,
                        background: '#EFF6FF', color: '#1846B0',
                        display: 'inline-grid', placeItems: 'center', flexShrink: 0 }}>
                        {Icon && <Icon name="container" size={11}/>}
                      </span>
                      <span style={{ flexShrink: 0, fontWeight: 700, color: '#1846B0',
                        fontFamily: 'JetBrains Mono, monospace' }}>{qty}×</span>
                      <span style={{ flex: 1, minWidth: 0, color: '#0B1220', fontWeight: 600,
                        whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                        {title}
                      </span>
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })()}

        {/* Always-visible pickup / delivery pending banner. Customer asked
            for door service, but this carrier's live rate didn't include the
            door leg — surface it on the collapsed card so the customer reads
            "pending" without having to expand the breakdown. The detailed
            note still appears inside the Pickup, delivery & drayage panel.

            FCL door pickup commonly comes back as "Origin Drayage: Door to
            PORT X" inside the breakdown rather than as r.hasPickup, so we
            also scan the breakdown labels — without that, drayage-only rates
            falsely show as pending. */}
        {(() => {
          const pickupFulfilled = isPickupFulfilled(r, breakdown);
          const deliveryFulfilled = isDeliveryFulfilled(r, breakdown);
          const pickupPending = wantsOriginDoor && !pickupFulfilled;
          const deliveryPending = wantsDestDoor && !deliveryFulfilled;
          if (!pickupPending && !deliveryPending) return null;
          const labels = [];
          if (pickupPending)   labels.push(t('rate.lbl.pickup_pending'));
          if (deliveryPending) labels.push(t('rate.lbl.delivery_pending'));
          return (
            <div data-rate-row="pending" style={{ padding: '0 16px 12px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8,
                padding: '8px 12px',
                background: 'rgba(247,144,9,0.08)',
                border: '1px solid rgba(247,144,9,0.28)',
                borderRadius: 10,
                fontFamily: SPEC_FONT, fontSize: 11.5,
                color: '#7A2E0E', lineHeight: 1.4 }}>
                <span style={{ width: 18, height: 18, borderRadius: 9999,
                  background: 'rgba(247,144,9,0.2)', color: '#92400E',
                  display: 'inline-grid', placeItems: 'center', flexShrink: 0,
                  fontWeight: 800, fontSize: 11 }}>!</span>
                <span style={{ minWidth: 0 }}>
                  <strong style={{ fontWeight: 800 }}>{labels.join(' · ')}</strong>
                  {' — '}
                  {pickupPending
                    ? t('rate.warn.pickup_pending')
                    : t('rate.warn.delivery_pending')}
                </span>
              </div>
            </div>
          );
        })()}

        {/* Always-visible port-to-port info pill. When the customer asked
            for port-to-port at BOTH ends (no door pickup, no door delivery),
            confirm what the rate covers so they're not surprised they need
            to handle the inland legs themselves. Informational blue tone
            (not warning) — this is the expected outcome of their request. */}
        {(() => {
          // Only show when neither end asked for door service AND we don't
          // already have a pickup/delivery pending banner above (mutually
          // exclusive — they only co-occur when transport tokens are mixed).
          if (wantsOriginDoor || wantsDestDoor) return null;
          // Skip if origin transport is unknown — the prop may not have been
          // passed (e.g. homepage hero, which doesn't forward it yet).
          if (!originTransport && !destinationTransport) return null;
          const isP2P = (originTransport === 'customer_deliver' || !originTransport)
            && (destinationTransport === 'customer_pickup' || !destinationTransport);
          if (!isP2P) return null;
          return (
            <div data-rate-row="port-to-port" style={{ padding: '0 16px 12px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8,
                padding: '8px 12px',
                background: 'rgba(30,87,214,0.07)',
                border: '1px solid rgba(30,87,214,0.25)',
                borderRadius: 10,
                fontFamily: SPEC_FONT, fontSize: 11.5,
                color: '#1846B0', lineHeight: 1.4 }}>
                <span style={{ width: 18, height: 18, borderRadius: 9999,
                  background: 'rgba(30,87,214,0.18)', color: '#1846B0',
                  display: 'inline-grid', placeItems: 'center', flexShrink: 0,
                  fontWeight: 800, fontSize: 11 }}>i</span>
                <span style={{ minWidth: 0 }}>
                  <strong style={{ fontWeight: 800 }}>{t('rate.lbl.port_to_port')}</strong>
                  {' — '}
                  {t('rate.info.port_to_port')}
                </span>
              </div>
            </div>
          );
        })()}

        {/* Show / hide breakdown disclosure */}
        <div style={{ padding: '0 16px 12px' }}>
          <button type="button" onClick={() => setExpanded(e => !e)}
            aria-expanded={expanded}
            style={{ width: '100%', padding: '10px 14px',
              background: expanded ? 'rgba(30,87,214,0.06)' : '#fff',
              border: '1px solid rgba(16,24,40,0.1)',
              borderRadius: 10, cursor: 'pointer',
              fontFamily: 'inherit', fontSize: 12, fontWeight: 600, color: '#0B1220',
              letterSpacing: '-0.005em',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'space-between', gap: 8,
              boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.85)',
              transition: 'background 200ms, border-color 200ms' }}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = expanded ? 'rgba(30,87,214,0.1)' : 'rgba(247,249,252,0.85)';
              e.currentTarget.style.borderColor = 'rgba(30,87,214,0.3)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = expanded ? 'rgba(30,87,214,0.06)' : '#fff';
              e.currentTarget.style.borderColor = 'rgba(16,24,40,0.1)';
            }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
              {Icon && <Icon name="sparkles" size={12} style={{ color: '#1E57D6' }}/>}
              {expanded ? t('rate.hide_breakdown') : t('rate.show_breakdown')}
            </span>
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none"
              stroke="#475467" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"
              style={{ transform: expanded ? 'rotate(180deg)' : 'rotate(0deg)',
                transition: 'transform 220ms cubic-bezier(0.4,0,0.2,1)' }}>
              <path d="M6 9l6 6 6-6"/>
            </svg>
          </button>
        </div>

        {expanded && (
          <div style={{ background: 'rgba(247,249,252,0.55)',
            borderTop: '1px solid rgba(16,24,40,0.06)',
            paddingTop: 10 }}>

            {breakdown.length > 0 && (() => {
              const isPickupRow = (it) => /origin\s+pickup/i.test(it.label || '');
              const isMarkupFreight = (it) => {
                const lbl = (it.label || '').toLowerCase();
                return lbl === 'air freight' || lbl === 'ocean freight';
              };
              const pickupRows  = hideBasisChips ? breakdown.filter(isPickupRow) : [];
              const exportRows  = hideBasisChips ? breakdown.filter(it => !isPickupRow(it)) : breakdown;
              const breakdownLabel = hideBasisChips
                ? t('rate.section.export_charges')
                : t('rate.section.breakdown');
              const totalFooter = (
                <div style={{ display: 'flex', alignItems: 'baseline',
                  justifyContent: 'space-between', gap: 12,
                  padding: '10px 14px 12px',
                  borderTop: '1px solid rgba(16,24,40,0.12)',
                  background: 'linear-gradient(180deg, rgba(247,249,252,0.7) 0%, rgba(247,249,252,0.4) 100%)' }}>
                  <span style={{ color: '#0B1220', fontWeight: 700,
                    fontSize: 11, letterSpacing: '0.1em',
                    textTransform: 'uppercase',
                    fontFamily: SPEC_FONT }}>
                    {t('rate.total_allin')}
                  </span>
                  <span style={{ color: '#0B1220', fontWeight: 800,
                    fontSize: 16, letterSpacing: '-0.02em',
                    fontVariantNumeric: 'tabular-nums',
                    fontFeatureSettings: '"tnum" 1, "cv11" 1',
                    fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "SF Pro Display", "Segoe UI", Roboto, sans-serif' }}>
                    {fmtMoney(total, ccy)}
                  </span>
                </div>
              );
              return (
                <React.Fragment>
                  {showRichOriginPickup ? (
                    <SpecPanel label={t('rate.section.origin_pickup')}>
                      <SpecRow label={t('rate.lbl.pickup')} value={renderPickupSegments()}/>
                    </SpecPanel>
                  ) : pickupRows.length > 0 && (
                    <SpecPanel label={t('rate.section.origin_pickup')}>
                      {pickupRows.map((it, i) => (
                        <SpecRow key={`pickup-${it.label}-${i}`} label={it.label}
                          value={fmtMoney(it.amount, ccy)}/>
                      ))}
                    </SpecPanel>
                  )}
                  {exportRows.length > 0 && (
                    <SpecPanel label={breakdownLabel} footer={totalFooter}>
                      {exportRows.map((it, i) => (
                        <SpecRow key={`${it.label}-${i}`} label={it.label}
                          value={fmtMoney(it.amount, ccy)}
                          basis={(hideBasisChips && isMarkupFreight(it)) ? null : it.basis}/>
                      ))}
                    </SpecPanel>
                  )}
                </React.Fragment>
              );
            })()}

            {hasChargeableBasis && (
              <SpecPanel label={t('rate.section.basis')}>
                {actCBM != null  && <SpecRow label={t('rate.lbl.actual_volume')}     value={`${actCBM} cbm`}/>}
                {volCBM != null  && <SpecRow label={t('rate.lbl.volumetric_volume')} value={`${volCBM} cbm`}/>}
                {chgCBM != null  && <SpecRow label={t('rate.lbl.chargeable_volume')} value={`${chgCBM} cbm`}/>}
                {ratePerCBM != null && <SpecRow label={t('rate.lbl.rate_cbm')}       value={fmtMoney(ratePerCBM, ccy)}/>}
                {minChargeC != null && <SpecRow label={t('rate.lbl.min_charge')}     value={fmtMoney(minChargeC, ccy)}/>}
                {actW != null  && <SpecRow label={t('rate.lbl.actual_weight')}     value={`${actW} kg`}/>}
                {volW != null  && <SpecRow label={t('rate.lbl.volumetric_weight')} value={`${volW} kg`}/>}
                {chgW != null  && <SpecRow label={t('rate.lbl.chargeable_weight')} value={`${chgW} kg`}/>}
                {ratePerKg != null && <SpecRow label={t('rate.lbl.rate_kg')} value={fmtMoney(ratePerKg, ccy)}/>}
                {minAir != null && <SpecRow label={t('rate.lbl.min_air')} value={fmtMoney(minAir, ccy)}/>}
                {r.minApplied != null && <SpecRow label={t('rate.lbl.min_applied')} value={r.minApplied ? t('rate.lbl.yes') : t('rate.lbl.no')}/>}
              </SpecPanel>
            )}

            {(oDist != null || dDist != null || (r.hasRail && (r.railOrigin || r.railDestination))
              || r.originalOceanPort || (validFrom || validUntil)) && (
              <SpecPanel label={t('rate.section.route')}>
                {oDist != null && (
                  <SpecRow label={t('rate.lbl.origin_dist')} value={`${oDist} ${distUnit}`}/>
                )}
                {dDist != null && (
                  <SpecRow label={t('rate.lbl.dest_dist')} value={`${dDist} ${distUnit}`}/>
                )}
                {r.hasRail && (r.railOrigin || r.railDestination) && (
                  <SpecRow label={t('rate.lbl.rail_leg')}
                    value={`${r.railOrigin || '—'} → ${r.railDestination || '—'}`}/>
                )}
                {r.originalOceanPort && (
                  <SpecRow label={t('rate.lbl.original_port')} value={r.originalOceanPort}/>
                )}
                {r.oceanTransitTime != null && (
                  <SpecRow label={t('rate.lbl.ocean_transit')} value={t('rate.days', { n: r.oceanTransitTime })}/>
                )}
                {r.railTransitTime != null && (
                  <SpecRow label={t('rate.lbl.rail_transit')}
                    value={t('rate.days', { n: r.railTransitTime }) + (r.railTransitPending ? ' ' + t('rate.transit.estimate') : '')}/>
                )}
                {(validFrom || validUntil) && (
                  <SpecRow label={t('rate.lbl.valid')}
                    value={validFrom && validUntil
                      ? `${fmtShortDate(validFrom)} → ${fmtDate(validUntil)}`
                      : t('rate.lbl.through', { date: fmtDate(validUntil || validFrom) })}/>
                )}
              </SpecPanel>
            )}

            {(r.closingDate || r.sailingDate || r.nextSailing
              || (Array.isArray(r.sailingSchedules) && r.sailingSchedules.length > 0)) && (
              <SpecPanel label={t('rate.section.sailings')}>
                {r.closingDate && <SpecRow label={t('rate.lbl.cutoff')} value={fmtDate(r.closingDate)}/>}
                {r.sailingDate && <SpecRow label={t('rate.lbl.sailing')} value={fmtDate(r.sailingDate)}/>}
                {r.nextSailing && <SpecRow label={t('rate.lbl.next_sailing')} value={fmtDate(r.nextSailing)}/>}
                {Array.isArray(r.sailingSchedules) && r.sailingSchedules.length > 0 && (
                  <SpecRow label={t('rate.lbl.schedules')}
                    value={t('rate.lbl.weekly', { n: r.sailingSchedules.length })}/>
                )}
              </SpecPanel>
            )}

            {(() => {
              const breakdownHasDrayage = breakdown.some(b => /drayage/i.test(b.label || ''));
              const showDrayageRow = r.hasDrayage && !breakdownHasDrayage;
              const pickupFallback = !!pdInfo.fallbackToMiami;
              const showBottomPickup = r.hasPickup && !showRichOriginPickup;
              // Pickup / delivery pending: customer asked for door service but
              // the carrier returned a rate without it. Surface "pending" so
              // the customer knows it's not a missed checkbox — pricing for
              // the door leg will follow by email. isPickupFulfilled also
              // recognizes "Origin Drayage: Door to PORT X" inside the
              // breakdown, which is how FCL door pickup commonly comes back.
              const pickupPending = wantsOriginDoor
                && !isPickupFulfilled(r, breakdown);
              const deliveryPending = wantsDestDoor
                && !isDeliveryFulfilled(r, breakdown);
              const sectionVisible = showBottomPickup || r.hasDelivery
                || (showDrayageRow && (r.drayageCost > 0 || r.drayageWarning))
                || r.drayageWarning || r.deliveryWarning || pickupFallback
                || pickupPending || deliveryPending;
              const warning = (txt) => (
                <div style={{ margin: '8px 14px 10px', padding: '8px 10px',
                  background: 'rgba(247,144,9,0.1)',
                  border: '1px solid rgba(247,144,9,0.25)', borderRadius: 8,
                  fontSize: 11, color: '#7A2E0E', lineHeight: 1.4,
                  fontFamily: SPEC_FONT }}>
                  <strong style={{ fontWeight: 700 }}>{t('rate.lbl.note')}</strong> {txt}
                </div>
              );
              const pendingPill = (label) => (
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6,
                  padding: '2px 9px', borderRadius: 9999,
                  background: 'rgba(247,144,9,0.12)',
                  border: '1px solid rgba(247,144,9,0.3)',
                  color: '#92400E', fontSize: 11, fontWeight: 700,
                  fontFamily: SPEC_FONT, letterSpacing: '0.02em' }}>
                  <span style={{ width: 6, height: 6, borderRadius: 9999,
                    background: '#F79009', display: 'inline-block' }}/>
                  {label}
                </span>
              );
              return sectionVisible && (
                <SpecPanel label={t('rate.section.pickup')}
                  footer={(r.drayageWarning || r.deliveryWarning || pickupFallback
                          || pickupPending || deliveryPending) ? (
                    <div>
                      {pickupFallback && warning(t('rate.warn.no_ltl'))}
                      {r.drayageWarning && warning(r.drayageWarning)}
                      {r.deliveryWarning && warning(r.deliveryWarning)}
                      {pickupPending && warning(t('rate.warn.pickup_pending'))}
                      {deliveryPending && warning(t('rate.warn.delivery_pending'))}
                    </div>
                  ) : null}>
                  {showBottomPickup && (
                    <SpecRow label={t('rate.lbl.pickup')} value={renderPickupSegments()}/>
                  )}
                  {pickupPending && !showBottomPickup && (
                    <SpecRow label={t('rate.lbl.pickup')}
                      value={pendingPill(t('rate.lbl.pickup_pending'))}/>
                  )}
                  {r.hasDelivery && (
                    <SpecRow label={t('rate.lbl.delivery')}
                      value={[r.deliveryLocation, fmtMoney(r.deliveryCost, ccy)].filter(Boolean).join(' · ')}/>
                  )}
                  {deliveryPending && !r.hasDelivery && (
                    <SpecRow label={t('rate.lbl.delivery')}
                      value={pendingPill(t('rate.lbl.delivery_pending'))}/>
                  )}
                  {showDrayageRow && (
                    <SpecRow label={t('rate.lbl.drayage')}
                      value={fmtMoney(r.drayageCost, ccy) || t('rate.lbl.included')}/>
                  )}
                </SpecPanel>
              );
            })()}

            {(features.length > 0 || restrictions.length > 0) && (
              <div style={{ padding: '0 12px 10px' }}>
                <div style={{ background: '#ffffff',
                  border: '1px solid rgba(16,24,40,0.08)',
                  borderRadius: 10,
                  overflow: 'hidden',
                  boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.85)' }}>
                  <div style={{ padding: '10px 14px 6px',
                    fontSize: 9.5, fontWeight: 700, color: '#98A2B3',
                    letterSpacing: '0.14em', textTransform: 'uppercase',
                    fontFamily: SPEC_FONT }}>
                    {t('rate.section.inclusions')}
                  </div>
                  {features.length > 0 && (
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6,
                      padding: '0 14px 10px' }}>
                      {features.map((f, i) => (
                        <span key={i} style={{ padding: '3px 9px', borderRadius: 9999,
                          background: 'rgba(18,183,106,0.1)', color: '#067647',
                          border: '1px solid rgba(18,183,106,0.25)',
                          fontSize: 10.5, fontWeight: 600,
                          letterSpacing: '0.01em',
                          fontFamily: SPEC_FONT }}>
                          ✓ {f}
                        </span>
                      ))}
                    </div>
                  )}
                  {restrictions.length > 0 && (
                    <div style={{ padding: '8px 14px 10px',
                      borderTop: features.length > 0 ? '1px solid rgba(16,24,40,0.05)' : 0 }}>
                      <div style={{ fontSize: 9.5, fontWeight: 700, color: '#98A2B3',
                        letterSpacing: '0.12em', textTransform: 'uppercase',
                        marginBottom: 4, fontFamily: SPEC_FONT }}>
                        {t('rate.restrictions')}
                      </div>
                      {restrictions.map((x, i) => (
                        <div key={i} style={{ fontSize: 11.5, color: '#475467',
                          lineHeight: 1.45, fontFamily: SPEC_FONT,
                          padding: '2px 0' }}>• {x}</div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>
        )}

        {/* Footer */}
        <div style={{ padding: '7px 12px 9px',
          borderTop: '1px solid rgba(16,24,40,0.06)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          gap: 10, fontSize: 10, color: '#667085',
          fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', letterSpacing: '0.02em' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            {r.provider && <span>{t('rate.via', { p: r.provider })}</span>}
            {r.transportMode && r.provider && <span style={{ opacity: 0.4 }}>·</span>}
            {r.transportMode && <span>{r.transportMode}</span>}
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            {r.bookable !== undefined && (
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4,
                color: r.bookable ? '#067647' : '#98A2B3' }}>
                <span style={{ width: 6, height: 6, borderRadius: 9999,
                  background: r.bookable ? '#12b76a' : '#98A2B3' }}/>
                {r.bookable ? t('rate.bookable') : t('rate.quote_only')}
              </span>
            )}
          </span>
        </div>
      </div>
    );
  }

  // ────────────────────────────────────────────────────────────────────────
  // NoRatesGlass — premium custom-quote fallback shown when the Walio rates
  // API returns zero rates. Ported from the homepage hero so the landings
  // (international-moving, vehicle-shipping) and future blog calculators
  // get the same polished "we're calculating your custom rate" surface
  // instead of a plain warning banner.
  //
  // Props (all optional — the component degrades gracefully when missing):
  //   summary             — { mode, modeIcon, modeName, unit, weight, ready,
  //                           fromLabel, toLabel, fromPlace, toPlace }
  //   lead                — { name, email, phone, company } from the lead form
  //   onEdit              — back / edit-search button handler (header)
  //   onChangeService     — "Start new search" / "Iniciar nueva búsqueda" CTA
  //   onClose             — close button handler (header)
  //   compact             — when true, drops the header (back/edit/close) for
  //                         consumers that already wrap the component in
  //                         their own chrome (e.g. the landing calculator).
  // ────────────────────────────────────────────────────────────────────────

  // Frosted-glass border overlay — used for the outer card chrome.
  function LiquidBorder({ radius = 20, alpha = [0.8, 0.3] }) {
    const [a, b] = alpha;
    return (
      <div aria-hidden style={{ position: 'absolute', inset: 0, borderRadius: radius,
        padding: 1.4, pointerEvents: 'none',
        background: `linear-gradient(180deg, rgba(255,255,255,${a}) 0%, rgba(255,255,255,${b}) 20%, transparent 40%, transparent 60%, rgba(255,255,255,${b}) 80%, rgba(255,255,255,${a}) 100%)`,
        WebkitMask: 'linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)',
        WebkitMaskComposite: 'xor', maskComposite: 'exclude' }}/>
    );
  }

  // Step indicator (mirrors the hero's). Used inside NoRatesGlass at step 6/6.
  function StepDots({ step, total = 6, t }) {
    const dots = Array.from({ length: total }, (_, i) => i + 1);
    return (
      <div style={{ position: 'relative', padding: '10px 18px 0',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
          {dots.map(n => {
            const active = n === step;
            const done   = n < step;
            return (
              <span key={n} style={{
                width: active ? 22 : 6, height: 6, borderRadius: 9999,
                background: active
                  ? 'linear-gradient(90deg, #2E6AE8 0%, #1E57D6 100%)'
                  : done ? 'rgba(30,87,214,0.45)' : 'rgba(16,24,40,0.12)',
                transition: 'width 280ms cubic-bezier(0.4,0,0.2,1), background 200ms' }}/>
            );
          })}
        </div>
        <div style={{ fontSize: 10, color: '#98A2B3', fontWeight: 600,
          fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', letterSpacing: '0.06em',
          textTransform: 'uppercase' }}>
          {t('q.step_x_of_y', { n: step, total })}
        </div>
      </div>
    );
  }

  // Single contact-line with icon chip + truncation. Used in the contact
  // info section of NoRatesGlass.
  function ContactRow({ icon, text, mono }) {
    const Icon = window.Icon;
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
        <span style={{ width: 22, height: 22, borderRadius: 7, flexShrink: 0,
          background: '#fff', border: '1px solid rgba(16,24,40,0.08)',
          display: 'inline-grid', placeItems: 'center', color: '#475467' }}>
          {Icon && <Icon name={icon} size={11}/>}
        </span>
        <span style={{ fontSize: 12, fontWeight: 600, color: '#0B1220',
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          minWidth: 0,
          fontFamily: mono
            ? 'JetBrains Mono, ui-monospace, Menlo, monospace'
            : 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
          letterSpacing: mono ? '0.005em' : '-0.005em' }}>
          {text}
        </span>
      </div>
    );
  }

  function NoRatesGlass({ summary, lead, onEdit, onChangeService, onClose, compact }) {
    const { t } = useRateT();
    const Icon = window.Icon;
    const wrapRef = React.useRef(null);
    const [wide, setWide] = useState(true);
    const [narrowHeader, setNarrowHeader] = useState(false);
    useEffect(() => {
      if (!wrapRef.current || typeof ResizeObserver === 'undefined') return;
      const ro = new ResizeObserver(([e]) => {
        const w = e.contentRect.width;
        setWide(w >= 640);
        setNarrowHeader(w <= 820);
      });
      ro.observe(wrapRef.current);
      return () => ro.disconnect();
    }, []);

    const s = summary || {};
    const modeIcon = s.modeIcon || 'box';
    const modeName = s.modeName || 'Quote';
    const fromLbl  = s.fromLabel || '—';
    const toLbl    = s.toLabel || '—';
    const readyLbl = s.ready ? fmtShortDate(s.ready) : null;
    const leadObj = lead || s.lead || {};

    // Stable quote reference per mount: Q-YYYY-XXXX. Recomputing on every
    // render would let the user see the ref flicker as state updates roll in.
    const quoteRefRef = React.useRef(null);
    if (quoteRefRef.current == null) {
      quoteRefRef.current = `Q-${new Date().getFullYear()}-${
        Math.random().toString(36).slice(2, 6).toUpperCase()
      }`;
    }
    const quoteRef = quoteRefRef.current;

    // Status rotation: 4 stages, ~1.2s each. Rotates while requestSent is false.
    const STATUS_KEYS = [
      'q.norates.status.analyzing',
      'q.norates.status.negotiating',
      'q.norates.status.checking',
      'q.norates.status.finalizing',
    ];
    const [statusIdx, setStatusIdx] = useState(0);
    const [requestSent, setRequestSent] = useState(false);
    useEffect(() => {
      if (requestSent) return;
      const id = setInterval(() => {
        setStatusIdx(i => (i + 1) % STATUS_KEYS.length);
      }, 1200);
      return () => clearInterval(id);
    }, [requestSent]);
    // Hold the "processing" UI for ~4s for a premium feel, then resolve.
    useEffect(() => {
      const id = setTimeout(() => setRequestSent(true), 4000);
      return () => clearTimeout(id);
    }, []);

    const chips = [];
    if (modeName) chips.push(modeName);
    if (s.unit)   chips.push(s.unit);
    if (s.weight) chips.push(`${s.weight} kg`);
    if (readyLbl) chips.push(readyLbl);
    chips.push(t('q.norates.chip.custom'));

    return (
      <div ref={wrapRef} style={{ position: 'relative',
        background: 'rgba(255,255,255,0.62)',
        backdropFilter: 'blur(50px) saturate(1.6)', WebkitBackdropFilter: 'blur(50px) saturate(1.6)',
        border: '1px solid rgba(255,255,255,0.7)', borderRadius: 24,
        boxShadow: 'inset 0 1px 1px rgba(255,255,255,0.85), 0 24px 48px -12px rgba(16,24,40,0.18)',
        overflow: 'hidden' }}>
        <LiquidBorder radius={24} alpha={[0.9, 0.35]}/>

        {/* Header — back arrow, mode chip, route, edit + close. Hidden in
            compact mode for consumers that already wrap the card in their
            own header (e.g. the landing calculator's "Quote ready · ABG-…
            / Modify" strip). */}
        {!compact && (
          <div style={{ position: 'relative', padding: '14px 16px',
            borderBottom: '1px solid rgba(16,24,40,0.06)',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
            background: 'linear-gradient(180deg, rgba(255,255,255,0.55) 0%, rgba(255,255,255,0) 100%)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0, flex: 1 }}>
              {onEdit && (
                <button type="button" onClick={onEdit} aria-label={t('q.results.aria.edit')}
                  style={{ width: 30, height: 30, borderRadius: 9999, flexShrink: 0,
                    background: '#ffffff', border: '1px solid rgba(16,24,40,0.1)',
                    boxShadow: '0 1px 2px rgba(16,24,40,0.06), inset 0 1px 0 rgba(255,255,255,0.9)',
                    display: 'inline-grid', placeItems: 'center', cursor: 'pointer', color: '#475467' }}>
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none"
                    stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M15 18l-6-6 6-6"/>
                  </svg>
                </button>
              )}
              <span style={{ width: 30, height: 30, borderRadius: 8, flexShrink: 0,
                background: 'linear-gradient(180deg, #2E6AE8 0%, #1E57D6 60%, #1846B0 100%)',
                display: 'inline-grid', placeItems: 'center', color: '#fff',
                boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.35), 0 2px 6px rgba(30,87,214,0.35)' }}>
                {Icon && <Icon name={modeIcon} size={14}/>}
              </span>
              <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.2, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0,
                  fontSize: 14, fontWeight: 700, color: '#0B1220', letterSpacing: '-0.01em' }}>
                  <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                    minWidth: 0 }}>{fromLbl}</span>
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none"
                    stroke="#1E57D6" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"
                    style={{ flexShrink: 0 }}>
                    <path d="M5 12h14M13 6l6 6-6 6"/>
                  </svg>
                  <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                    minWidth: 0 }}>{toLbl}</span>
                </div>
                <span style={{ fontSize: 10.5, color: '#667085', marginTop: 2,
                  fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
                  letterSpacing: '0.02em',
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {chips.join(' · ')}
                </span>
              </div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
              {onEdit && (narrowHeader ? (
                <button type="button" onClick={onEdit} aria-label={t('q.results.aria.edit')}
                  title={t('q.results.aria.edit')}
                  style={{ width: 30, height: 30, borderRadius: 9999, flexShrink: 0,
                    background: 'rgba(255,255,255,0.85)',
                    border: '1px solid rgba(16,24,40,0.12)', cursor: 'pointer',
                    color: '#0B1220',
                    display: 'inline-grid', placeItems: 'center',
                    boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.9)' }}>
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none"
                    stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M12 20h9M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4z"/>
                  </svg>
                </button>
              ) : (
                <button type="button" onClick={onEdit}
                  style={{ padding: '6px 12px',
                    background: 'rgba(255,255,255,0.85)',
                    border: '1px solid rgba(16,24,40,0.12)', borderRadius: 9999, cursor: 'pointer',
                    color: '#0B1220', fontFamily: 'inherit', fontSize: 11.5, fontWeight: 600,
                    display: 'inline-flex', alignItems: 'center', gap: 6,
                    boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.9)' }}>
                  <svg width="11" height="11" viewBox="0 0 24 24" fill="none"
                    stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M12 20h9M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4z"/>
                  </svg>
                  {t('q.results.edit_search')}
                </button>
              ))}
              {onClose && (
                <button type="button" onClick={onClose}
                  style={{ padding: '6px 12px',
                    background: 'rgba(255,255,255,0.7)',
                    border: '1px solid rgba(16,24,40,0.1)', borderRadius: 9999, cursor: 'pointer',
                    color: '#475467', fontFamily: 'inherit', fontSize: 11.5, fontWeight: 600 }}>
                  {t('common.close')}
                </button>
              )}
            </div>
          </div>
        )}

        {!compact && <StepDots step={6} t={t}/>}

        {/* Body */}
        <div style={{ position: 'relative', padding: '16px 18px 18px',
          display: 'flex', flexDirection: 'column', gap: 14 }}>

          {/* A. Identity + status row */}
          <div style={{ display: 'flex', alignItems: 'flex-start',
            justifyContent: 'space-between', gap: 14, flexWrap: 'wrap' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0, flex: 1 }}>
              <span style={{ position: 'relative', width: 52, height: 52, borderRadius: 14,
                background: 'linear-gradient(180deg, #EAF2FF 0%, #DDE9FF 100%)',
                border: '1px solid rgba(30,87,214,0.18)', flexShrink: 0,
                display: 'inline-grid', placeItems: 'center', color: '#1E57D6',
                boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.9), 0 4px 12px -4px rgba(30,87,214,0.25)',
                overflow: 'hidden' }}>
                {requestSent ? (
                  Icon && <Icon name="shieldCheck" size={24} style={{ color: '#12b76a' }}/>
                ) : (
                  <React.Fragment>
                    {Icon && <Icon name="sparkles" size={22} style={{ position: 'relative', zIndex: 2 }}/>}
                    <span aria-hidden style={{ position: 'absolute', inset: 0,
                      background: 'rgba(30,87,214,0.12)',
                      animation: 'nrg-pulse 1.6s ease-in-out infinite' }}/>
                  </React.Fragment>
                )}
              </span>
              <div style={{ minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8,
                  fontSize: 17, fontWeight: 800, color: '#0B1220',
                  letterSpacing: '-0.018em', lineHeight: 1.15 }}>
                  {t('q.norates.title')}
                  {!requestSent && (
                    <span aria-hidden style={{ position: 'relative',
                      width: 7, height: 7, flexShrink: 0 }}>
                      <span style={{ position: 'absolute', inset: 0, borderRadius: 9999,
                        background: '#1E57D6' }}/>
                      <span style={{ position: 'absolute', inset: -2, borderRadius: 9999,
                        background: 'rgba(30,87,214,0.45)',
                        animation: 'nrg-ping 1.4s cubic-bezier(0,0,0.2,1) infinite' }}/>
                    </span>
                  )}
                </div>
                <div style={{ height: 18, marginTop: 4, position: 'relative',
                  fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
                  letterSpacing: '0.01em' }}>
                  {requestSent ? (
                    <div style={{ fontSize: 12, fontWeight: 700, color: '#058F4D',
                      display: 'inline-flex', alignItems: 'center', gap: 6,
                      animation: 'nrg-fadein 320ms ease-out both' }}>
                      {Icon && <Icon name="check" size={12}/>}
                      {t('q.norates.subtitle.confirmed')}
                    </div>
                  ) : (
                    <div key={statusIdx} style={{ fontSize: 12, fontWeight: 700,
                      color: '#1E57D6', display: 'inline-flex', alignItems: 'center', gap: 6,
                      animation: 'nrg-rotate-in 380ms cubic-bezier(0.16,1,0.3,1) both' }}>
                      <span style={{ position: 'relative', width: 12, height: 12, flexShrink: 0 }}>
                        <span style={{ position: 'absolute', inset: 0, borderRadius: 9999,
                          border: '1.6px solid rgba(30,87,214,0.2)',
                          borderTopColor: '#1E57D6',
                          animation: 'nrg-spin 0.9s linear infinite' }}/>
                      </span>
                      {t(STATUS_KEYS[statusIdx])}
                    </div>
                  )}
                </div>
              </div>
            </div>

            <div style={{ textAlign: 'right', flexShrink: 0, minWidth: 132 }}>
              <div style={{ fontSize: 9.5, fontWeight: 700, color: '#98A2B3',
                letterSpacing: '0.12em', textTransform: 'uppercase',
                fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' }}>
                {t('q.norates.metadata.rate')}
              </div>
              {requestSent ? (
                <div style={{ marginTop: 4, fontSize: 22, fontWeight: 800,
                  color: '#0B1220', letterSpacing: '-0.02em', lineHeight: 1,
                  animation: 'nrg-fadein 380ms ease-out both' }}>
                  {t('q.norates.status.pending')}
                </div>
              ) : (
                <div style={{ marginTop: 6, height: 22, width: 132, marginLeft: 'auto',
                  borderRadius: 6, background: 'rgba(16,24,40,0.06)',
                  animation: 'nrg-shimmer 1.6s linear infinite',
                  backgroundImage: 'linear-gradient(90deg, rgba(16,24,40,0.06) 0%, rgba(16,24,40,0.12) 50%, rgba(16,24,40,0.06) 100%)',
                  backgroundSize: '200% 100%' }}/>
              )}
              <div style={{ marginTop: 6, fontFamily: 'JetBrains Mono, ui-monospace, Menlo, monospace',
                fontSize: 9.5, fontWeight: 700, color: '#98A2B3', letterSpacing: '0.04em' }}>
                {t('q.norates.ref')} · {quoteRef}
              </div>
            </div>
          </div>

          {/* B. Friendly explanatory card */}
          <div style={{ position: 'relative', overflow: 'hidden',
            borderRadius: 16, padding: '14px 16px',
            background: 'linear-gradient(135deg, rgba(234,242,255,0.85) 0%, rgba(255,255,255,0.7) 50%, rgba(234,238,255,0.85) 100%)',
            border: '1px solid rgba(30,87,214,0.16)',
            boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.9), 0 2px 12px -6px rgba(30,87,214,0.15)' }}>
            <div style={{ position: 'absolute', top: -40, right: -40, width: 140, height: 140,
              borderRadius: 9999, background: 'rgba(30,87,214,0.08)', filter: 'blur(36px)',
              pointerEvents: 'none' }}/>
            <div style={{ position: 'absolute', bottom: -40, left: -40, width: 140, height: 140,
              borderRadius: 9999, background: 'rgba(75,108,255,0.07)', filter: 'blur(36px)',
              pointerEvents: 'none' }}/>
            <div style={{ position: 'relative', display: 'flex',
              alignItems: 'center', gap: 14,
              flexDirection: wide ? 'row' : 'column',
              textAlign: wide ? 'left' : 'center' }}>
              <span style={{ width: 42, height: 42, borderRadius: 12, flexShrink: 0,
                background: '#fff', border: '1px solid rgba(30,87,214,0.18)',
                display: 'inline-grid', placeItems: 'center', color: '#1E57D6',
                boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.9), 0 2px 6px rgba(30,87,214,0.15)' }}>
                {Icon && <Icon name="sparkles" size={20}/>}
              </span>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 800, color: '#0B1220',
                  letterSpacing: '-0.012em', marginBottom: 3 }}>
                  {t('q.norates.message.title')}
                </div>
                <div style={{ fontSize: 12, color: '#475467', lineHeight: 1.5,
                  fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
                  letterSpacing: '0.005em', maxWidth: 540 }}>
                  {t('q.norates.message.body')}
                </div>
              </div>
            </div>
          </div>

          {/* C. Route visualization */}
          <div style={{ position: 'relative', overflow: 'hidden',
            padding: '14px 16px', borderRadius: 14,
            background: '#fff', border: '1px solid rgba(16,24,40,0.06)',
            boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.9), 0 2px 6px -2px rgba(16,24,40,0.04)',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
            <div aria-hidden style={{ position: 'absolute', top: 6, right: 8, opacity: 0.045,
              color: '#0B1220', pointerEvents: 'none' }}>
              {Icon && <Icon name={modeIcon} size={120}/>}
            </div>

            <div style={{ minWidth: 0, flex: '0 1 auto', maxWidth: '38%',
              display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 4,
              position: 'relative' }}>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4,
                fontSize: 9, fontWeight: 800, color: '#98A2B3', letterSpacing: '0.12em',
                textTransform: 'uppercase',
                fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' }}>
                {Icon && <Icon name="pin" size={10}/>}
                {t('q.norates.route.origin')}
              </div>
              <div style={{ fontSize: 14, fontWeight: 800, color: '#0B1220',
                letterSpacing: '-0.012em', lineHeight: 1.2,
                overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                maxWidth: '100%' }}>
                {fromLbl}
              </div>
              {s.fromPlace && s.fromPlace.country && (
                <div style={{ fontSize: 10, fontWeight: 600, color: '#667085',
                  background: 'rgba(247,249,252,0.8)', border: '1px solid rgba(16,24,40,0.06)',
                  padding: '2px 7px', borderRadius: 6 }}>
                  {s.fromPlace.country}
                </div>
              )}
            </div>

            <div style={{ flex: '1 1 auto', position: 'relative', minWidth: 60,
              display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <div style={{ position: 'absolute', left: 0, right: 0, top: '50%',
                height: 0, borderTop: '1.5px dashed rgba(16,24,40,0.18)', transform: 'translateY(-50%)' }}/>
              <span style={{ position: 'relative', width: 32, height: 32, borderRadius: 9999,
                background: '#fff', border: '1px solid rgba(30,87,214,0.22)',
                display: 'inline-grid', placeItems: 'center', color: '#1E57D6',
                boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.9), 0 4px 10px -4px rgba(30,87,214,0.3)' }}>
                {Icon && <Icon name={modeIcon} size={14}/>}
              </span>
            </div>

            <div style={{ minWidth: 0, flex: '0 1 auto', maxWidth: '38%',
              display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4,
              position: 'relative' }}>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4,
                fontSize: 9, fontWeight: 800, color: '#98A2B3', letterSpacing: '0.12em',
                textTransform: 'uppercase',
                fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' }}>
                {t('q.norates.route.destination')}
                {Icon && <Icon name="pin" size={10}/>}
              </div>
              <div style={{ fontSize: 14, fontWeight: 800, color: '#0B1220',
                letterSpacing: '-0.012em', lineHeight: 1.2, textAlign: 'right',
                overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                maxWidth: '100%' }}>
                {toLbl}
              </div>
              {s.toPlace && s.toPlace.country && (
                <div style={{ fontSize: 10, fontWeight: 600, color: '#667085',
                  background: 'rgba(247,249,252,0.8)', border: '1px solid rgba(16,24,40,0.06)',
                  padding: '2px 7px', borderRadius: 6 }}>
                  {s.toPlace.country}
                </div>
              )}
            </div>
          </div>

          {/* D. Metadata grid — 4 cols when wide, 2 cols when narrow.
              className + --nrg-metadata-cols CSS variable keep the dynamic
              count on mobile pages that ship a blanket grid-flatten rule. */}
          <div className="nrg-metadata-grid"
            style={{ display: 'grid',
              gridTemplateColumns: wide ? 'repeat(4, minmax(0, 1fr))' : 'repeat(2, minmax(0, 1fr))',
              '--nrg-metadata-cols': wide ? 4 : 2,
              gap: 8 }}>
            {[
              { icon: 'clock',    label: t('q.norates.metadata.transit'), value: null,                                placeholder: true },
              { icon: 'shield',   label: t('q.norates.metadata.service'), value: t('q.norates.metadata.priority') },
              { icon: 'truck',    label: t('q.norates.metadata.mode'),    value: t('q.norates.metadata.multimodal') },
              { icon: 'sparkles', label: t('q.norates.metadata.rate'),    value: t('q.norates.metadata.custom') },
            ].map((cell, i) => (
              <div key={i} style={{ background: 'rgba(247,249,252,0.7)',
                border: '1px solid rgba(16,24,40,0.06)', borderRadius: 12,
                padding: '8px 10px', minWidth: 0 }}>
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5,
                  fontSize: 9, fontWeight: 800, color: '#98A2B3', letterSpacing: '0.1em',
                  textTransform: 'uppercase', marginBottom: 4,
                  fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' }}>
                  {Icon && <Icon name={cell.icon} size={10}/>}
                  {cell.label}
                </div>
                {cell.placeholder ? (
                  <div style={{ width: 36, height: 12, borderRadius: 4,
                    background: 'rgba(16,24,40,0.08)',
                    animation: 'nrg-shimmer 1.6s linear infinite',
                    backgroundImage: 'linear-gradient(90deg, rgba(16,24,40,0.06) 0%, rgba(16,24,40,0.14) 50%, rgba(16,24,40,0.06) 100%)',
                    backgroundSize: '200% 100%' }}/>
                ) : (
                  <div style={{ fontSize: 12.5, fontWeight: 800, color: '#0B1220',
                    letterSpacing: '-0.005em' }}>{cell.value}</div>
                )}
              </div>
            ))}
          </div>

          {/* E. Contact details (only if at least one field is present) */}
          {(leadObj.name || leadObj.email || leadObj.phone || leadObj.company) && (
            <div style={{ borderRadius: 12, overflow: 'hidden',
              border: '1px solid rgba(16,24,40,0.06)',
              background: 'rgba(247,249,252,0.5)' }}>
              <div style={{ padding: '8px 12px',
                borderBottom: '1px solid rgba(16,24,40,0.06)',
                background: 'rgba(255,255,255,0.7)',
                display: 'inline-flex', alignItems: 'center', gap: 6, width: '100%' }}>
                {Icon && <Icon name="users" size={11} style={{ color: '#98A2B3' }}/>}
                <span style={{ fontSize: 9.5, fontWeight: 800, color: '#667085',
                  letterSpacing: '0.1em', textTransform: 'uppercase',
                  fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' }}>
                  {t('q.norates.contact.title')}
                </span>
              </div>
              <div className="nrg-contact-grid"
                style={{ padding: '10px 12px',
                  display: 'grid',
                  gridTemplateColumns: wide ? 'repeat(2, minmax(0, 1fr))' : '1fr',
                  '--nrg-contact-cols': wide ? 2 : 1,
                  gap: '8px 16px' }}>
                {leadObj.name    && <ContactRow icon="users"     text={leadObj.name}/>}
                {leadObj.email   && <ContactRow icon="docs"      text={leadObj.email} mono/>}
                {leadObj.phone   && <ContactRow icon="phone"     text={leadObj.phone} mono/>}
                {leadObj.company && <ContactRow icon="warehouse" text={leadObj.company}/>}
              </div>
            </div>
          )}

          {/* F. Footer — pre-success progress vs success card */}
          {requestSent ? (
            <div style={{ display: 'flex', flexDirection: wide ? 'row' : 'column',
              gap: 10, alignItems: 'stretch',
              animation: 'nrg-fadein 380ms ease-out both' }}>
              <div style={{ flex: 1, minWidth: 0,
                padding: '12px 14px', borderRadius: 14,
                background: 'linear-gradient(180deg, rgba(220,252,231,0.85) 0%, rgba(240,253,244,0.85) 100%)',
                border: '1px solid rgba(18,183,106,0.3)',
                display: 'flex', alignItems: 'center', gap: 12,
                boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.9)' }}>
                <span style={{ width: 32, height: 32, borderRadius: 9999, flexShrink: 0,
                  background: 'linear-gradient(180deg, #18B66B 0%, #058F4D 100%)',
                  color: '#fff', display: 'inline-grid', placeItems: 'center',
                  boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.35), 0 2px 6px rgba(18,183,106,0.35)' }}>
                  {Icon && <Icon name="check" size={14}/>}
                </span>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 800, color: '#04532D',
                    letterSpacing: '-0.005em' }}>
                    {t('q.norates.success')}
                  </div>
                  <div style={{ fontSize: 10.5, color: '#067A47', marginTop: 2,
                    fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
                    letterSpacing: '0.01em' }}>
                    {t('q.norates.ref')}: {quoteRef} · {t('q.norates.expert_assigned')}
                  </div>
                </div>
              </div>
              {onChangeService && (
                <button type="button" onClick={onChangeService}
                  style={{ padding: '12px 18px',
                    background: 'linear-gradient(180deg, #2E6AE8 0%, #1E57D6 60%, #1846B0 100%)',
                    color: '#fff', border: 0, borderRadius: 14,
                    fontFamily: 'inherit', fontSize: 13, fontWeight: 700,
                    cursor: 'pointer', whiteSpace: 'nowrap',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                    boxShadow: 'inset 0 1px 1px rgba(255,255,255,0.35), 0 12px 24px -8px rgba(30,87,214,0.5)' }}>
                  {t('q.norates.button.new_search')}
                  {Icon && <Icon name="arrowRight" size={12}/>}
                </button>
              )}
            </div>
          ) : (
            <div style={{ padding: '12px 14px', borderRadius: 14,
              background: 'rgba(234,242,255,0.55)',
              border: '1px solid rgba(30,87,214,0.18)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span aria-hidden style={{ position: 'relative', width: 8, height: 8, flexShrink: 0 }}>
                  <span style={{ position: 'absolute', inset: 0, borderRadius: 9999,
                    background: '#1E57D6' }}/>
                  <span style={{ position: 'absolute', inset: -3, borderRadius: 9999,
                    background: 'rgba(30,87,214,0.4)',
                    animation: 'nrg-ping 1.4s cubic-bezier(0,0,0.2,1) infinite' }}/>
                </span>
                <div style={{ fontSize: 11.5, fontWeight: 600, color: '#1E3A8A',
                  fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
                  letterSpacing: '0.005em', lineHeight: 1.4 }}>
                  {t('q.norates.connecting')}
                </div>
              </div>
              <div style={{ marginTop: 10, height: 4, borderRadius: 9999,
                background: 'rgba(30,87,214,0.15)', overflow: 'hidden' }}>
                <div style={{ height: '100%', width: '100%',
                  background: 'linear-gradient(90deg, #2E6AE8 0%, #1E57D6 100%)',
                  transformOrigin: 'left center',
                  animation: 'nrg-progress 4s cubic-bezier(0.4,0,0.2,1) forwards' }}/>
              </div>
            </div>
          )}
        </div>

        {/* Footer trust row */}
        <div style={{ position: 'relative', padding: '10px 18px',
          borderTop: '1px solid rgba(16,24,40,0.06)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
          flexWrap: 'wrap',
          background: 'linear-gradient(0deg, rgba(255,255,255,0.55) 0%, rgba(255,255,255,0) 100%)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10,
            fontSize: 10.5, color: '#667085' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
              {Icon && <Icon name="check" size={11} style={{ color: '#12b76a' }}/>}
              {t('q.results.footer.allin')}
            </span>
            <span style={{ width: 1, height: 10, background: 'rgba(16,24,40,0.1)' }}/>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
              {Icon && <Icon name="lock" size={11} style={{ color: '#1E57D6' }}/>}
              {t('common.private')}
            </span>
            <span style={{ width: 1, height: 10, background: 'rgba(16,24,40,0.1)' }}/>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5,
              fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
              letterSpacing: '0.06em' }}>
              {Icon && <Icon name="shield" size={11} style={{ color: '#1E57D6' }}/>}
              SOC 2 · C-TPAT · NVOCC
            </span>
          </div>
        </div>

        <style>{`
          @keyframes nrg-pulse {
            0%, 100% { opacity: 0.35; }
            50%      { opacity: 0.85; }
          }
          @keyframes nrg-ping {
            0%   { transform: scale(1);   opacity: 0.6; }
            75%, 100% { transform: scale(2.2); opacity: 0; }
          }
          @keyframes nrg-rotate-in {
            from { opacity: 0; transform: translateY(8px); }
            to   { opacity: 1; transform: translateY(0); }
          }
          @keyframes nrg-fadein {
            from { opacity: 0; transform: translateY(4px); }
            to   { opacity: 1; transform: translateY(0); }
          }
          @keyframes nrg-shimmer {
            from { background-position: 200% 0; }
            to   { background-position: -200% 0; }
          }
          @keyframes nrg-progress {
            from { transform: scaleX(0); }
            to   { transform: scaleX(1); }
          }
          @keyframes nrg-spin {
            to { transform: rotate(360deg); }
          }
        `}</style>
      </div>
    );
  }

  // ────────────────────────────────────────────────────────────────────────
  // Exports
  // ────────────────────────────────────────────────────────────────────────

  window.RichRateCard = RichRateCard;
  window.NoRatesGlass = NoRatesGlass;
  window.__abgsRateHelpers = {
    rateTotalOf,
    rateTransitDays,
    collectBreakdown,
    buildRateOffersForFirestore,
    fmtMoney,
    fmtDate,
    fmtShortDate,
    titleCase,
    carrierBrand,
    resolveCarrierLogo,
    useWalioCarriers,
    loadWalioCarriers,
    extractIataCode,
    // Lets consumers reach into the same i18n surface the card uses,
    // so they can localize their own surrounding UI (e.g. landing's
    // urgency strip, success block) against the same lang detection.
    useRateT,
    fallbackT,
    PickupCarrierTag,
    QuickStat,
    SpecPanel,
    SpecRow,
  };
})();
