
// ── Price Estimator Page ────────────────────────────────────────────────────
//
// Pricing config — edit these values to update all estimates site-wide
const PRICING = {
  // Container sale prices (before tax)
  sale: {
    '20-new':  2500,
    '20-used': 2000,
    '40-new':  4500,
    '40-used': 3200, // default assumption
  },
  // Monthly rental rates
  rental: {
    '20-new':  120,
    '20-used': 100,
    '40-new':  145,
    '40-used': 110,
  },
  // Buyout: 50% of each month's payment credited toward purchase
  buyoutCreditRate: 0.50,
  // Delivery
  delivery: {
    flatFee: 250,       // base fee per one-way trip
    includedMiles: 45,  // miles included in the base fee
    perMile: 2.50,      // $ per additional mile one-way
    maxRadius: 150,     // miles
    hubZip: '98001',    // Auburn, WA — centroid of service area
    // Straight-line coords for hub ZIP (Auburn, WA)
    hubLat: 47.3073,
    hubLng: -122.2285,
  },
  // Sales tax
  taxRate: 0.10,
};

// Approximate lat/lng for major WA/OR/ID ZIP prefixes
// We use a simple lookup table for demo; real impl would use a geocoding API
const ZIP_COORDS = {
  // WA
  '980': [47.606, -122.332], // Seattle
  '981': [47.606, -122.332],
  '982': [47.253, -122.444], // Tacoma
  '983': [47.253, -122.444],
  '984': [47.253, -122.444],
  '985': [47.042, -122.900], // Olympia
  '986': [45.639, -122.660], // Vancouver WA
  '988': [46.596, -120.505], // Yakima
  '989': [47.658, -117.426], // Spokane
  '990': [47.658, -117.426],
  '991': [47.658, -117.426],
  '992': [47.658, -117.426],
  '993': [46.596, -120.505],
  '994': [46.730, -117.003], // Pullman
  // OR
  '970': [45.523, -122.676], // Portland
  '971': [45.523, -122.676],
  '972': [45.523, -122.676],
  '973': [44.942, -123.033], // Salem
  '974': [44.057, -123.095], // Eugene
  '975': [42.327, -122.875], // Medford
  '976': [42.327, -122.875],
  '977': [45.523, -122.676],
  '978': [44.057, -123.095],
  '979': [44.057, -123.095],
  // ID
  '832': [43.615, -116.202], // Boise
  '833': [43.615, -116.202],
  '834': [43.615, -116.202],
  '835': [46.416, -117.000], // Lewiston
  '836': [42.561, -114.460], // Twin Falls
  '837': [42.561, -114.460],
  '838': [47.678, -116.780], // Coeur d'Alene
};

function getDistance(lat1, lon1, lat2, lon2) {
  const R = 3958.8; // Earth radius in miles
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLon = (lon2 - lon1) * Math.PI / 180;
  const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
    Math.sin(dLon/2) * Math.sin(dLon/2);
  return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
}

function getApproxCoords(zip) {
  if (!zip || zip.length < 3) return null;
  return ZIP_COORDS[zip.substring(0, 3)] || null;
}

function estimateDistance(zip, hubZip = PRICING.delivery.hubZip) {
  if (!zip || zip.length < 3) return null;
  const coords = getApproxCoords(zip);
  const hubCoords = getApproxCoords(hubZip);
  if (!coords) return null;
  return Math.round(getDistance(
    hubCoords ? hubCoords[0] : PRICING.delivery.hubLat,
    hubCoords ? hubCoords[1] : PRICING.delivery.hubLng,
    coords[0],
    coords[1]
  ));
}

function normalizeTaxRateDecimal(value) {
  const numeric = Number(value);
  if (!Number.isFinite(numeric) || numeric < 0) return 0;
  return numeric > 1 ? numeric / 100 : numeric;
}

