// =============================================
// Flacenter v3 — Modals + App
// =============================================

const { useState: useStateM, useEffect: useEffectM, useRef: useRefM, useMemo: useMemoM } = React;

// ---------- Car detail modal ----------
function CarDetailModal({ car, t, onClose, onOpenApply }) {
  const [idx, setIdx] = useStateM(0);
  const thumbStripRef = useRefM(null);
  useEffectM(() => {
    setIdx(0);
    const esc = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', esc);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', esc);
      document.body.style.overflow = '';
    };
  }, [car, onClose]);

  if (!car) return null;

  const d = t.detail || {};
  const photos = (car.photos || []).filter(Boolean);
  const activePhoto = photos[idx] || photos[0] || '';
  const market = car.marketcheckData || {};
  const pricing = market.pricing || {};
  const mpg = market.mpg || {};
  const engineDetails = market.engineDetails || {};
  const warranty = market.warranty || {};
  const rating = market.rating || {};
  const features = Array.isArray(car.features) ? car.features.filter(Boolean) : [];
  const safety = Array.isArray(car.safetyFeatures) ? car.safetyFeatures.filter(Boolean) : [];
  const installedOptions = Array.isArray(market.installedOptions) ? market.installedOptions : [];
  const wheelDetails = Array.isArray(market.wheelAndTireDetails) ? market.wheelAndTireDetails : [];
  const infotainment = Array.isArray(market.infotainmentHighlights) ? market.infotainmentHighlights : [];
  const bodyLabel = t.inv[car.body] || car.body;
  const cylinders = car.cylinders || engineDetails.cylinders;
  const horsepower = engineDetails.horsepower;
  const cash = car.cashPrice || car.price;
  const finance = car.financePrice || Math.round((car.price || 0) * 1.13);
  const monthly = Math.round((finance || cash || 0) / 60 * 1.05);
  const priceText = (value) => Number(value) > 0 ? `$${fmt(Math.round(Number(value)))}` : (d.askPrice || 'Ask for price');
  const numberText = (value) => Number(value) > 0 ? fmt(Number(value)) : '';
  const present = (value) => value !== undefined && value !== null && value !== '';
  const textKey = (value) => String(value || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
  const cleanText = (value) => String(value || '')
    .replace(/\s+/g, ' ')
    .replace(/\s+-\s+location:\s*(front|rear|all).*$/i, '')
    .replace(/\s+-\s+number of months subscription included.*$/i, '')
    .trim();
  const optionLabel = (option) => {
    if (!option) return '';
    if (typeof option === 'string') return cleanText(option);
    const name = [option.code, option.name].filter(Boolean).join(' - ') || option.type;
    const price = Number(option.msrp) > 0 ? ` ${priceText(option.msrp)}` : '';
    return cleanText(`${name || ''}${price}`);
  };
  const warrantyText = (entry) => {
    if (!entry) return '';
    const years = entry.duration ? `${Math.round(Number(entry.duration) / 12)} yr` : '';
    const miles = entry.distance ? `${fmt(Number(entry.distance))} mi` : '';
    return [years, miles].filter(Boolean).join(' / ');
  };
  const mpgText = (entry = {}) => {
    const values = [
      entry.city ? `${entry.city} city` : '',
      entry.highway ? `${entry.highway} hwy` : '',
      entry.combined ? `${entry.combined} combined` : ''
    ].filter(Boolean);
    return values.join(' / ');
  };

  const noisePatterns = [
    /\bfloor\s+(mat|mats|liner|liners)\b/i,
    /head restraints?/i,
    /seat belts?/i,
    /airbags?/i,
    /disc brakes?/i,
    /power steering/i,
    /isofix|latch/i,
    /test revision|standard-/i,
    /headlights-(good|poor)/i,
    /location:\s*(front|rear)/i,
    /tire (width|profile|speed rating)/i,
    /rpm for|maximum torque|co2 level/i,
    /wheelbase|external dimensions/i,
    /months of subscription/i,
    /audio system - radio/i,
    /steering wheel - (height|telescopic)/i,
    /suspension - wheel dependence/i
  ];
  const smartList = (items, limit = 99) => {
    const seen = new Set();
    return items
      .map(cleanText)
      .filter(Boolean)
      .filter((item) => !noisePatterns.some((pattern) => pattern.test(item)))
      .filter((item) => {
        const key = textKey(item);
        if (!key || seen.has(key)) return false;
        seen.add(key);
        return true;
      })
      .slice(0, limit);
  };
  const takeMatches = (items, pattern, limit, used = new Set()) => {
    const results = [];
    smartList(items).forEach((item) => {
      const key = textKey(item);
      if (results.length >= limit || used.has(key) || !pattern.test(item)) return;
      used.add(key);
      results.push(item);
    });
    return results;
  };
  const takePriorityMatches = (items, patterns, limit, used = new Set()) => {
    const source = smartList(items);
    const results = [];
    patterns.forEach((pattern) => {
      source.forEach((item) => {
        const key = textKey(item);
        if (results.length >= limit || used.has(key) || !pattern.test(item)) return;
        used.add(key);
        results.push(item);
      });
    });
    return results;
  };

  const installedOptionLabels = smartList(installedOptions.map(optionLabel), 12);
  const featureSources = smartList([
    ...installedOptionLabels,
    ...features,
    ...infotainment,
    ...wheelDetails
  ]);
  const safetySources = smartList([...safety, ...features]);
  const activeSafetyPatterns = [
    /blind spot|blind/i,
    /lane keep|lane/i,
    /anti collision|collision avoidance|collision system/i,
    /cross traffic/i,
    /adaptive cruise/i,
    /rear parking|parking assistance|parking distance|parking device|360 view|camera/i,
    /brake assist|automatic braking|front crash prevention|front crash prevent/i,
    /stability|traction/i,
    /hill holder|hill assist/i,
    /tire pressure|low tire pressure/i,
    /driver pattern|driver monitor/i,
    /intelligent speed/i,
    /autonomous drive/i
  ];
  const isActiveSafetyFeature = (item) => (
    activeSafetyPatterns.some((pattern) => pattern.test(item)) && !/telematics|breakdown/i.test(item)
  );
  const usedFeatureKeys = new Set();
  const comfortItems = takeMatches(featureSources, /heated|seat|leather|liftgate|keyless|smart|remote|climate|hvac|mirror|3rd row|third row|cargo|puddle|power closing/i, 6, usedFeatureKeys);
  const techPriorityItems = takePriorityMatches(featureSources, [
    /apple carplay/i,
    /android auto/i,
    /phone integration/i,
    /navigation/i,
    /bluetooth/i,
    /touch screen|screen/i,
    /wireless charging|wireless/i,
    /usb/i
  ], 6, usedFeatureKeys);
  const techItems = smartList([
    ...techPriorityItems,
    ...takeMatches(featureSources, /carplay|android|bluetooth|navigation|speaker|audio|satellite|touch|screen|voice|wireless|usb|telematics|traffic|phone integration|infotainment/i, 6, usedFeatureKeys)
  ], 6);
  const activeSafetyItems = takePriorityMatches(safetySources, activeSafetyPatterns, 30)
    .filter(isActiveSafetyFeature);
  const safetyItems = activeSafetyItems;
  const drivingItems = takeMatches(featureSources, /engine|transmission|drivetrain|wheel|tire|mpg|horsepower|torque|awd|fwd|rwd|premium wheels|upgraded wheel|upgraded tire/i, 5, usedFeatureKeys);
  const generalItems = smartList([...installedOptionLabels, ...features], 8).filter((item) => !usedFeatureKeys.has(textKey(item))).slice(0, 5);
  const readyItems = smartList([
    car.inspected ? (d.inspected || '170 point inspection') : '',
    d.cleanTitle || 'Title verified',
    car.carfaxUrl ? (d.carfaxIncluded || 'Vehicle history available') : '',
    ...features.filter((item) => /service|serviced|new tire|tires|oil|filter|detail|detailed|ready|recondition|inspected|revis|higien/i.test(item))
  ], 5);

  const featureGroups = [
    { key: 'comfort', title: d.comfort || 'Comfort', items: comfortItems.length ? comfortItems : generalItems },
    { key: 'tech', title: d.technology || 'Technology', items: techItems },
    { key: 'safety', title: d.safety || 'Safety', items: safetyItems.length ? safetyItems : smartList([d.cleanTitle, car.carfaxUrl ? d.carfaxIncluded : '', car.inspected ? d.inspected : ''], 3) },
    { key: 'drive', title: d.driving || 'Driving', items: drivingItems }
  ].filter((group) => group.items.length);

  const featureFallback = smartList([
    car.engine,
    car.trans,
    car.drive,
    car.fuel,
    car.exteriorColor,
    car.interiorColor,
    cylinders ? `${cylinders} ${d.cylindersShort || 'cyl'}` : '',
    horsepower ? `${horsepower} hp` : ''
  ], 6);
  const benefitItems = smartList([
    ...techItems,
    ...comfortItems,
    ...drivingItems,
    ...generalItems,
    ...installedOptionLabels,
    ...features,
    ...infotainment,
    ...wheelDetails,
    ...featureFallback
  ], 80).filter((item) => !isActiveSafetyFeature(item));
  const specItems = [
    [d.year || t.inv.year, car.year],
    [d.mileage || t.inv.miles, numberText(car.miles) ? `${numberText(car.miles)} mi` : ''],
    [d.body || t.inv.body, bodyLabel],
    [d.trim || 'Trim', car.trim],
    [d.transmission || t.inv.trans, car.trans],
    [d.drivetrain || t.inv.drive, car.drive],
    [d.fuel || t.inv.fuel, car.fuel],
    [d.engine || 'Engine', car.engine || engineDetails.description],
    [d.cylinders || 'Cylinders', cylinders],
    [d.horsepower || 'Horsepower', horsepower ? `${horsepower} hp` : ''],
    [d.doors || 'Doors', car.doors],
    [d.exterior || 'Exterior', car.exteriorColor],
    [d.interior || 'Interior', car.interiorColor],
    [d.vin || 'VIN', car.vin],
    [d.stock || t.inv.stock, car.stock]
  ].filter(([, value]) => present(value));
  const marketFacts = [
    [d.version || 'Version', market.version],
    [d.mpg || 'MPG', mpgText(mpg)],
    [d.msrp || 'MSRP', pricing.msrp ? priceText(pricing.msrp) : ''],
    [d.seating || 'Seating', market.seatingCapacity],
    [d.warranty || 'Powertrain warranty', warrantyText(warranty.powertrain)],
    [d.safetyRating || 'Safety rating', rating.safety?.overall ? `${rating.safety.overall} / 5` : '']
  ].filter(([, value]) => present(value));
  const story = car.description || `${car.fullName} is available now at Florida Auto Center in Orlando. Review the essentials, confirm availability, and schedule a test drive with our team.`;
  const photoCount = photos.length;
  const trackVehicleAction = (eventName, extra = {}) => {
    window.FlacenterTracking?.track?.(eventName, {
      item_id: car.slug || car.id,
      vehicle_id: car.vehicleId,
      item_name: car.fullName,
      item_brand: car.make,
      item_category: car.body,
      price: cash,
      currency: 'USD',
      ...extra
    });
  };
  const clampPhotoIndex = (value) => photoCount ? (value + photoCount) % photoCount : 0;
  const scrollActiveThumbIntoView = (photoIndex) => {
    const strip = thumbStripRef.current;
    const target = strip?.querySelector(`[data-photo-index="${photoIndex}"]`);
    if (target) target.scrollIntoView({ behavior: 'smooth', inline: 'nearest', block: 'nearest' });
  };
  const thumbScrollStep = () => {
    const strip = thumbStripRef.current;
    const firstThumb = strip?.querySelector('.vehicle-thumb');
    if (!strip || !firstThumb) return 420;
    const styles = window.getComputedStyle(strip);
    const gap = parseFloat(styles.columnGap || styles.gap || '10') || 10;
    return (firstThumb.offsetWidth + gap) * 4;
  };
  const scrollThumbStrip = (direction) => {
    const strip = thumbStripRef.current;
    if (!strip) return;
    strip.scrollBy({ left: thumbScrollStep() * direction, behavior: 'smooth' });
  };
  const showPhoto = (nextIndex) => {
    const next = clampPhotoIndex(nextIndex);
    setIdx(next);
    trackVehicleAction('vehicle_photo_view', { photo_index: next + 1, photo_count: photoCount });
    window.setTimeout(() => scrollActiveThumbIntoView(next), 0);
  };
  const selectThumb = (nextIndex, e) => {
    setIdx(nextIndex);
    trackVehicleAction('vehicle_photo_view', { photo_index: nextIndex + 1, photo_count: photoCount });
    const strip = thumbStripRef.current;
    const clicked = e.currentTarget;
    if (!strip || !clicked) return;
    const stripRect = strip.getBoundingClientRect();
    const visibleThumbs = Array.from(strip.querySelectorAll('.vehicle-thumb')).filter((thumb) => {
      const rect = thumb.getBoundingClientRect();
      return rect.right > stripRect.left + 1 && rect.left < stripRect.right - 1;
    });
    const firstVisible = visibleThumbs[0];
    const lastVisible = visibleThumbs[visibleThumbs.length - 1];
    if (clicked === lastVisible && nextIndex < photoCount - 1) scrollThumbStrip(1);
    if (clicked === firstVisible && nextIndex > 0) scrollThumbStrip(-1);
  };

  return (
    <div className="modal-bg vehicle-modal-bg" onClick={onClose}>
      <div className="modal vehicle-modal" onClick={e=>e.stopPropagation()} role="dialog" aria-modal="true" aria-label={car.fullName}>
        <button className="modal-close" onClick={onClose}><Icon.Close /></button>

        <div className="vehicle-modal-hero">
          <section className="vehicle-visual-panel">
            <div className="vehicle-main-media">
              {activePhoto && <img src={activePhoto} alt={car.fullName} onError={(e)=>{e.currentTarget.style.display='none'; e.currentTarget.parentElement.classList.add('fallback-img');}} />}
              {photoCount > 1 && (
                <>
                  <button className="vehicle-gallery-nav prev" type="button" aria-label="Previous photo" onClick={()=>showPhoto(idx - 1)}>
                    <Icon.Arrow />
                  </button>
                  <button className="vehicle-gallery-nav next" type="button" aria-label="Next photo" onClick={()=>showPhoto(idx + 1)}>
                    <Icon.Arrow />
                  </button>
                </>
              )}
              <div className="vehicle-media-top">
                <span>{photos.length ? `${idx + 1} / ${photos.length}` : d.photoComing || 'Photo coming soon'}</span>
                {car.carfaxUrl && <a href={car.carfaxUrl} target="_blank" rel="noopener noreferrer" onClick={(e)=>{e.stopPropagation(); trackVehicleAction('carfax_click');}}><Icon.Shield style={{width:14, height:14}} /> CARFAX</a>}
              </div>
            </div>
            {photos.length > 1 && (
              <div
                ref={thumbStripRef}
                className="vehicle-thumb-strip"
                onWheel={(e) => {
                  if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) {
                    e.currentTarget.scrollLeft += e.deltaY;
                    e.preventDefault();
                  }
                }}
              >
                {photos.map((p, i) => (
                  <button key={p + i} data-photo-index={i} className={'vehicle-thumb' + (i === idx ? ' active' : '')} onClick={(e)=>selectThumb(i, e)}>
                    <img src={p} alt={`${car.fullName} photo ${i + 1}`} />
                  </button>
                ))}
              </div>
            )}
          </section>

          <aside className="vehicle-deal-panel">
            <div className="vehicle-title-block">
              <div className="vehicle-kicker">
                <span>{car.make}</span>
                <span>{bodyLabel}</span>
                {car.condition && <span>{car.condition}</span>}
              </div>
              <h3>{car.fullName}</h3>
              <div className="vehicle-subline">
                {numberText(car.miles) && <span>{numberText(car.miles)} mi</span>}
                {car.vin && <span>VIN {car.vin}</span>}
                {car.stock && <span>{d.stock || 'Stock'} {car.stock}</span>}
              </div>
            </div>

            <div className="vehicle-price-panel">
              <div className="vehicle-price-main">
                <span>{t.inv.cash}</span>
                <strong>{priceText(cash)}</strong>
              </div>
              <div className="vehicle-price-side">
                <span>{t.inv.finance}</span>
                <strong>{priceText(finance)}</strong>
              </div>
              {monthly > 0 && <div className="vehicle-monthly">{priceText(monthly)}{t.inv.perMonth} {d.estPayment || 'estimated'}</div>}
              <p>{t.inv.taxFee}</p>
            </div>

            <div className="vehicle-quick-grid">
              {[
                [d.engine || 'Engine', car.engine || engineDetails.description],
                [d.drivetrain || t.inv.drive, car.drive],
                [d.transmission || t.inv.trans, car.trans],
                [d.fuel || t.inv.fuel, car.fuel]
              ].filter(([, value]) => present(value)).map(([label, value]) => (
                <div key={label}>
                  <span>{label}</span>
                  <strong>{value}</strong>
                </div>
              ))}
            </div>

            <div className="vehicle-action-stack">
              <button className="btn btn-primary btn-lg btn-block" onClick={()=>onOpenApply(car)}>
                {t.inv.iWantIt} <Icon.Arrow />
              </button>
              <a className="btn btn-sms btn-block" href={smsHref(vehicleSmsMessage(car))}>
                <Icon.Message /> {t.inv.smsVehicle || 'Text about this vehicle'}
              </a>
              <a className="btn btn-green btn-block" href="https://w.app/flawebsite" target="_blank">
                <Icon.Wa /> {t.inv.whatsapp}
              </a>
              <a className="btn btn-ghost btn-block" href="tel:4078024670">
                <Icon.Phone /> (407) 802 4670
              </a>
            </div>

            <div className="vehicle-trust-row">
              {readyItems.slice(0, 3).map((item) => <span key={item}><Icon.Check /> {item}</span>)}
            </div>
          </aside>
        </div>

        <div className="vehicle-detail-body">
          <section className="vehicle-main-details">
            <div className="vehicle-section vehicle-story-card">
              <div className="vehicle-section-head">
                <span className="tag">{d.overviewEyebrow || 'Vehicle overview'}</span>
                <h4>{d.story || 'Why this vehicle is worth a look'}</h4>
              </div>
              <p>{story}</p>
              <div className="vehicle-highlight-row">
                {[
                  [d.cash || t.inv.cash, priceText(cash)],
                  [d.mileage || t.inv.miles, numberText(car.miles) ? `${numberText(car.miles)} mi` : ''],
                  [d.powertrain || 'Powertrain', [car.engine || engineDetails.description, car.drive].filter(Boolean).join(' / ')],
                  [d.history || 'History', car.carfaxUrl ? (t.inv.carfaxBadge || 'CARFAX available') : (d.askHistory || 'Ask for report')]
                ].filter(([, value]) => present(value)).map(([label, value]) => (
                  <div className="vehicle-highlight" key={label}>
                    <span>{label}</span>
                    <strong>{value}</strong>
                  </div>
                ))}
              </div>
            </div>

            <div className="vehicle-curated-grid">
              {featureGroups.map((group) => (
                <section className={`feature-category-card ${group.key}`} key={group.key}>
                  <div className="feature-category-head">
                    <span className="feature-card-icon"><Icon.Check /></span>
                    <h4>{group.title}</h4>
                  </div>
                  <div className="feature-card-list">
                    {group.items.slice(0, 6).map((item) => (
                      <div className="feature-row" key={item}><Icon.Check /> <span>{item}</span></div>
                    ))}
                  </div>
                </section>
              ))}
            </div>

            {benefitItems.length > 0 && (
              <div className="vehicle-section vehicle-benefits-card">
                <div className="vehicle-section-head compact">
                  <h4>{d.allBenefits || 'Benefits and equipment'}</h4>
                  <span>{benefitItems.length} {d.items || 'items'}</span>
                </div>
                <div className="vehicle-benefit-grid">
                  {benefitItems.map((item) => <span className="vehicle-benefit-pill" key={item}><Icon.Check /> {item}</span>)}
                </div>
              </div>
            )}

            {activeSafetyItems.length > 0 && (
              <div className="vehicle-section vehicle-active-safety-card">
                <div className="vehicle-section-head compact">
                  <h4>{d.activeSafety || 'Active safety'}</h4>
                  <span>{activeSafetyItems.length} {d.items || 'items'}</span>
                </div>
                <div className="vehicle-safety-grid">
                  {activeSafetyItems.map((item) => <div className="vehicle-safety-item" key={item}><Icon.Shield /> <span>{item}</span></div>)}
                </div>
              </div>
            )}

            {readyItems.length > 0 && (
              <div className="vehicle-section vehicle-ready-card">
                <div className="vehicle-section-head compact">
                  <h4>{d.readyRoad || 'Ready for the road'}</h4>
                  <span>{readyItems.length} {d.items || 'items'}</span>
                </div>
                <div className="vehicle-ready-row">
                  {readyItems.map((item) => <span key={item}><Icon.Check /> {item}</span>)}
                </div>
              </div>
            )}

            <div className="vehicle-section market-data-card">
              <div className="vehicle-section-head compact">
                <h4>{d.decodedSpecs || d.marketData || 'Decoded specs'}</h4>
                <span>{marketFacts.length ? (d.marketSource || 'VIN data') : (d.listingSource || 'Listing data')}</span>
              </div>
              {marketFacts.length > 0 ? (
                <div className="market-fact-grid compact">
                  {marketFacts.map(([label, value]) => (
                    <div className="market-fact" key={label}>
                      <span>{label}</span>
                      <strong>{value}</strong>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="vehicle-muted">{d.noMarketData || 'VIN decode data will appear here after this vehicle is decoded in the admin.'}</p>
              )}
            </div>

          </section>

          <aside className="vehicle-side-details">
            <div className="vehicle-section sticky-detail-card">
              <div className="vehicle-section-head compact">
                <h4>{d.specs || 'Specifications'}</h4>
              </div>
              <div className="vehicle-spec-list">
                {specItems.map(([label, value]) => (
                  <div className="vehicle-spec-row" key={label}>
                    <span>{label}</span>
                    <strong>{value}</strong>
                  </div>
                ))}
              </div>
            </div>

            <div className="vehicle-section vehicle-history-card">
              <div className="vehicle-section-head compact">
                <h4>{d.history || 'Vehicle history'}</h4>
              </div>
              <p>{car.carfaxUrl ? (d.carfaxCopy || 'Review the vehicle history report before you visit.') : (d.historyCopy || 'Ask our team for title, service, and inspection notes.')}</p>
              {car.carfaxUrl && (
                <a className="modal-carfax" href={car.carfaxUrl} target="_blank" rel="noopener noreferrer" onClick={()=>trackVehicleAction('carfax_click')}>
                  <span className="carfax-icon"><Icon.Shield style={{width:18, height:18}} /></span>
                  <span className="carfax-text">
                    <strong>{t.inv.carfaxFull}</strong>
                    <small>{d.carfaxLine || 'Independent vehicle history report'}</small>
                  </span>
                  <Icon.Arrow />
                </a>
              )}
            </div>

            <div className="vehicle-section vehicle-contact-card">
              <div className="vehicle-section-head compact">
                <h4>{d.contactTitle || 'Ready to see it?'}</h4>
              </div>
              <p>{d.contactCopy || 'Confirm availability, request a walkaround video, or schedule a test drive with our Orlando team.'}</p>
              <div className="vehicle-contact-actions">
                <a className="btn btn-sms btn-block" href={smsHref(vehicleSmsMessage(car))}><Icon.Message /> {t.inv.smsVehicle || 'Text about this vehicle'}</a>
                <a className="btn btn-green btn-block" href="https://w.app/flawebsite" target="_blank"><Icon.Wa /> WhatsApp</a>
                <button className="btn btn-primary btn-block" onClick={()=>onOpenApply(car)}>{d.apply || t.finance.cta}</button>
              </div>
              <div className="vehicle-location-line"><Icon.Pin /> 4509 Old Winter Garden Rd, Orlando, FL 32811</div>
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}

// ---------- Compare modal ----------
function CompareModal({ cars, t, onClose }) {
  useEffectM(() => {
    const esc = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', esc);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', esc);
      document.body.style.overflow = '';
    };
  }, [onClose]);
  if (!cars || cars.length === 0) return null;
  const specKeys = ['price','year','miles','trans','fuel','drive','body','inspected'];
  return (
    <div className="modal-bg" onClick={onClose}>
      <div className="cmp-modal" onClick={e=>e.stopPropagation()}>
        <button className="modal-close" onClick={onClose}><Icon.Close /></button>
        <h3>{t.compare.title}</h3>
        <div className="cmp-table" style={{'--cols': cars.length}}>
          <div className="row-head"></div>
          {cars.map(c => (
            <div className="car-head" key={c.id}>
              <img src={c.photos[0]} alt="" onError={(e)=>{e.currentTarget.style.display='none'; e.currentTarget.parentElement.classList.add('fallback-img');}} />
              <div className="nm">{c.name}</div>
            </div>
          ))}
          {specKeys.map((k, i) => (
            <React.Fragment key={k}>
              <div className="row-head">{t.compare.specs[i]}</div>
              {cars.map(c => {
                let v = c[k];
                if (k === 'price') v = '$' + fmt(c.price);
                if (k === 'miles') v = fmt(c.miles) + ' mi';
                if (k === 'body') v = t.inv[c.body] || c.body;
                return <div key={c.id + k}>{v}</div>;
              })}
            </React.Fragment>
          ))}
        </div>
        <div style={{marginTop:24, display:'flex', gap:10, justifyContent:'center', flexWrap:'wrap'}}>
          <a href={smsHref('Hi Florida Auto Center, I would like to discuss these vehicles.')} className="btn btn-sms"><Icon.Message /> SMS</a>
          <a href="tel:4078024670" className="btn btn-primary"><Icon.Phone /> Call to discuss</a>
          <a href="https://w.app/flawebsite" target="_blank" className="btn btn-green"><Icon.Wa /> WhatsApp</a>
        </div>
      </div>
    </div>
  );
}

// ---------- Apply form (multi-step) ----------
function ApplyModal({ t, onClose, prefilledCar }) {
  const [step, setStep] = useStateM(0);
  const [sending, setSending] = useStateM(false);
  const [error, setError] = useStateM('');
  const [data, setData] = useStateM({
    fullName: '', phone: '', email: '', preferredContact: 'SMS',
    lang: document.documentElement.lang || 'en', budget: '$15,000 / $20,000', timeline: 'This week', tradeIn: 'No',
    employer: '', income: '', housing: '',
    interestedIn: prefilledCar ? prefilledCar.fullName : ''
  });

  useEffectM(() => {
    const esc = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', esc);
    document.body.style.overflow = 'hidden';
    window.FlacenterTracking?.track?.('apply_modal_view', {
      form_id: 'preapproval_modal',
      vehicle_id: prefilledCar?.vehicleId,
      item_id: prefilledCar?.slug || prefilledCar?.id,
      content_name: prefilledCar?.fullName
    });
    return () => {
      document.removeEventListener('keydown', esc);
      document.body.style.overflow = '';
    };
  }, [onClose, prefilledCar]);

  const set = (k, v) => {
    setData(d => ({ ...d, [k]: v }));
    if (error) setError('');
  };
  const f = t.apply.fields;
  const vehiclePayload = prefilledCar ? {
    vehicleId: prefilledCar.vehicleId,
    vehicleSlug: prefilledCar.slug || prefilledCar.id,
    vehicleName: prefilledCar.fullName,
    vehiclePrice: prefilledCar.price
  } : {};

  const submitApplication = async () => {
    if (sending) return;
    if (!data.fullName || (data.preferredContact === 'Email' ? !data.email : !data.phone)) {
      setError(data.preferredContact === 'Email'
        ? (t.leadForm?.emailRequired || 'Please add your name and email.')
        : (t.leadForm?.errorRequired || 'Please add your name and phone.'));
      setStep(0);
      return;
    }

    setSending(true);
    setError('');

    try {
      if (!window.FlacenterApi?.submitLead) throw new Error('Lead API client unavailable');
      await window.FlacenterApi.submitLead({
        name: data.fullName,
        phone: data.phone,
        email: data.email,
        lang: data.lang,
        budget: data.budget,
        time: data.timeline,
        tradeIn: data.tradeIn,
        preferred: data.preferredContact || 'SMS',
        msg: [
          data.interestedIn ? `Interested in ${data.interestedIn}` : 'Pre approval application',
          data.employer ? `Employer: ${data.employer}` : '',
          data.income ? `Income: ${data.income}` : '',
          data.housing ? `Housing: ${data.housing}` : ''
        ].filter(Boolean).join('\n'),
        source: 'website-v3-application',
        formId: 'preapproval_modal',
        conversionEvent: 'apply_submit',
        vehicleId: prefilledCar?.vehicleId,
        payload: {
          ...vehiclePayload,
          interestedIn: data.interestedIn,
          employer: data.employer,
          income: data.income,
          housing: data.housing,
          applicationStep: 'complete'
        }
      });
      setStep(3);
    } catch (err) {
      setError(err.message || t.leadForm?.error || 'Could not send your request. Please call or WhatsApp us.');
    } finally {
      setSending(false);
    }
  };

  const next = () => {
    if (step === 0 && (!data.fullName || (data.preferredContact === 'Email' ? !data.email : !data.phone))) {
      setError(data.preferredContact === 'Email'
        ? (t.leadForm?.emailRequired || 'Please add your name and email.')
        : (t.leadForm?.errorRequired || 'Please add your name and phone.'));
      return;
    }
    if (step === 2) {
      submitApplication();
      return;
    }
    window.FlacenterTracking?.track?.('apply_step', {
      form_id: 'preapproval_modal',
      step: step + 1,
      next_step: step + 2,
      vehicle_id: prefilledCar?.vehicleId,
      item_id: prefilledCar?.slug || prefilledCar?.id
    });
    setStep(s => s + 1);
  };

  return (
    <div className="modal-bg" onClick={onClose}>
      <div style={{background:'white', borderRadius:18, width:'100%', maxWidth:640, maxHeight:'92vh', overflow:'auto', position:'relative', padding:36}} onClick={e=>e.stopPropagation()}>
        <button className="modal-close" onClick={onClose}><Icon.Close /></button>
        <span className="tag">{t.finance.eyebrow}</span>
        <h3 style={{fontSize:28, marginTop:8, fontWeight:700}}>{t.apply.title}</h3>
        <p style={{color:'var(--ink-soft)', marginTop:8}}>{t.apply.sub}</p>

        {prefilledCar && (
          <div style={{background:'var(--blue-soft)', padding:12, borderRadius:10, marginTop:18, display:'flex', gap:12, alignItems:'center'}}>
            <img src={prefilledCar.photos[0]} alt="" style={{width:56, height:42, objectFit:'cover', borderRadius:6}} />
            <div>
              <div style={{fontSize:12, color:'var(--muted)', fontWeight:600}}>Interested in</div>
              <div style={{fontWeight:700}}>{prefilledCar.fullName}</div>
            </div>
            <div style={{marginLeft:'auto', fontWeight:800, color:'var(--blue)'}}>${fmt(prefilledCar.price)}</div>
          </div>
        )}

        <div style={{display:'flex', gap:6, marginTop:24, marginBottom:28}}>
          {t.apply.steps.map((s, i) => (
            <div key={i} style={{flex:1}}>
              <div style={{height:4, background: i<=step?'var(--blue)':'var(--line)', borderRadius:2}}></div>
              <div style={{fontSize:11, fontWeight:600, marginTop:6, color: i<=step?'var(--ink)':'var(--muted)'}}>{String(i+1).padStart(2,'0')} · {s}</div>
            </div>
          ))}
        </div>

        {step === 0 && (
          <div style={{display:'grid', gap:14}}>
            <div>
              <label className="lbl">{f.fullName}</label>
              <input className="input" value={data.fullName} onChange={e=>set('fullName', e.target.value)} placeholder="Emily Johnson" />
            </div>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
              <div>
                <label className="lbl">{f.phone}</label>
                <input className="input" value={data.phone} onChange={e=>set('phone', e.target.value)} placeholder="(407) 555 1234" />
              </div>
              <div>
                <label className="lbl">{f.email}</label>
                <input className="input" value={data.email} onChange={e=>set('email', e.target.value)} placeholder="you@email.com" />
              </div>
            </div>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
              <div>
                <label className="lbl">{t.leadForm?.preferred || 'Preferred contact'}</label>
                <select className="select" value={data.preferredContact} onChange={e=>set('preferredContact', e.target.value)}>
                  <option value="SMS">{t.contactOptions?.sms || 'SMS'}</option>
                  <option value="Email">{t.contactOptions?.email || f.email}</option>
                  <option value="WhatsApp">{t.contactOptions?.whatsapp || 'WhatsApp'}</option>
                  <option value="Phone call">{t.contactOptions?.phone || f.phone}</option>
                </select>
              </div>
              <div>
                <label className="lbl">{f.lang}</label>
                <select className="select" value={data.lang} onChange={e=>set('lang', e.target.value)}>
                  <option value="en">English</option>
                  <option value="es">Español</option>
                  <option value="pt">Português</option>
                </select>
              </div>
            </div>
          </div>
        )}
        {step === 1 && (
          <div style={{display:'grid', gap:14}}>
            <div>
              <label className="lbl">{f.budget}</label>
              <select className="select" value={data.budget} onChange={e=>set('budget', e.target.value)}>
                <option>Under $10,000</option>
                <option>$10,000 / $15,000</option>
                <option>$15,000 / $20,000</option>
                <option>$20,000 / $30,000</option>
                <option>$30,000 and up</option>
              </select>
            </div>
            <div>
              <label className="lbl">{f.timeline}</label>
              <select className="select" value={data.timeline} onChange={e=>set('timeline', e.target.value)}>
                <option>This week</option>
                <option>This month</option>
                <option>Just exploring</option>
              </select>
            </div>
            <div>
              <label className="lbl">{f.tradeIn}</label>
              <select className="select" value={data.tradeIn} onChange={e=>set('tradeIn', e.target.value)}>
                <option>No</option>
                <option>Yes, paid off</option>
                <option>Yes, still paying</option>
              </select>
            </div>
          </div>
        )}
        {step === 2 && (
          <div style={{display:'grid', gap:14}}>
            <div>
              <label className="lbl">{f.employer}</label>
              <input className="input" value={data.employer} onChange={e=>set('employer', e.target.value)} placeholder="Disney, Orlando Health, ..." />
            </div>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
              <div>
                <label className="lbl">{f.income}</label>
                <input className="input" value={data.income} onChange={e=>set('income', e.target.value)} placeholder="$ / mo" />
              </div>
              <div>
                <label className="lbl">{f.housing}</label>
                <input className="input" value={data.housing} onChange={e=>set('housing', e.target.value)} placeholder="$ / mo" />
              </div>
            </div>
          </div>
        )}
        {step === 3 && (
          <div style={{textAlign:'center', padding:'24px 0'}}>
            <div style={{width:72, height:72, background:'var(--green-soft)', color:'var(--green)', borderRadius:'50%', display:'grid', placeItems:'center', margin:'0 auto 18px'}}>
              <Icon.Check style={{width:32, height:32}} />
            </div>
            <h3 style={{fontSize:26}}>{t.apply.done}</h3>
            <p style={{color:'var(--ink-soft)', marginTop:12, maxWidth:380, marginLeft:'auto', marginRight:'auto'}}>{t.apply.doneSub}</p>
            <div style={{display:'flex', gap:10, justifyContent:'center', marginTop:20, flexWrap:'wrap'}}>
              <a href={smsHref('Hi Florida Auto Center, I just submitted my pre approval.')} className="btn btn-sms"><Icon.Message /> SMS</a>
              <a href="tel:4078024670" className="btn btn-primary"><Icon.Phone /> (407) 802 4670</a>
              <a href="https://w.app/flawebsite" target="_blank" className="btn btn-green"><Icon.Wa /> WhatsApp</a>
            </div>
          </div>
        )}

        {error && <div className="form-error" style={{marginTop:18}}>{error}</div>}

        {step < 3 && (
          <div style={{display:'flex', justifyContent:'space-between', marginTop:28}}>
            <button className="btn btn-ghost" onClick={()=>step>0 ? setStep(s=>s-1) : onClose()} disabled={sending}>
              {step === 0 ? 'Cancel' : t.apply.back}
            </button>
            <button className="btn btn-primary" onClick={next} disabled={sending}>
              {sending ? (t.leadForm?.sending || 'Sending...') : (step === 2 ? t.apply.submit : t.apply.next)} {!sending && <Icon.Arrow />}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

// ============================================
// APP
// ============================================
function App() {
  const [lang, setLang] = useStateM(() => localStorage.getItem('flacenter.lang') || 'en');
  const [filter, setFilter] = useStateM({ make: '', body: '', maxPrice: 30000 });
  const [inventory, setInventory] = useStateM(() => window.INVENTORY || []);
  const [inventoryState, setInventoryState] = useStateM({ loading: true, source: 'mock', error: '' });
  const [compared, setCompared] = useStateM([]);
  const [openedCar, setOpenedCar] = useStateM(null);
  const [showCompare, setShowCompare] = useStateM(false);
  const [showApply, setShowApply] = useStateM(false);
  const [applyCar, setApplyCar] = useStateM(null);
  const invRef = useRefM(null);
  const leadRef = useRefM(null);

  useEffectM(() => {
    localStorage.setItem('flacenter.lang', lang);
    document.documentElement.lang = lang;
  }, [lang]);

  useEffectM(() => {
    let active = true;

    if (!window.FlacenterApi?.fetchInventory) {
      setInventoryState({ loading: false, source: 'mock', error: 'API client unavailable' });
      return () => { active = false; };
    }

    window.FlacenterApi.fetchInventory()
      .then(cars => {
        if (!active) return;
        if (cars.length > 0) {
          setInventory(cars);
          setInventoryState({ loading: false, source: 'api', error: '' });
        } else {
          setInventoryState({ loading: false, source: 'mock', error: 'No published vehicles returned by API' });
        }
      })
      .catch(error => {
        if (!active) return;
        console.warn('Inventory API unavailable, keeping preview inventory.', error);
        setInventoryState({ loading: false, source: 'mock', error: error.message || 'Inventory API unavailable' });
      });

    return () => { active = false; };
  }, []);

  const t = window.T[lang];
  const isInventoryPage = window.location.pathname.replace(/\/+$/, '') === '/inventory';
  const makes = useMemoM(() => {
    const list = [...new Set(inventory.map(car => car.make).filter(Boolean))].sort();
    return list.length ? list : (window.MAKES || []);
  }, [inventory]);

  const scrollTo = (ref) => {
    if (ref?.current) ref.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  const trackingVehiclePayload = (car) => ({
    item_id: car?.slug || car?.id,
    vehicle_id: car?.vehicleId,
    item_name: car?.fullName,
    item_brand: car?.make,
    item_category: car?.body,
    price: car?.price,
    currency: 'USD'
  });

  const openCarDetail = (car) => {
    window.FlacenterTracking?.track?.('view_item', trackingVehiclePayload(car));
    setOpenedCar(car);
  };

  const toggleCompare = (car) => {
    window.FlacenterTracking?.track?.('compare_vehicle', trackingVehiclePayload(car));
    setCompared(c => {
      if (c.some(x => x.id === car.id)) return c.filter(x => x.id !== car.id);
      if (c.length >= 3) return [...c.slice(1), car];
      return [...c, car];
    });
  };

  const openApplyForCar = (car) => {
    window.FlacenterTracking?.track?.('apply_start', {
      form_id: 'preapproval_modal',
      ...trackingVehiclePayload(car)
    });
    setApplyCar(car);
    setShowApply(true);
  };

  const openApplyEmpty = () => {
    window.FlacenterTracking?.track?.('apply_start', { form_id: 'preapproval_modal' });
    setApplyCar(null);
    setShowApply(true);
  };

  return (
    <>
      <CtaStrip t={t} />
      <Header lang={lang} setLang={setLang} t={t} openApply={openApplyEmpty} />
      <main className={isInventoryPage ? 'inventory-dedicated' : ''}>
        {isInventoryPage ? (
          <>
            <section className="section section-categories inventory-page-categories">
              <div className="wrap">
                <CategoryTiles t={t} inventory={inventory} setFilter={setFilter} scrollToInv={() => scrollTo(invRef)} />
              </div>
            </section>
            <InventorySection
              t={t} lang={lang}
              inventory={inventory}
              inventoryState={inventoryState}
              filter={filter} setFilter={setFilter}
              compared={compared} toggleCompare={toggleCompare}
              openCar={openCarDetail}
              openApplyForCar={openApplyForCar}
              scrollRef={invRef}
              isDedicated={true}
            />
          </>
        ) : (
          <>
            <Hero
              t={t}
              makes={makes}
              scrollToInv={() => scrollTo(invRef)}
              setFilter={setFilter}
              openApply={openApplyEmpty}
              scrollToLead={() => scrollTo(leadRef)}
            />
            <section className="section section-categories">
              <div className="wrap">
                <CategoryTiles t={t} inventory={inventory} setFilter={setFilter} scrollToInv={() => scrollTo(invRef)} />
              </div>
            </section>
            <InventorySection
              t={t} lang={lang}
              inventory={inventory}
              inventoryState={inventoryState}
              filter={filter} setFilter={setFilter}
              compared={compared} toggleCompare={toggleCompare}
              openCar={openCarDetail}
              openApplyForCar={openApplyForCar}
              scrollRef={invRef}
            />
            <LeadBanner t={t} openApply={openApplyEmpty} />
            <WhySection t={t} />
            <FinanceSection t={t} lang={lang} openApply={openApplyEmpty} />
            <TestimonialsSection t={t} />
            <LeadSection t={t} leadRef={leadRef} inventory={inventory} />
            <VisitSection t={t} />
          </>
        )}
      </main>
      <Footer t={t} />

      <a href="https://w.app/flawebsite" target="_blank" className="wa-fab">
        <span className="icn"><Icon.Wa /></span>
        <span>WhatsApp</span>
      </a>

      <div className="mobile-cta-bar">
        <a href={smsHref('Hi Florida Auto Center, I would like to start my pre approval.')} className="b sms">
          <Icon.Message /> SMS
        </a>
        <a href="tel:4078024670" className="b call">
          <Icon.Phone /> Call
        </a>
        <a href="https://w.app/flawebsite" target="_blank" className="b wa">
          <Icon.Wa /> WhatsApp
        </a>
        <button className="b apply" onClick={openApplyEmpty}>
          Apply
        </button>
      </div>

      {compared.length > 0 && (
        <div className="compare-bar">
          <span className="count">{compared.length}</span>
          <span>{t.compare.addMore}</span>
          <button className="go" disabled={compared.length < 2} onClick={()=>setShowCompare(true)}>
            {t.compare.ready}
          </button>
          <button className="clr" onClick={()=>setCompared([])}><Icon.Close /></button>
        </div>
      )}

      {openedCar && <CarDetailModal car={openedCar} t={t} onClose={()=>setOpenedCar(null)} onOpenApply={(car)=>{setOpenedCar(null); openApplyForCar(car);}} />}
      {showCompare && <CompareModal cars={compared} t={t} onClose={()=>setShowCompare(false)} />}
      {showApply && <ApplyModal t={t} onClose={()=>{setShowApply(false); setApplyCar(null);}} prefilledCar={applyCar} />}
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
