// VDI Sydney Dealer Configurator — fully interactive
const { useState, useMemo, useEffect } = React;

const VARIANTS = [
  { id: 'school', name: 'School', tag: 'TfNSW Cat 4 — 80 children / 57 adults', price: 0, img: 'images/use-school.jpg', desc: '2-for-3 child seating, CCTV, TS160 door safety, electronic destination sign.' },
  { id: 'charter', name: 'Charter & Tour', tag: '53 reclining seats + driver', price: 18500, img: 'images/use-charter.jpg', desc: 'Reclining luxury coach seats, full-through luggage bins, curtains, fold-down LCD.' },
  { id: 'mining', name: 'Mining / FIFO', tag: '57 fixed seats — rated for site', price: 12400, img: 'images/use-mining.jpg', desc: 'Full-through luggage bins, CCTV, TS160 door safety, 360° driver warning camera.' },
  { id: 'community', name: 'Community', tag: '57 comfort seats — accessible', price: 8200, img: 'images/use-public.jpg', desc: 'Comfortable coach seats, CCTV, TS160 door safety, 360° driver warning camera.' },
];

const COLOURS = [
  { id: 'white', name: 'Glacier White', hex: '#F5F5F2', price: 0 },
  { id: 'silver', name: 'Pewter Silver', hex: '#9CA0A4', price: 0 },
  { id: 'black', name: 'Onyx Black', hex: '#1A1A1A', price: 1800 },
  { id: 'yellow', name: 'School Yellow', hex: '#F2C200', price: 1800 },
  { id: 'custom', name: 'Custom Livery', hex: 'linear-gradient(135deg, #FFD400 50%, #1A1A1A 50%)', price: 5400 },
];

const ACCESSORIES = [
  { id: 'dashcam', name: 'Roadview M4 Dash Camera', desc: 'Forward + cabin recording, 4G uplink, 256GB storage', price: 2400, icon: 'camera' },
  { id: 'telematics', name: 'Fleet Telematics + GPS', desc: 'Live tracking, driver behaviour, fuel monitoring, 3-yr SIM', price: 3800, icon: 'gps' },
  { id: 'av', name: 'Premium AV System', desc: '32" fold-down LCD, BluRay, surround PA, USB ×8', price: 5600, icon: 'av' },
  { id: 'wifi', name: 'Onboard 5G Wi-Fi', desc: 'Cradlepoint router, antenna, 12-month plan included', price: 1900, icon: 'wifi' },
  { id: 'cctv', name: 'CCTV Upgrade (8-channel)', desc: 'Adds rear and aisle cams to standard 4-channel system', price: 1400, icon: 'cctv' },
  { id: 'wheelchair', name: 'Wheelchair Lift + Bay', desc: 'Side-loading lift, two-bay tie-down, accessible signage', price: 14800, icon: 'access' },
];

const SERVICE_PLANS = [
  { id: 'std', name: 'Standard Warranty', desc: '24-month / 200,000 km bumper-to-bumper. Included with every C12.', price: 0, included: true },
  { id: 'extended', name: 'Extended 5-Year Cover', desc: '60-month / 500,000 km. Driveline + electronics + body.', price: 6800 },
  { id: 'fleet', name: 'Fleet Care Plus', desc: '5-year cover + scheduled servicing + 24/7 priority parts.', price: 14400, popular: true },
  { id: 'total', name: 'Total Operations Plan', desc: 'Everything in Fleet Care Plus + driver training + telematics SaaS.', price: 22800 },
];

const BUYER_TYPES = [
  { id: 'private', name: 'Private / Retail', desc: 'No ABN — personal purchase', meta: '1 vehicle' },
  { id: 'sb', name: 'Small Business / ABN Holder', desc: 'Single operator, school or charter', meta: '1–5 vehicles' },
  { id: 'gov', name: 'Government / NFP', desc: 'Local, State, Federal, NFPs, Diplomats, Concession', meta: 'Tendered' },
  { id: 'fleet-sm', name: 'Business Fleet', desc: 'Established operator', meta: '6–25 vehicles' },
  { id: 'fleet-lg', name: 'Large Fleet', desc: 'Volume discount eligible', meta: '25+ vehicles' },
  { id: 'fleet-nat', name: 'National Fleet', desc: 'Manufacturer-direct sales agreement', meta: '100+ vehicles' },
  { id: 'rental', name: 'Rental Operator', desc: 'Short-term hire / sub-lease', meta: 'Specialist plan' },
];