function calcDelivery(miles, isRental, maxRadius = PRICING.delivery.maxRadius) {
  if (miles === null) return null;
  if (miles > maxRadius) return 'out-of-range';
  const includedMiles = Math.max(0, Number(PRICING.delivery.includedMiles) || 0);
  const additionalMiles = Math.max(0, miles - includedMiles);
  const oneWay = PRICING.delivery.flatFee + (additionalMiles * PRICING.delivery.perMile);
  return isRental ? Math.round(oneWay * 2) : Math.round(oneWay); // rental includes pickup
}

// ── Estimator Component ─────────────────────────────────────────────────────
const EstimatorPage = ({ setCurrentPage }) => {
  const goContact = () => { setCurrentPage('contact'); window.scrollTo({ top: 0, behavior: 'smooth' }); };

  const [pricingLoadedAt, setPricingLoadedAt] = React.useState(0);
  const [mode, setMode] = React.useState('sale'); // 'sale' | 'rental'
  const [size, setSize] = React.useState('20');
  const [condition, setCondition] = React.useState('new');
  const [zip, setZip] = React.useState('');
  const [months, setMonths] = React.useState(12); // for rental buyout
  const [showBreakdown, setShowBreakdown] = React.useState(false);
  const [deliveryEstimate, setDeliveryEstimate] = React.useState({
    status: 'idle',
    provider: '',
    miles: null,
    maxRadius: PRICING.delivery.maxRadius,
    warning: '',
    outOfRange: false,
  });

  React.useEffect(() => {
    if (!SUPABASE_CONFIGURED) return undefined;
    let cancelled = false;

    (async () => {
      try {
        const pricing = await supa.getPricing();
        if (!pricing || cancelled) return;
        PRICING.sale['20-new'] = Number(pricing.sale_20_new || PRICING.sale['20-new']);
        PRICING.sale['20-used'] = Number(pricing.sale_20_used || PRICING.sale['20-used']);
        PRICING.sale['40-new'] = Number(pricing.sale_40_new || PRICING.sale['40-new']);
        PRICING.sale['40-used'] = Number(pricing.sale_40_used || PRICING.sale['40-used']);
        PRICING.rental['20-new'] = Number(pricing.rent_20_new || PRICING.rental['20-new']);
        PRICING.rental['20-used'] = Number(pricing.rent_20_used || PRICING.rental['20-used']);
        PRICING.rental['40-new'] = Number(pricing.rent_40_new || PRICING.rental['40-new']);
        PRICING.rental['40-used'] = Number(pricing.rent_40_used || PRICING.rental['40-used']);
        PRICING.delivery.flatFee = Number(pricing.delivery_flat || PRICING.delivery.flatFee);
        PRICING.delivery.includedMiles = Number(pricing.delivery_included_miles || PRICING.delivery.includedMiles);
        PRICING.delivery.perMile = Number(pricing.delivery_per_mile || PRICING.delivery.perMile);
        PRICING.delivery.maxRadius = Number(pricing.delivery_max_radius || PRICING.delivery.maxRadius);
        PRICING.delivery.hubZip = pricing.delivery_hub_zip || PRICING.delivery.hubZip;
        PRICING.taxRate = normalizeTaxRateDecimal(pricing.tax_rate || PRICING.taxRate);
        PRICING.buyoutCreditRate = Number(pricing.buyout_credit_rate || PRICING.buyoutCreditRate);
        setPricingLoadedAt(Date.now());
      } catch {}
    })();

    return () => { cancelled = true; };
  }, []);

  React.useEffect(() => {
    if (zip.length !== 5) {
      setDeliveryEstimate({
        status: 'idle',
        provider: '',
        miles: null,
        maxRadius: PRICING.delivery.maxRadius,
        warning: '',
        outOfRange: false,
      });
      return;
    }

    const fallbackMiles = estimateDistance(zip, PRICING.delivery.hubZip);
    const controller = new AbortController();

    setDeliveryEstimate(current => ({
      ...current,
      status: 'loading',
      provider: '',
      warning: '',
      miles: current.miles,
      maxRadius: current.maxRadius || PRICING.delivery.maxRadius,
      outOfRange: false,
    }));

    (async () => {
      try {
        const params = new URLSearchParams({
          zip,
        });
        const response = await fetch(`/api/delivery-distance?${params.toString()}`, {
          signal: controller.signal,
        });

        if (!response.ok) throw new Error('Distance lookup failed.');

        const payload = await response.json();
        setDeliveryEstimate({
          status: 'ready',
          provider: payload.provider || '',
          miles: typeof payload.miles === 'number' ? payload.miles : null,
          maxRadius: Number(payload.maxRadius || PRICING.delivery.maxRadius),
          warning: payload.warning || '',
          outOfRange: !!payload.outOfRange,
        });
      } catch (error) {
        if (controller.signal.aborted) return;
        setDeliveryEstimate({
          status: 'ready',
          provider: fallbackMiles !== null ? 'approximate' : '',
          miles: fallbackMiles,
          maxRadius: PRICING.delivery.maxRadius,
          warning: fallbackMiles !== null ? 'Using approximate distance right now.' : 'Unable to estimate delivery distance for this ZIP.',
          outOfRange: typeof fallbackMiles === 'number' ? fallbackMiles > PRICING.delivery.maxRadius : false,
        });
      }
    })();

    return () => controller.abort();
  }, [zip, pricingLoadedAt]);

  // Derived
  const containerKey = `${size}-${condition}`;
  const miles = deliveryEstimate.miles;
  const effectiveMaxRadius = deliveryEstimate.maxRadius || PRICING.delivery.maxRadius;
  const deliveryCost = calcDelivery(miles, mode === 'rental', effectiveMaxRadius);
  const validDelivery = typeof deliveryCost === 'number';
  const outOfRange = deliveryEstimate.outOfRange || deliveryCost === 'out-of-range';
  const taxRateDecimal = normalizeTaxRateDecimal(PRICING.taxRate);
  const taxPercentLabel = `${(taxRateDecimal * 100).toFixed(taxRateDecimal * 100 % 1 === 0 ? 0 : 2)}%`;

  // Sale calc
  const basePrice = PRICING.sale[containerKey] || 0;
  const deliveryForSale = validDelivery ? deliveryCost : 0;
  const saleSubtotal = basePrice + deliveryForSale;
  const taxAmount = Math.round(saleSubtotal * taxRateDecimal);
  const saleTotal = saleSubtotal + taxAmount;

  // Rental calc
  const monthlyRate = PRICING.rental[containerKey] || 0;
  const deliveryDeposit = validDelivery ? deliveryCost : 0; // rental delivery = round trip upfront
  const deliveryTaxAmount = Math.round(deliveryDeposit * taxRateDecimal);
  const totalPaidAfterMonths = monthlyRate * months + deliveryDeposit + deliveryTaxAmount;
  const buyoutCredit = Math.round(monthlyRate * PRICING.buyoutCreditRate * Math.max(0, months - 6));
  const residualValue = PRICING.sale[containerKey] * 0.35; // ~35% residual floor
  const rawBuyout = Math.max(residualValue, PRICING.sale[containerKey] - buyoutCredit);
  const buyoutTax = Math.round(rawBuyout * taxRateDecimal);
  const depositCredit = validDelivery ? Math.round(deliveryCost / 2) : 0; // half deposit credited on buyout
  const estimatedBuyout = Math.round(rawBuyout + buyoutTax - depositCredit);
  const buyoutAvailable = months >= 6;

  const fmt = (n) => '$' + Math.round(n).toLocaleString();

  const TabBtn = ({ val, label }) => {
    const active = mode === val;
    return (
      <button onClick={() => setMode(val)} style={{
        flex: 1, padding: '14px', border: 'none', cursor: 'pointer',
        fontFamily: '"Barlow Condensed", sans-serif', fontSize: '18px', fontWeight: '700',
        letterSpacing: '0.01em',
        background: active ? '#1B2A4A' : 'transparent',
        color: active ? '#fff' : '#6B7E96',
        borderRadius: active ? '8px' : '8px',
        transition: 'all 0.2s',
      }}>
        {label}
      </button>
    );
  };

  const OptionBtn = ({ val, current, onChange, children }) => {
    const active = current === val;
    return (
      <button onClick={() => onChange(val)} style={{
        padding: '10px 20px', border: `2px solid ${active ? '#1B2A4A' : '#E2E8F0'}`,
        background: active ? '#1B2A4A' : '#fff',
        color: active ? '#fff' : '#4A5568',
        borderRadius: '6px', cursor: 'pointer',
        fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '600',
        transition: 'all 0.2s',
      }}>
        {children}
      </button>
    );
  };

  const LineItem = ({ label, value, bold, accent, muted, indent }) => (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      padding: indent ? '6px 0 6px 16px' : '8px 0',
      borderBottom: '1px solid #EEF2F7',
    }}>
      <span style={{
        fontFamily: 'Inter, sans-serif', fontSize: muted ? '13px' : '14px',
        color: muted ? '#9AAAB8' : '#4A5568', fontWeight: bold ? '700' : '500',
      }}>{label}</span>
      <span style={{
        fontFamily: bold ? '"Barlow Condensed", sans-serif' : 'Inter, sans-serif',
        fontSize: bold ? '20px' : '14px',
        color: accent ? '#4A9FD4' : (bold ? '#1B2A4A' : '#1B2A4A'),
        fontWeight: '700',
      }}>{value}</span>
    </div>
  );

  return (
    <div>
      {/* Hero */}
      <section style={{
        background: 'linear-gradient(160deg, #0F1D33 0%, #1B2A4A 100%)',
        padding: '140px 32px 72px',
      }}>
        <div style={{ maxWidth: '1200px', margin: '0 auto' }}>
          <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700', letterSpacing: '0.12em', textTransform: 'uppercase', color: '#4A9FD4', display: 'block', marginBottom: '12px' }}>
            Price Estimator
          </span>
          <h1 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: 'clamp(36px, 5vw, 64px)', fontWeight: '800', color: '#fff', margin: '0 0 16px 0', lineHeight: '1.05' }}>
            Estimate Your<br /><span style={{ color: '#4A9FD4' }}>Container Price</span>
          </h1>
          <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '17px', color: 'rgba(255,255,255,0.7)', lineHeight: '1.65', maxWidth: '520px', margin: 0 }}>
            Get an instant estimate for buying or renting a shipping container, including delivery to your ZIP code.
          </p>
        </div>
      </section>

      {/* Estimator */}
      <Section bg="#F4F6F8">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '40px', alignItems: 'start' }} className="estimator-grid">

          {/* Controls */}
          <div>
            <Card style={{ padding: '32px' }}>
              <h2 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '24px', fontWeight: '700', color: '#1B2A4A', margin: '0 0 24px 0' }}>
                Configure Your Container
              </h2>

              {/* Mode tabs */}
              <div style={{ display: 'flex', gap: '4px', background: '#F4F6F8', padding: '4px', borderRadius: '10px', marginBottom: '28px' }}>
                <TabBtn val="sale" label="🏷 Buy" />
                <TabBtn val="rental" label="📅 Rent" />
              </div>

              {/* Size */}
              <div style={{ marginBottom: '24px' }}>
                <label style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.08em', textTransform: 'uppercase', display: 'block', marginBottom: '10px' }}>
                  Container Size
                </label>
                <div style={{ display: 'flex', gap: '10px' }}>
                  <OptionBtn val="20" current={size} onChange={setSize}>20' Standard</OptionBtn>
                  <OptionBtn val="40" current={size} onChange={setSize}>40' High Cube</OptionBtn>
                </div>
              </div>

              {/* Condition */}
              <div style={{ marginBottom: '24px' }}>
                <label style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.08em', textTransform: 'uppercase', display: 'block', marginBottom: '10px' }}>
                  Condition
                </label>
                <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
                  <OptionBtn val="new" current={condition} onChange={setCondition}>New / One-Trip</OptionBtn>
                  <OptionBtn val="used" current={condition} onChange={setCondition}>Used</OptionBtn>
                </div>
              </div>

              {/* Delivery ZIP */}
              <div style={{ marginBottom: mode === 'rental' ? '24px' : '8px' }}>
                <label style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.08em', textTransform: 'uppercase', display: 'block', marginBottom: '10px' }}>
                  Delivery ZIP Code <span style={{ color: '#9AAAB8', fontWeight: '500', textTransform: 'none', letterSpacing: 0 }}>(optional)</span>
                </label>
                <input
                  type="text" placeholder="e.g. 98101"
                  value={zip}
                  maxLength={5}
                  onChange={e => setZip(e.target.value.replace(/\D/g, ''))}
                  style={{
                    width: '100%', boxSizing: 'border-box',
                    fontFamily: 'Inter, sans-serif', fontSize: '16px', fontWeight: '600',
                    padding: '13px 16px', borderRadius: '6px',
                    border: `2px solid ${outOfRange ? '#E53E3E' : zip.length === 5 && miles ? '#4A9FD4' : '#E2E8F0'}`,
                    color: '#1B2A4A', outline: 'none', transition: 'border-color 0.2s',
                  }}
                />
                {zip.length === 5 && (
                  <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', marginTop: '6px',
                    color: outOfRange ? '#E53E3E' : miles ? '#4A9FD4' : '#9AAAB8' }}>
                    {deliveryEstimate.status === 'loading'
                      ? 'Calculating road-route distance...'
                      : outOfRange
                      ? `⚠ ${zip} is outside our ${effectiveMaxRadius}-mile service radius. Contact us for options.`
                      : miles
                        ? `✓ ${deliveryEstimate.provider === 'google' ? 'Road-route' : 'Approximate'} estimate ~${miles} miles from our hub`
                        : deliveryEstimate.warning || '⚠ ZIP not recognized — delivery estimate unavailable'
                    }
                  </p>
                )}
                {zip.length === 5 && deliveryEstimate.status !== 'loading' && deliveryEstimate.warning && miles && (
                  <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', color: '#9AAAB8', marginTop: '4px' }}>
                    {deliveryEstimate.warning}
                  </p>
                )}
              </div>

              {/* Rental months slider */}
              {mode === 'rental' && (
                <div style={{ marginBottom: '8px' }}>
                  <label style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.08em', textTransform: 'uppercase', display: 'block', marginBottom: '10px' }}>
                    Rental Duration — <span style={{ color: '#1B2A4A' }}>{months} months</span>
                  </label>
                  <input
                    type="range" min={1} max={60} step={1}
                    value={months}
                    onChange={e => setMonths(Number(e.target.value))}
                    style={{ width: '100%', accentColor: '#4A9FD4', cursor: 'pointer' }}
                  />
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'Inter, sans-serif', fontSize: '11px', color: '#9AAAB8', marginTop: '4px' }}>
                    <span>1 mo</span>
                    <span style={{ color: months >= 6 ? '#4A9FD4' : '#9AAAB8', fontWeight: months >= 6 ? '700' : '400' }}>6 mo — buyout unlocks</span>
                    <span>60 mo</span>
                  </div>
                </div>
              )}
            </Card>

            {/* Disclaimer */}
            <div style={{ marginTop: '16px', padding: '14px 18px', background: 'rgba(27,42,74,0.04)', border: '1px solid rgba(27,42,74,0.1)', borderRadius: '8px' }}>
              <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#6B7E96', lineHeight: '1.6', margin: 0 }}>
                <strong style={{ color: '#1B2A4A' }}>Estimates only.</strong> Actual pricing may vary based on inventory availability, exact delivery location, access conditions, and current contract terms. Contact us for a firm quote.
              </p>
            </div>
          </div>

          {/* Results panel */}
          <div style={{ position: 'sticky', top: '110px' }}>
            {mode === 'sale' ? (
              <Card style={{ padding: '32px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px' }}>
                  <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '22px', fontWeight: '700', color: '#1B2A4A', margin: 0 }}>
                    Purchase Estimate
                  </h3>
                  <span style={{
                    background: '#1B2A4A', color: '#fff',
                    fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700',
                    padding: '4px 10px', borderRadius: '100px', letterSpacing: '0.04em',
                  }}>
                    {size}' {condition === 'new' ? 'New' : 'Used'}
                  </span>
                </div>
                <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#9AAAB8', margin: '0 0 24px 0' }}>
                  One-time purchase price
                </p>

                {/* Big total */}
                <div style={{
                  background: 'linear-gradient(135deg, #1B2A4A, #243a5e)',
                  borderRadius: '10px', padding: '24px', marginBottom: '24px', textAlign: 'center',
                }}>
                  <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: 'rgba(255,255,255,0.5)', fontWeight: '600', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '8px' }}>
                    {validDelivery ? 'Total with Delivery' : 'Container Total'}
                  </div>
                  <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '52px', fontWeight: '800', color: '#fff', lineHeight: 1 }}>
                    {fmt(saleTotal)}
                  </div>
                  {validDelivery && (
                    <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: 'rgba(255,255,255,0.5)', marginTop: '6px' }}>
                      ~{miles} miles · {fmt(deliveryForSale)} delivery
                    </div>
                  )}
                </div>

                {/* Breakdown */}
                <button onClick={() => setShowBreakdown(!showBreakdown)} style={{
                  background: 'none', border: 'none', cursor: 'pointer',
                  fontFamily: 'Inter, sans-serif', fontSize: '13px', fontWeight: '600',
                  color: '#4A9FD4', padding: '0 0 12px 0', display: 'flex', alignItems: 'center', gap: '6px',
                }}>
                  {showBreakdown ? '▲' : '▼'} {showBreakdown ? 'Hide' : 'Show'} breakdown
                </button>

                {showBreakdown && (
                  <div style={{ marginBottom: '20px' }}>
                    <LineItem label="Container price" value={fmt(basePrice)} />
                    {validDelivery
                      ? <LineItem label={`Delivery (~${miles} mi)`} value={fmt(deliveryForSale)} />
                      : <LineItem label="Delivery" value="Enter ZIP" muted />
                    }
                    <LineItem label={`Sales tax (${taxPercentLabel})`} value={fmt(taxAmount)} indent />
                    <div style={{ padding: '12px 0', display: 'flex', justifyContent: 'space-between' }}>
                      <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '15px', fontWeight: '700', color: '#1B2A4A' }}>Estimated Total</span>
                      <span style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '22px', fontWeight: '800', color: '#1B2A4A' }}>{fmt(saleTotal)}</span>
                    </div>
                  </div>
                )}

                <CTAButton variant="primary" style={{ width: '100%', justifyContent: 'center' }} onClick={goContact}>
                  Get a Firm Quote →
                </CTAButton>
              </Card>
            ) : (
              <Card style={{ padding: '32px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px' }}>
                  <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '22px', fontWeight: '700', color: '#1B2A4A', margin: 0 }}>
                    Rental Estimate
                  </h3>
                  <span style={{
                    background: '#1B2A4A', color: '#fff',
                    fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700',
                    padding: '4px 10px', borderRadius: '100px', letterSpacing: '0.04em',
                  }}>
                    {size}' {condition === 'new' ? 'New' : 'Used'}
                  </span>
                </div>
                <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#9AAAB8', margin: '0 0 20px 0' }}>
                  {months} month{months !== 1 ? 's' : ''} rental estimate
                </p>

                {/* Monthly rate badge */}
                <div style={{ display: 'flex', gap: '12px', marginBottom: '20px' }}>
                  <div style={{ flex: 1, background: '#F4F6F8', border: '1px solid #E2E8F0', borderRadius: '8px', padding: '16px', textAlign: 'center' }}>
                    <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', color: '#9AAAB8', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '4px' }}>Monthly Rate</div>
                    <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '28px', fontWeight: '800', color: '#4A9FD4' }}>{fmt(monthlyRate)}<span style={{ fontSize: '14px', color: '#9AAAB8', fontFamily: 'Inter, sans-serif', fontWeight: '500' }}>/mo</span></div>
                  </div>
                  {validDelivery && (
                    <div style={{ flex: 1, background: '#F4F6F8', border: '1px solid #E2E8F0', borderRadius: '8px', padding: '16px', textAlign: 'center' }}>
                      <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', color: '#9AAAB8', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '4px' }}>Delivery Deposit</div>
                      <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '28px', fontWeight: '800', color: '#1B2A4A' }}>{fmt(deliveryDeposit)}</div>
                      <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '10px', color: '#9AAAB8', marginTop: '2px' }}>incl. pickup</div>
                    </div>
                  )}
                </div>

                {/* Breakdown */}
                <LineItem label="Monthly rental rate" value={fmt(monthlyRate) + '/mo'} />
                <LineItem label={`${months} month${months !== 1 ? 's' : ''} of rent`} value={fmt(monthlyRate * months)} />
                {validDelivery
                  ? <LineItem label={`Delivery deposit (~${miles} mi, round trip)`} value={fmt(deliveryDeposit)} />
                  : <LineItem label="Delivery deposit" value="Enter ZIP" muted />
                }
                {validDelivery
                  ? <LineItem label={`Tax on delivery (${taxPercentLabel})`} value={fmt(deliveryTaxAmount)} />
                  : null
                }
                <LineItem
                  label={`Total paid after ${months} mo`}
                  value={fmt(validDelivery ? totalPaidAfterMonths : monthlyRate * months)}
                  bold
                />

                {/* Buyout section */}
                <div style={{
                  marginTop: '20px', padding: '18px', borderRadius: '8px',
                  background: buyoutAvailable ? 'linear-gradient(135deg, #1B2A4A, #243a5e)' : '#F4F6F8',
                  border: buyoutAvailable ? 'none' : '1px solid #E2E8F0',
                }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: buyoutAvailable ? '14px' : '0' }}>
                    <span style={{
                      fontFamily: 'Inter, sans-serif', fontSize: '13px', fontWeight: '700',
                      color: buyoutAvailable ? 'rgba(255,255,255,0.7)' : '#9AAAB8',
                    }}>
                      {buyoutAvailable ? '🔓 Buyout Option' : `🔒 Buyout unlocks at month 6`}
                    </span>
                    {!buyoutAvailable && (
                      <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#9AAAB8' }}>
                        {6 - months} more month{6 - months !== 1 ? 's' : ''}
                      </span>
                    )}
                  </div>
                  {buyoutAvailable && (
                    <>
                      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px' }}>
                        <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: 'rgba(255,255,255,0.6)' }}>Buyout credit ({months - 6} mo × {fmt(monthlyRate * PRICING.buyoutCreditRate)})</span>
                        <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#4A9FD4', fontWeight: '600' }}>−{fmt(buyoutCredit)}</span>
                      </div>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: '10px', borderTop: '1px solid rgba(255,255,255,0.1)' }}>
                        <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '700', color: 'rgba(255,255,255,0.9)' }}>Est. Buyout Price</span>
                        <span style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '28px', fontWeight: '800', color: '#fff' }}>{fmt(estimatedBuyout)}</span>
                      </div>
                      <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', color: 'rgba(255,255,255,0.35)', margin: '8px 0 0 0', lineHeight: '1.5' }}>
                        Includes tax. Half of delivery deposit credited at buyout. Floor price applies.
                      </p>
                    </>
                  )}
                </div>

                <div style={{ marginTop: '20px' }}>
                  <CTAButton variant="primary" style={{ width: '100%', justifyContent: 'center' }} onClick={goContact}>
                    Start a Rental Quote →
                  </CTAButton>
                </div>
              </Card>
            )}
          </div>
        </div>

        <style>{`@media (max-width: 768px) { .estimator-grid { grid-template-columns: 1fr !important; } }`}</style>
      </Section>

      <QuoteCTABand setCurrentPage={setCurrentPage} />
    </div>
  );
};

Object.assign(window, { EstimatorPage, PRICING });