const STEPS = [
  { id: 'buyer', name: 'Buyer Type' },
  { id: 'variant', name: 'Variant' },
  { id: 'accessories', name: 'Accessories' },
  { id: 'service', name: 'Service Plan' },
  { id: 'tradein', name: 'Trade-In' },
  { id: 'finance', name: 'Finance' },
  { id: 'review', name: 'Review' },
];

const BASE_PRICE = 429990;
const ORDER_FEE = 1000;

function fmt(n) { return '$' + n.toLocaleString('en-AU'); }
function fmtNoSign(n) { return n.toLocaleString('en-AU'); }

// Icons
const Icon = ({ name }) => {
  const paths = {
    camera: <g><rect x="4" y="9" width="24" height="16" rx="2" stroke="currentColor" strokeWidth="2" fill="none"/><circle cx="16" cy="17" r="4" stroke="currentColor" strokeWidth="2" fill="none"/><rect x="11" y="6" width="10" height="3" stroke="currentColor" strokeWidth="2" fill="none"/></g>,
    gps: <g><path d="M16 4 L16 28 M4 16 L28 16" stroke="currentColor" strokeWidth="2"/><circle cx="16" cy="16" r="6" stroke="currentColor" strokeWidth="2" fill="none"/><circle cx="16" cy="16" r="2" fill="currentColor"/></g>,
    av: <g><rect x="4" y="6" width="24" height="14" rx="1" stroke="currentColor" strokeWidth="2" fill="none"/><path d="M14 13 L19 16 L14 19 Z" fill="currentColor"/><path d="M10 26 L22 26" stroke="currentColor" strokeWidth="2"/></g>,
    wifi: <g><path d="M4 12 Q16 2 28 12" stroke="currentColor" strokeWidth="2" fill="none"/><path d="M8 16 Q16 8 24 16" stroke="currentColor" strokeWidth="2" fill="none"/><path d="M12 20 Q16 16 20 20" stroke="currentColor" strokeWidth="2" fill="none"/><circle cx="16" cy="24" r="2" fill="currentColor"/></g>,
    cctv: <g><rect x="6" y="8" width="20" height="10" rx="1" stroke="currentColor" strokeWidth="2" fill="none"/><circle cx="11" cy="13" r="2" fill="currentColor"/><path d="M16 18 L13 26 L19 26 Z" stroke="currentColor" strokeWidth="2" fill="none"/></g>,
    access: <g><circle cx="16" cy="7" r="3" stroke="currentColor" strokeWidth="2" fill="none"/><path d="M11 15 L21 15 M16 15 L16 23 L23 23" stroke="currentColor" strokeWidth="2" fill="none"/><circle cx="16" cy="23" r="5" stroke="currentColor" strokeWidth="2" fill="none"/></g>,
  };
  return <svg viewBox="0 0 32 32" fill="none">{paths[name]}</svg>;
};

function App() {
  const [stepIdx, setStepIdx] = useState(0);
  const [buyer, setBuyer] = useState('sb');
  const [variant, setVariant] = useState('charter');
  const [colour, setColour] = useState('white');
  const [accessories, setAccessories] = useState(['telematics']);
  const [servicePlan, setServicePlan] = useState('fleet');
  const [tradeIn, setTradeIn] = useState({ has: false, rego: '', state: 'NSW', odo: '', estimate: 0 });
  const [finance, setFinance] = useState({ method: 'finance', term: 60, deposit: 50000, balloon: 20 });
  const [showFinanceCalc, setShowFinanceCalc] = useState(true);
  const [orderPlaced, setOrderPlaced] = useState(false);

  // Tweaks panel hookup — show finance calc toggle
  useEffect(() => {
    const handler = (e) => {
      if (!e.data) return;
      if (e.data.type === '__activate_edit_mode') setTweaksVisible(true);
      if (e.data.type === '__deactivate_edit_mode') setTweaksVisible(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({type:'__edit_mode_available'}, '*');
    return () => window.removeEventListener('message', handler);
  }, []);
  const [tweaksVisible, setTweaksVisible] = useState(false);

  const v = VARIANTS.find(x => x.id === variant);
  const c = COLOURS.find(x => x.id === colour);
  const sp = SERVICE_PLANS.find(x => x.id === servicePlan);
  const accObjs = ACCESSORIES.filter(a => accessories.includes(a.id));
  const buyerObj = BUYER_TYPES.find(b => b.id === buyer);

  // Buyer-type discount logic
  const buyerDiscount = useMemo(() => {
    const subtotal = BASE_PRICE + (v?.price||0) + (c?.price||0) + accObjs.reduce((s,a)=>s+a.price,0) + (sp?.price||0);
    if (buyer === 'fleet-sm') return Math.round(subtotal * 0.025);
    if (buyer === 'fleet-lg') return Math.round(subtotal * 0.05);
    if (buyer === 'fleet-nat') return Math.round(subtotal * 0.075);
    if (buyer === 'gov') return Math.round(subtotal * 0.04);
    if (buyer === 'rental') return Math.round(subtotal * 0.03);
    return 0;
  }, [buyer, variant, colour, accessories, servicePlan]);

  const subtotal = BASE_PRICE + (v?.price||0) + (c?.price||0) + accObjs.reduce((s,a)=>s+a.price,0) + (sp?.price||0);
  const tradeInValue = tradeIn.has ? (tradeIn.estimate || 0) : 0;
  const orcCharges = 4850; // on-road costs
  const driveAway = subtotal + orcCharges - buyerDiscount - tradeInValue;

  // Finance calc
  const monthlyPmt = useMemo(() => {
    if (finance.method !== 'finance') return 0;
    const principal = Math.max(0, driveAway - finance.deposit);
    const balloonAmt = principal * (finance.balloon / 100);
    const r = 0.082 / 12;
    const n = finance.term;
    const pv = principal - balloonAmt / Math.pow(1 + r, n);
    if (n === 0 || r === 0) return 0;
    return pv * (r * Math.pow(1+r, n)) / (Math.pow(1+r, n) - 1);
  }, [finance, driveAway]);

  const goNext = () => setStepIdx(i => Math.min(i+1, STEPS.length-1));
  const goPrev = () => setStepIdx(i => Math.max(i-1, 0));

  const toggleAcc = (id) => {
    setAccessories(prev => prev.includes(id) ? prev.filter(x=>x!==id) : [...prev, id]);
  };

  const renderStep = () => {
    const step = STEPS[stepIdx];

    if (step.id === 'buyer') {
      return (
        <div>
          <div className="cfg-step-head">
            <div className="kicker">Step 01 / 07 — Tell us who you are</div>
            <h2>Are You Buying As…</h2>
            <p>This helps us route your enquiry to the right specialist and apply any fleet, government or volume pricing you may be eligible for. You can change this later.</p>
          </div>
          <div className="opt-grid" style={{gridTemplateColumns:'1fr', gap: 10}}>
            {BUYER_TYPES.map(b => (
              <div key={b.id} className={`opt compact${buyer===b.id?' selected':''}`} onClick={()=>setBuyer(b.id)}>
                <div className="body">
                  <h4>{b.name}</h4>
                  <p className="desc">{b.desc}</p>
                </div>
                <div className="right-meta">{b.meta}</div>
              </div>
            ))}
          </div>
        </div>
      );
    }

    if (step.id === 'variant') {
      return (
        <div>
          <div className="cfg-step-head">
            <div className="kicker">Step 02 / 07 — Configuration</div>
            <h2>Choose Your Variant.</h2>
            <p>One C12 chassis, four operations-ready fitouts. Each variant ships with the safety, comfort and connectivity features that make sense for the job.</p>
          </div>
          <div className="opt-grid">
            {VARIANTS.map(x => (
              <div key={x.id} className={`opt${variant===x.id?' selected':''}`} onClick={()=>setVariant(x.id)}>
                <div className="img"><img src={x.img} alt={x.name}/></div>
                <div className="body">
                  <h4>{x.name}</h4>
                  <p className="desc">{x.desc}</p>
                  <div className="meta">
                    <span style={{fontSize:11, letterSpacing:'0.12em', textTransform:'uppercase', color:'var(--vdi-stone)'}}>{x.tag}</span>
                    {x.price === 0 ? <span className="price included">Included</span> : <span className="price">+{fmt(x.price)}</span>}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      );
    }

    if (step.id === 'accessories') {
      return (
        <div>
          <div className="cfg-step-head">
            <div className="kicker">Step 03 / 07 — Accessories</div>
            <h2>Add Accessories.</h2>
            <p>Factory-fit options installed before delivery. Everything is workshop-grade, supported by our nationwide service network and covered by your service plan.</p>
          </div>
          <div className="acc-grid">
            {ACCESSORIES.map(a => (
              <div key={a.id} className={`acc${accessories.includes(a.id)?' selected':''}`} onClick={()=>toggleAcc(a.id)}>
                <div className="icon"><Icon name={a.icon}/></div>
                <div>
                  <h4>{a.name}</h4>
                  <p className="desc">{a.desc}</p>
                </div>
                <div style={{textAlign:'right'}}>
                  <div className="price">+{fmt(a.price)}</div>
                  <div className="check">{accessories.includes(a.id) ? '✓' : ''}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      );
    }

    if (step.id === 'service') {
      return (
        <div>
          <div className="cfg-step-head">
            <div className="kicker">Step 04 / 07 — Aftercare</div>
            <h2>Service & Warranty.</h2>
            <p>Every C12 ships with our 24-month standard warranty. Most fleet operators upgrade — extended cover protects driveline, electronics and body for the full lifecycle.</p>
          </div>
          <div className="opt-grid">
            {SERVICE_PLANS.map(x => (
              <div key={x.id} className={`opt${servicePlan===x.id?' selected':''}`} onClick={()=>setServicePlan(x.id)} style={{position:'relative'}}>
                {x.popular && <span style={{position:'absolute', top:14, left:14, background:'var(--vdi-black)', color:'var(--vdi-yellow)', fontSize:10, letterSpacing:'0.2em', padding:'4px 8px', fontFamily:'Barlow', fontWeight:800, zIndex:2}}>★ Most Chosen</span>}
                <div className="body" style={{padding: x.popular ? '52px 28px 28px' : '28px'}}>
                  <h4>{x.name}</h4>
                  <p className="desc">{x.desc}</p>
                  <div className="meta">
                    <span/>
                    {x.included ? <span className="price included">Included</span> : <span className="price">+{fmt(x.price)}</span>}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      );
    }

    if (step.id === 'tradein') {
      return (
        <div>
          <div className="cfg-step-head">
            <div className="kicker">Step 05 / 07 — Trade-In</div>
            <h2>Trade In Your Old Bus?</h2>
            <p>Tell us about your existing vehicle and we'll come back with our best price within 48 hours. You can accept, reject, or proceed without trade-in at any point.</p>
          </div>
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap: 14, marginBottom: 24}}>
            <div className={`opt compact${!tradeIn.has?' selected':''}`} onClick={()=>setTradeIn({...tradeIn, has: false})}>
              <div className="body"><h4>No trade-in</h4><p className="desc">I'll handle disposal of any existing vehicle myself.</p></div>
              <div className="right-meta">Skip</div>
            </div>
            <div className={`opt compact${tradeIn.has?' selected':''}`} onClick={()=>setTradeIn({...tradeIn, has: true, estimate: tradeIn.estimate || 145000})}>
              <div className="body"><h4>Yes, trade in a vehicle</h4><p className="desc">Get an estimate against your final drive-away price.</p></div>
              <div className="right-meta">Continue</div>
            </div>
          </div>
          {tradeIn.has && (
            <div className="form-card">
              <h4>Tell us about your trade-in</h4>
              <div className="field-grid">
                <div className="field"><label>Registration number</label><input type="text" placeholder="e.g. BS12VDI" value={tradeIn.rego} onChange={e=>setTradeIn({...tradeIn, rego:e.target.value})}/></div>
                <div className="field"><label>Registration state</label><select value={tradeIn.state} onChange={e=>setTradeIn({...tradeIn, state:e.target.value})}>{['ACT','NSW','NT','QLD','SA','TAS','VIC','WA'].map(s=><option key={s}>{s}</option>)}</select></div>
                <div className="field"><label>Make / Model</label><input type="text" placeholder="e.g. Yutong C12 2018"/></div>
                <div className="field"><label>Estimated odometer (km)</label><input type="number" placeholder="e.g. 240,000" value={tradeIn.odo} onChange={e=>setTradeIn({...tradeIn, odo:e.target.value})}/></div>
              </div>
              <div style={{marginTop:24, padding:'18px 20px', background:'var(--vdi-paper)', border:'1px dashed var(--vdi-line)', display:'flex', justifyContent:'space-between', alignItems:'center'}}>
                <div>
                  <div style={{fontSize:11, letterSpacing:'0.16em', textTransform:'uppercase', color:'var(--vdi-stone)'}}>Indicative trade-in value</div>
                  <div style={{fontFamily:'Barlow', fontWeight:800, fontSize:32, color:'var(--vdi-success)'}}>{fmt(tradeIn.estimate || 145000)}</div>
                </div>
                <span style={{fontSize:12, color:'var(--vdi-stone)', maxWidth:240, textAlign:'right'}}>Estimate only. Final valuation confirmed in person within 48hrs of order.</span>
              </div>
            </div>
          )}
        </div>
      );
    }

    if (step.id === 'finance') {
      return (
        <div>
          <div className="cfg-step-head">
            <div className="kicker">Step 06 / 07 — Payment</div>
            <h2>How Will You Pay?</h2>
            <p>Cash for own-bank purchases, finance for traditional chattel mortgage, novated lease for personal use against pre-tax salary. Our specialists will be in touch.</p>
          </div>
          <div className="toggle-row" style={{marginBottom:32}}>
            {[{id:'cash',name:'Cash'},{id:'finance',name:'Finance'},{id:'novated',name:'Novated Lease'}].map(m=>(
              <button key={m.id} className={finance.method===m.id?'active':''} onClick={()=>setFinance({...finance, method:m.id})}>{m.name}</button>
            ))}
          </div>
          {finance.method === 'cash' && (
            <div className="form-card">
              <h4>Cash purchase</h4>
              <p style={{color:'var(--vdi-stone)', fontSize:14, marginBottom:0}}>Final payment of <strong style={{color:'var(--vdi-black)'}}>{fmt(driveAway)}</strong> due on delivery. We'll provide tax invoice on order placement and final delivery confirmation. Bank transfer or company cheque accepted.</p>
            </div>
          )}
          {finance.method === 'finance' && showFinanceCalc && (
            <div className="finance-card">
              <div style={{fontSize:11, letterSpacing:'0.2em', textTransform:'uppercase', color:'var(--vdi-yellow-dark)', fontFamily:'Barlow', fontWeight:800}}>Estimated monthly payment</div>
              <div className="pmt">{fmt(Math.round(monthlyPmt))}<small>/ month</small></div>
              <div className="calc-row">
                <div className="field">
                  <label>Loan term</label>
                  <select value={finance.term} onChange={e=>setFinance({...finance, term:Number(e.target.value)})}>
                    {[24,36,48,60,72].map(t=><option key={t} value={t}>{t} months</option>)}
                  </select>
                </div>
                <div className="field">
                  <label>Balloon</label>
                  <select value={finance.balloon} onChange={e=>setFinance({...finance, balloon:Number(e.target.value)})}>
                    {[0,5,10,15,20,25,30].map(b=><option key={b} value={b}>{b}%</option>)}
                  </select>
                </div>
                <div className="field" style={{gridColumn:'1 / -1'}}>
                  <label>Deposit ({fmt(finance.deposit)})</label>
                  <div className="slider-row">
                    <input type="range" min="0" max="200000" step="5000" value={finance.deposit} onChange={e=>setFinance({...finance, deposit:Number(e.target.value)})}/>
                    <span className="val">{fmtNoSign(finance.deposit/1000)}k</span>
                  </div>
                </div>
              </div>
              <div className="rates">
                <div><div className="v">8.20%</div><div className="l">Interest rate</div></div>
                <div><div className="v">8.30%</div><div className="l">Comparison rate</div></div>
                <div><div className="v">{fmt(Math.round(monthlyPmt * finance.term))}</div><div className="l">Total repaid</div></div>
                <div><div className="v">{fmt(Math.round((driveAway - finance.deposit) * finance.balloon/100))}</div><div className="l">Final balloon</div></div>
              </div>
              <p style={{fontSize:11, color:'rgba(53,53,53,0.55)', marginTop:24, lineHeight:1.6}}>
                Comparison rate is based on an approved loan meeting required criteria. Estimate only and subject to approval — your personal rate may differ. Our finance specialists will reach out to confirm requirements.
              </p>
            </div>
          )}
          {finance.method === 'novated' && (
            <div className="finance-card">
              <div style={{fontSize:11, letterSpacing:'0.2em', textTransform:'uppercase', color:'var(--vdi-yellow-dark)', fontFamily:'Barlow', fontWeight:800}}>Estimated novated payment</div>
              <div className="pmt">{fmt(Math.round(driveAway / 60 * 0.92))}<small>/ month pre-tax</small></div>
              <p style={{fontSize:13, color:'rgba(53,53,53,0.7)', marginTop:24, lineHeight:1.6, maxWidth:480}}>
                Novated lease is uncommon for commercial buses but available where the buyer is an eligible PAYG employee. Our novated specialists will assess eligibility and confirm.
              </p>
            </div>
          )}
        </div>
      );
    }

    if (step.id === 'review') {
      if (orderPlaced) {
        return (
          <div style={{padding:'80px 0', textAlign:'center', maxWidth:560, margin:'0 auto'}}>
            <div style={{fontFamily:'Barlow', fontWeight:800, fontSize:14, letterSpacing:'0.2em', color:'var(--vdi-yellow-dark)'}}>Order received</div>
            <h2 style={{fontSize:72, marginTop:14, lineHeight:0.95}}>You're On The List.</h2>
            <p style={{color:'var(--vdi-stone)', marginTop:18, fontSize:16, lineHeight:1.55}}>
              Order reference <strong style={{color:'var(--vdi-black)'}}>VDI-SYD-2026-0428</strong> received. A VDI Sydney sales specialist will be in touch within one business day to confirm allocation, finalise trade-in valuation and walk you through delivery scheduling.
            </p>
            <div style={{display:'flex', gap:12, justifyContent:'center', marginTop:28}}>
              <a href="VDI Australia.html" className="btn btn-dark">Back to VDI Australia</a>
              <a href="#" className="btn btn-ghost">View Order Portal</a>
            </div>
          </div>
        );
      }
      return (
        <div>
          <div className="cfg-step-head">
            <div className="kicker">Step 07 / 07 — Review & Place</div>
            <h2>Here's Your Order.</h2>
            <p>One last look. Submitting an order is a fully refundable {fmt(ORDER_FEE)} reservation — vehicle allocation is confirmed by a VDI specialist within one business day.</p>
          </div>
          <div className="form-card" style={{marginBottom:18}}>
            <h4>Account details</h4>
            <div className="field-grid">
              <div className="field"><label>Company / trading name</label><input type="text" placeholder={buyer==='private'?'Personal purchase':'e.g. Sydney Charter Co.'} defaultValue={buyer==='gov'?'Sydney Trains':'Sydney Charter Co.'}/></div>
              <div className="field"><label>ABN</label><input type="text" placeholder="e.g. 12 345 678 901" defaultValue="58 003 142 619"/></div>
              <div className="field"><label>Contact name</label><input type="text" defaultValue="Marcus Lee"/></div>
              <div className="field"><label>Mobile</label><input type="tel" defaultValue="+61 412 345 678"/></div>
              <div className="field" style={{gridColumn:'1 / -1'}}><label>Email</label><input type="email" defaultValue="marcus@sydneycharter.com.au"/></div>
            </div>
          </div>
          <div className="form-card">
            <h4>Delivery</h4>
            <div className="field-grid">
              <div className="field"><label>Method</label><select defaultValue="depot"><option value="depot">VDI Sydney depot pickup — Prestons NSW</option><option value="delivery">Door-to-depot delivery (+$1,200)</option></select></div>
              <div className="field"><label>Estimated delivery</label><input type="text" defaultValue="Jun. / Jul. 2026" disabled style={{background:'var(--vdi-paper)', color:'var(--vdi-stone)'}}/></div>
            </div>
          </div>
          <div style={{marginTop:24, padding:20, background:'var(--vdi-paper)', display:'flex', gap:12, alignItems:'flex-start', fontSize:12, color:'var(--vdi-stone)', lineHeight:1.6}}>
            <span style={{fontFamily:'Barlow', fontWeight:800, fontSize:18, color:'var(--vdi-yellow-dark)'}}>★</span>
            <span>By placing this order you agree to VDI's Terms & Conditions and acknowledge a {fmt(ORDER_FEE)} fully refundable reservation will be charged. Vehicle allocation, fleet pricing, and final trade-in valuation are confirmed by a VDI Sydney specialist within one business day.</span>
          </div>
        </div>
      );
    }
  };

  return (
    <div>
      <div className="utility-bar">
        <div className="container">
          <div className="left"><span>VDI Sydney · 231 Kurrajong Road, Prestons NSW 2170</span><span style={{opacity:0.4}}>|</span><span>Authorised Yutong Dealer</span></div>
          <div className="right"><a href="VDI Australia.html">Back to VDI Australia</a><a href="#">Order Portal</a><a className="phone" href="#">(02) 9601 9988</a></div>
        </div>
      </div>

      <header className="dealer-header">
        <div className="container">
          <div style={{display:'flex', alignItems:'center'}}>
            <a href="VDI Australia.html" className="logo"><span className="mark">VDI<span className="dot"></span></span><span className="sub">Australia</span></a>
            <span className="dealer-tag"><span className="dot"/>Authorised Dealer · <b>VDI Sydney</b></span>
          </div>
          <div className="right">
            <div className="pc">📍 Servicing <b>2153 NSW</b> · Castle Hill</div>
            <a href="VDI Australia.html">Distributor Site →</a>
          </div>
        </div>
      </header>

      <div className="stepper-bar">
        <div className="container">
          <div className="stepper">
            {STEPS.map((s, i) => (
              <div key={s.id} className={`step${i===stepIdx?' active':''}${i<stepIdx?' complete':''}`} onClick={()=>setStepIdx(i)}>
                <span className="num">{i<stepIdx?'✓':String(i+1).padStart(2,'0')}</span>
                <span>{s.name}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="cfg-shell">
        <div className="cfg-main">
          {renderStep()}
          {!orderPlaced && (
            <div className="cfg-footer-nav">
              <button className="btn btn-ghost" onClick={goPrev} disabled={stepIdx===0} style={{opacity: stepIdx===0?0.4:1}}>← Back</button>
              <div style={{fontSize:12, color:'var(--vdi-stone)', letterSpacing:'0.12em', textTransform:'uppercase'}}>
                Step {stepIdx+1} of {STEPS.length}
              </div>
              {stepIdx < STEPS.length-1 ? (
                <button className="btn btn-primary" onClick={goNext}>Continue →</button>
              ) : (
                <button className="btn btn-primary" onClick={()=>setOrderPlaced(true)}>Place Order · {fmt(ORDER_FEE)} →</button>
              )}
            </div>
          )}
        </div>

        <aside className="cfg-summary">
          <div className="summary-hero">
            <div className="label">Your build</div>
            <h3>Yutong C12 — {v?.name}</h3>
            <div className="img-wrap"><img src={v?.img} alt={v?.name}/></div>
          </div>
          <div className="summary-body">
            <h5>Configuration</h5>
            <div className="summary-line"><span className="name">Buyer</span><span className="val">{buyerObj?.name}</span></div>
            <div className="summary-line"><span className="name">Variant — {v?.name}</span><span className="val">{v?.price===0?'Included':`+${fmt(v.price)}`}</span></div>
            <div className="summary-line"><span className="name">Livery — {c?.name}</span><span className="val">{c?.price===0?'Included':`+${fmt(c.price)}`}</span></div>
            <div className="summary-line"><span className="name">Service — {sp?.name}</span><span className="val">{sp?.included?'Included':`+${fmt(sp.price)}`}</span></div>

            {accObjs.length > 0 && <h5>Accessories</h5>}
            {accObjs.map(a=>(
              <div key={a.id} className="summary-line"><span className="name">{a.name}</span><span className="val">+{fmt(a.price)}</span></div>
            ))}

            <h5>Pricing</h5>
            <div className="summary-line muted"><span className="name">Base C12</span><span className="val">{fmt(BASE_PRICE)}</span></div>
            <div className="summary-line muted"><span className="name">On-road costs (NSW)</span><span className="val">+{fmt(orcCharges)}</span></div>
            {buyerDiscount > 0 && <div className="summary-line" style={{color:'var(--vdi-success)'}}><span className="name">Buyer-type discount</span><span className="val">−{fmt(buyerDiscount)}</span></div>}
            {tradeInValue > 0 && <div className="summary-line" style={{color:'var(--vdi-success)'}}><span className="name">Trade-in</span><span className="val">−{fmt(tradeInValue)}</span></div>}
          </div>
          <div className="summary-total">
            <div className="row">
              <div>
                <div className="l">Drive away price</div>
                <div className="sub">NSW · {buyerObj?.name}</div>
              </div>
              <div className="v">{fmt(driveAway)}</div>
            </div>
            {finance.method==='finance' && monthlyPmt > 0 && (
              <div style={{marginTop:14, paddingTop:14, borderTop:'1px solid rgba(255,255,255,0.1)', display:'flex', justifyContent:'space-between', alignItems:'baseline'}}>
                <span style={{fontSize:11, letterSpacing:'0.16em', textTransform:'uppercase', color:'rgba(255,255,255,0.6)'}}>From</span>
                <span style={{fontFamily:'Barlow', fontWeight:800, fontSize:24}}>{fmt(Math.round(monthlyPmt))}<span style={{fontSize:12, color:'rgba(255,255,255,0.5)'}}> /mo</span></span>
              </div>
            )}
            <div className="actions">
              <button className="btn btn-primary" onClick={()=>setStepIdx(STEPS.length-1)}>Review & Order</button>
            </div>
          </div>
        </aside>
      </div>

      {tweaksVisible && <TweaksPanel
        showFinanceCalc={showFinanceCalc}
        onToggleFinance={()=>setShowFinanceCalc(!showFinanceCalc)}
        onClose={()=>{ setTweaksVisible(false); window.parent.postMessage({type:'__edit_mode_dismissed'},'*'); }}
      />}
    </div>
  );
}

function TweaksPanel({ showFinanceCalc, onToggleFinance, onClose }) {
  return (
    <div style={{position:'fixed', right:24, bottom:24, width:280, background:'var(--vdi-black)', color:'white', padding:20, borderRadius:6, boxShadow:'0 16px 40px rgba(0,0,0,0.3)', zIndex:1000}}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:14}}>
        <div style={{fontFamily:'Barlow', fontWeight:800, fontSize:14, letterSpacing:'0.2em', color:'var(--vdi-yellow)'}}>Tweaks</div>
        <button onClick={onClose} style={{color:'white', fontSize:18, opacity:0.6}}>×</button>
      </div>
      <label style={{display:'flex', justifyContent:'space-between', alignItems:'center', fontSize:13, padding:'10px 0', borderBottom:'1px solid rgba(255,255,255,0.1)', cursor:'pointer'}}>
        <span>Show finance calculator</span>
        <input type="checkbox" checked={showFinanceCalc} onChange={onToggleFinance}/>
      </label>
      <p style={{fontSize:11, color:'rgba(255,255,255,0.5)', marginTop:14, lineHeight:1.5}}>Toggle to compare configurator with/without inline finance calc — some operators prefer to handle it offline.</p>
    </div>
  );
}

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