// Alba Cars — Vehicle Detail page (the flagship cinematic page)
const { useState: useStateV } = React;

function VehiclePage({ id, setRoute, setVehicleId }) {
  const v = VEHICLES.find(x => x.id === id);
  const [tab, setTab] = useStateV('specs');
  if (!v) {
    return (
      <div style={{ paddingTop: 200, paddingBottom: 200, textAlign: 'center' }}>
        <h2 className="display" style={{ fontSize: 32 }}>Vehicle not found</h2>
        <div style={{ marginTop: 20 }}>
          <Btn variant="primary" icon="arrow-right" onClick={() => setRoute('buy')}>Back to inventory</Btn>
        </div>
      </div>
    );
  }
  const isPOA = v.price == null;
  const similar = VEHICLES.filter(x => x.body === v.body && x.id !== v.id).slice(0, 4);

  return (
    <div style={{ paddingTop: 88 }}>
      {/* Breadcrumbs */}
      <div className="container-wide" style={{ padding: '24px 32px 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: 'var(--text-muted)', flexWrap: 'wrap' }}>
          <button onClick={() => setRoute('home')} style={crumbBtn}>Home</button>
          <Icon name="chevron-right" size={11} />
          <button onClick={() => setRoute('buy')} style={crumbBtn}>Inventory</button>
          <Icon name="chevron-right" size={11} />
          <button onClick={() => setRoute('buy')} style={crumbBtn}>{v.make}</button>
          <Icon name="chevron-right" size={11} />
          <span style={{ color: 'var(--text)' }}>{v.year} {v.model}</span>
        </div>
      </div>

      {/* Hero — full-bleed photo */}
      <section style={{ padding: '24px 0 0' }}>
        <div className="container-wide">
          <div style={{
            position: 'relative', borderRadius: 14, overflow: 'hidden',
            aspectRatio: window.innerWidth > 900 ? '21/9' : '4/3',
            background: 'var(--surface-2)',
          }}>
            <img src={v.photo} alt={`${v.year} ${v.make} ${v.model}`} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
            <div style={{
              position: 'absolute', inset: 0,
              background: 'linear-gradient(180deg, rgba(11,13,16,0) 30%, rgba(11,13,16,0.75) 100%)',
            }} />

            {/* Top badges */}
            <div style={{ position: 'absolute', top: 24, left: 24, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              <Pill className="" dot>Certified Pre-Owned</Pill>
              <span style={{ ...pillStyle('var(--alba-red)', '#fff') }}>● 150+ Point Inspected</span>
              <span style={{ ...pillStyle('rgba(255,255,255,0.95)', 'var(--ink)') }}>RTA Certified</span>
            </div>
            <div style={{ position: 'absolute', top: 24, right: 24, display: 'flex', gap: 8 }}>
              <button style={iconCircle()}><Icon name="heart" size={16} /></button>
              <button style={iconCircle()}><Icon name="share" size={16} /></button>
            </div>

            {/* Bottom info */}
            <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: 36, color: '#fff' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 24, flexWrap: 'wrap' }}>
                <div>
                  <div style={{ fontSize: 12, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.7)', fontFamily: 'var(--f-display)' }}>
                    {v.year} · {v.make} · <span className="mono">{v.stockId}</span>
                  </div>
                  <h1 className="display" style={{ fontSize: 'clamp(36px, 5.6vw, 76px)', letterSpacing: '-0.04em', marginTop: 10, color: '#fff' }}>
                    {v.model} <span style={{ fontStyle: 'italic', fontWeight: 300, color: 'var(--gold)' }}>{v.variant}</span>
                  </h1>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.7)' }}>
                    {isPOA ? 'Inquire for price' : 'Demo price'}
                  </div>
                  <div className="mono" style={{ fontSize: 36, fontWeight: 600, marginTop: 4 }}>
                    {fmtAED(v.price)}
                  </div>
                </div>
              </div>
            </div>

            {/* Thumb strip - placeholder */}
            <div style={{ position: 'absolute', bottom: 28, left: 36, display: window.innerWidth > 900 ? 'flex' : 'none', gap: 6 }}>
              {[1,2,3,4,5,6,7,8].map(i => (
                <div key={i} style={{
                  width: 60, height: 38,
                  borderRadius: 4,
                  background: i === 1 ? 'rgba(255,255,255,0.95)' : 'rgba(0,0,0,0.4)',
                  border: '1px solid rgba(255,255,255,0.2)',
                  backdropFilter: 'blur(4px)',
                  display: 'grid', placeItems: 'center',
                  fontSize: 9, color: i === 1 ? 'var(--ink)' : 'rgba(255,255,255,0.7)',
                  fontFamily: 'var(--f-mono)',
                }}>{i.toString().padStart(2,'0')}</div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* Key facts row */}
      <section style={{ padding: '32px 0', borderBottom: '1px solid var(--border)' }}>
        <div className="container-wide" style={{
          display: 'grid',
          gridTemplateColumns: window.innerWidth > 900 ? 'repeat(6, 1fr)' : 'repeat(3, 1fr)',
          gap: 0,
        }}>
          {[
            { l: 'Year', v: v.year, icon: 'calendar' },
            { l: 'Mileage', v: fmtMileage(v.mileage), icon: 'gauge' },
            { l: 'Engine', v: v.engine, icon: 'fuel' },
            { l: 'Power', v: v.power, icon: 'sparkle' },
            { l: 'Transmission', v: v.trans, icon: 'transmission' },
            { l: 'Drivetrain', v: v.drive, icon: 'cog' },
          ].map((k, i) => (
            <div key={k.l} style={{
              padding: '8px 24px',
              borderRight: (i % (window.innerWidth > 900 ? 6 : 3) !== (window.innerWidth > 900 ? 5 : 2)) ? '1px solid var(--border)' : 'none',
              display: 'flex', flexDirection: 'column', gap: 6,
            }}>
              <div style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--text-muted)', display: 'flex', alignItems: 'center', gap: 6 }}>
                <Icon name={k.icon} size={12} /> {k.l}
              </div>
              <div className="mono" style={{ fontSize: 15 }}>{k.v}</div>
            </div>
          ))}
        </div>
      </section>

      {/* Main body — content + sticky enquiry */}
      <section style={{ padding: '60px 0' }}>
        <div className="container-wide" style={{ display: 'grid', gridTemplateColumns: window.innerWidth > 1100 ? '1.6fr 1fr' : '1fr', gap: 60 }}>
          {/* Left content */}
          <div>
            {/* Tabs */}
            <div style={{ display: 'flex', gap: 0, borderBottom: '1px solid var(--border)', marginBottom: 32 }}>
              {['specs', 'inspection', 'history', 'features'].map(t => (
                <button key={t} onClick={() => setTab(t)} style={{
                  background: 'none', border: 'none',
                  padding: '14px 22px',
                  fontFamily: 'var(--f-display)', fontSize: 13, fontWeight: 500,
                  letterSpacing: '0.06em', textTransform: 'uppercase',
                  color: tab === t ? 'var(--text)' : 'var(--text-muted)',
                  borderBottom: tab === t ? '2px solid var(--alba-red)' : '2px solid transparent',
                  marginBottom: -1, cursor: 'pointer',
                }}>
                  {t === 'specs' ? 'Specifications' : t === 'inspection' ? '154-Point Report' : t === 'history' ? 'Vehicle History' : 'Features'}
                </button>
              ))}
            </div>

            {tab === 'specs' && <TabSpecs v={v} />}
            {tab === 'inspection' && <TabInspection v={v} />}
            {tab === 'history' && <TabHistory v={v} />}
            {tab === 'features' && <TabFeatures v={v} />}
          </div>

          {/* Right enquiry */}
          <aside style={{ position: window.innerWidth > 1100 ? 'sticky' : 'static', top: 110, alignSelf: 'start' }}>
            <EnquiryPanel v={v} setRoute={setRoute} />
          </aside>
        </div>
      </section>

      {/* Similar */}
      <section className="section" style={{ background: 'var(--surface-2)' }}>
        <div className="container-wide">
          <SectionHead
            eyebrow={`More ${v.body}s`}
            title="Other cars you might consider."
            actions={<Btn variant="ghost" icon="arrow-right" onClick={() => setRoute('buy')}>All inventory</Btn>}
          />
          <div style={{
            display: 'grid',
            gridTemplateColumns: window.innerWidth > 1100 ? 'repeat(4, 1fr)' : window.innerWidth > 700 ? 'repeat(2, 1fr)' : '1fr',
            gap: 20,
          }}>
            {similar.map(s => (
              <VehicleCard key={s.id} v={s} onClick={() => { setVehicleId(s.id); window.scrollTo({top:0}); }} />
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}

function crumbBtn() {
  return {
    background: 'none', border: 'none', color: 'inherit', fontSize: 12, cursor: 'pointer', padding: 0,
  };
}

function pillStyle(bg, fg) {
  return {
    background: bg, color: fg,
    padding: '5px 12px', borderRadius: 999,
    fontFamily: 'var(--f-display)', fontSize: 11, fontWeight: 500,
    letterSpacing: '0.06em', textTransform: 'uppercase',
    backdropFilter: 'blur(4px)',
    display: 'inline-flex', alignItems: 'center', gap: 5,
  };
}

function iconCircle() {
  return {
    width: 40, height: 40, borderRadius: '50%',
    background: 'rgba(255,255,255,0.92)', border: 'none',
    color: 'var(--ink)',
    display: 'grid', placeItems: 'center', cursor: 'pointer',
    backdropFilter: 'blur(8px)',
  };
}

function TabSpecs({ v }) {
  const rows = [
    ['Make', v.make],
    ['Model', v.model],
    ['Variant', v.variant],
    ['Year', v.year],
    ['Body type', v.body],
    ['Mileage', fmtMileage(v.mileage)],
    ['Exterior colour', v.ext],
    ['Interior', v.intC],
    ['Engine', v.engine],
    ['Power output', v.power],
    ['Transmission', v.trans],
    ['Drivetrain', v.drive],
    ['Stock ID', v.stockId],
    ['VIN', 'WDD2050651F••••••'],
    ['Registration', 'Dubai · Private'],
    ['Owners', '1 previous'],
  ];
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: window.innerWidth > 700 ? '1fr 1fr' : '1fr', columnGap: 40 }}>
        {rows.map(([k, val]) => (
          <div key={k} style={{
            display: 'grid', gridTemplateColumns: '140px 1fr',
            gap: 16, padding: '14px 0',
            borderBottom: '1px solid var(--border)',
            fontSize: 14,
          }}>
            <span style={{ color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.1em', fontSize: 11 }}>{k}</span>
            <span className={typeof val === 'string' && /^[A-Z0-9\-•]+$/.test(val) ? 'mono' : ''}>{val}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function TabInspection({ v }) {
  const cats = [
    { t: 'Engine & Drivetrain', n: 38, p: 38 },
    { t: 'Transmission', n: 24, p: 24 },
    { t: 'Body & Paint', n: 32, p: 31, note: 'Minor stone chip on front bumper — re-touched' },
    { t: 'Electronics & ADAS', n: 28, p: 28 },
    { t: 'Suspension & Brakes', n: 18, p: 18 },
    { t: 'Interior & Comfort', n: 14, p: 14 },
  ];
  return (
    <div>
      <p style={{ fontSize: 16, lineHeight: 1.6, color: 'var(--text-muted)', maxWidth: 640 }}>
        Inspected on <span className="mono" style={{ color: 'var(--text)' }}>2026-05-18</span> by senior technician <span style={{ color: 'var(--text)' }}>R. Nair</span>.
        154 points checked, 153 passed, 1 noted (cosmetic). Full digital report below.
      </p>
      <div style={{ marginTop: 28, display: 'flex', flexDirection: 'column', gap: 0 }}>
        {cats.map(c => (
          <div key={c.t} style={{ display: 'grid', gridTemplateColumns: '1fr auto 110px', gap: 18, padding: '18px 0', borderTop: '1px solid var(--border)', alignItems: 'center' }}>
            <div>
              <div className="display" style={{ fontSize: 17, letterSpacing: '-0.015em' }}>{c.t}</div>
              {c.note && <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 4 }}>{c.note}</div>}
            </div>
            <div style={{ width: 200, height: 6, borderRadius: 999, background: 'var(--border)', overflow: 'hidden' }}>
              <div style={{
                width: `${(c.p/c.n)*100}%`, height: '100%',
                background: c.p === c.n ? '#2ECC71' : 'var(--gold)',
              }} />
            </div>
            <div className="mono" style={{ textAlign: 'right', fontSize: 13 }}>
              <span style={{ color: c.p === c.n ? '#2ECC71' : 'var(--gold)' }}>{c.p}</span>
              <span style={{ color: 'var(--text-muted)' }}>/{c.n} pass</span>
            </div>
          </div>
        ))}
      </div>
      <div style={{ marginTop: 32, padding: 20, background: 'var(--surface-2)', borderRadius: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
        <div>
          <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>Full report</div>
          <div className="display" style={{ fontSize: 20, marginTop: 4 }}>154-point inspection PDF</div>
        </div>
        <Btn variant="dark" icon="arrow-up-right">Download report</Btn>
      </div>
    </div>
  );
}

function TabHistory({ v }) {
  const timeline = [
    { d: '2022-03', t: 'First registered', sub: 'Dubai, UAE — Private use' },
    { d: '2023-04', t: 'Service · 15,000 km', sub: 'Authorized dealer · oil, filters, brake fluid' },
    { d: '2024-06', t: 'Service · 30,000 km', sub: 'Authorized dealer · major service, brake pads' },
    { d: '2026-05', t: 'Acquired by Alba Cars', sub: '154-point inspection passed · Listed on showroom floor' },
  ];
  return (
    <div>
      <p style={{ fontSize: 16, lineHeight: 1.6, color: 'var(--text-muted)', maxWidth: 640 }}>
        Single owner, GCC-spec, full service history at authorized dealer. No accidents recorded against the VIN.
      </p>
      <div style={{ marginTop: 32, position: 'relative', paddingLeft: 30 }}>
        <div style={{ position: 'absolute', left: 8, top: 8, bottom: 8, width: 1, background: 'var(--border)' }} />
        {timeline.map((item, i) => (
          <div key={i} style={{ position: 'relative', paddingBottom: 28 }}>
            <div style={{
              position: 'absolute', left: -27, top: 4,
              width: 16, height: 16, borderRadius: '50%',
              background: i === timeline.length - 1 ? 'var(--alba-red)' : 'var(--surface)',
              border: '2px solid ' + (i === timeline.length - 1 ? 'var(--alba-red)' : 'var(--border)'),
            }} />
            <div className="mono" style={{ fontSize: 12, color: 'var(--text-muted)' }}>{item.d}</div>
            <div className="display" style={{ fontSize: 17, marginTop: 4, letterSpacing: '-0.015em' }}>{item.t}</div>
            <div style={{ fontSize: 14, color: 'var(--text-muted)', marginTop: 4 }}>{item.sub}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function TabFeatures({ v }) {
  const groups = [
    { t: 'Performance', items: ['Adaptive Damping', 'Sport Exhaust', 'Launch Control', 'Drive Mode Select', 'Limited-Slip Differential'] },
    { t: 'Comfort', items: ['Heated & Ventilated Seats', '4-Zone Climate', 'Memory Seats', 'Panoramic Roof', 'Soft-Close Doors'] },
    { t: 'Technology', items: ['Heads-Up Display', '360° Camera', 'Wireless CarPlay', 'Burmester Sound', 'Digital Cockpit'] },
    { t: 'Safety', items: ['Adaptive Cruise', 'Lane Keep Assist', 'Blind Spot Monitor', 'Pre-Collision', 'Surround Airbags'] },
  ];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: window.innerWidth > 700 ? 'repeat(2, 1fr)' : '1fr', gap: 28 }}>
      {groups.map(g => (
        <div key={g.t}>
          <div className="display" style={{ fontSize: 18, letterSpacing: '-0.015em', paddingBottom: 12, borderBottom: '1px solid var(--border)' }}>{g.t}</div>
          <ul style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
            {g.items.map(it => (
              <li key={it} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 14 }}>
                <span style={{ color: 'var(--alba-red)' }}><Icon name="check" size={14} /></span>
                {it}
              </li>
            ))}
          </ul>
        </div>
      ))}
    </div>
  );
}

function EnquiryPanel({ v, setRoute }) {
  const [name, setName] = useStateV('');
  const [phone, setPhone] = useStateV('');
  const [intent, setIntent] = useStateV('request-price');
  const [submitted, setSubmitted] = useStateV(false);
  const isPOA = v.price == null;

  const intents = [
    { id: 'request-price', label: 'Request price' },
    { id: 'book-viewing', label: 'Book viewing' },
    { id: 'trade-in', label: 'Trade-in' },
    { id: 'finance', label: 'Finance' },
  ];

  if (submitted) {
    return (
      <div style={{ background: 'var(--noir)', color: '#fff', borderRadius: 14, padding: 36, textAlign: 'center' }}>
        <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--alba-red)', margin: '0 auto', display: 'grid', placeItems: 'center' }}>
          <Icon name="check" size={28} />
        </div>
        <h3 className="display" style={{ marginTop: 18, fontSize: 22, color: '#fff' }}>Got it — we'll be in touch.</h3>
        <p style={{ marginTop: 10, fontSize: 14, color: 'var(--muted-dk)' }}>
          A specialist will reach out about the {v.year} {v.model} within 30 minutes during showroom hours.
        </p>
        <div style={{ marginTop: 22 }}>
          <Btn variant="light" icon="whatsapp">Continue on WhatsApp</Btn>
        </div>
      </div>
    );
  }

  return (
    <div style={{
      background: 'var(--surface)', border: '1px solid var(--border)',
      borderRadius: 14, overflow: 'hidden',
    }}>
      <div style={{ padding: 28, borderBottom: '1px solid var(--border)' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 11, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.12em' }}>
              {isPOA ? 'Price on Application' : 'Demo price'}
            </div>
            <div className="mono" style={{ fontSize: 30, fontWeight: 600, marginTop: 4, letterSpacing: '-0.01em' }}>
              {fmtAED(v.price)}
            </div>
          </div>
          {!isPOA && (
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 10, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.12em' }}>From / mo</div>
              <div className="mono" style={{ fontSize: 16, marginTop: 4 }}>
                AED {Math.round(v.price / 60).toLocaleString()}
              </div>
            </div>
          )}
        </div>
        {!isPOA && (
          <div style={{ marginTop: 14, fontSize: 12, color: 'var(--text-muted)' }}>
            Finance from <span className="mono" style={{ color: 'var(--text)' }}>2.99%</span> reducing · 60-mo · 20% down
          </div>
        )}
      </div>

      <div style={{ padding: 28 }}>
        <div style={{ display: 'flex', gap: 6, marginBottom: 22, flexWrap: 'wrap' }}>
          {intents.map(it => (
            <button key={it.id} onClick={() => setIntent(it.id)} style={{
              padding: '7px 11px', borderRadius: 6,
              border: '1px solid ' + (intent === it.id ? 'var(--text)' : 'var(--border)'),
              background: intent === it.id ? 'var(--text)' : 'transparent',
              color: intent === it.id ? 'var(--bg)' : 'var(--text)',
              fontFamily: 'var(--f-display)', fontSize: 11.5, fontWeight: 500,
              letterSpacing: '0.04em', cursor: 'pointer',
            }}>{it.label}</button>
          ))}
        </div>

        <form onSubmit={e => { e.preventDefault(); setSubmitted(true); }} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <input className="input" placeholder="Your name" value={name} onChange={e => setName(e.target.value)} required />
          <input className="input" type="tel" placeholder="Phone / WhatsApp" value={phone} onChange={e => setPhone(e.target.value)} required />
          <textarea className="textarea" rows={3} placeholder={`Pre-filled: Interested in ${v.year} ${v.model} ${v.variant} (${v.stockId})`} defaultValue={`Hi, I'm interested in the ${v.year} ${v.make} ${v.model} ${v.variant} — ${v.stockId}. Please get in touch.`} />

          <Btn variant="primary" icon="arrow-right" type="submit" style={{ width: '100%', justifyContent: 'center' }}>
            {intent === 'request-price' ? 'Request Price' : intent === 'book-viewing' ? 'Book Viewing' : intent === 'trade-in' ? 'Trade-In My Car' : 'Check Eligibility'}
          </Btn>
        </form>

        <div style={{ marginTop: 20, paddingTop: 20, borderTop: '1px solid var(--border)', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          <a href="https://wa.me/97143772503" target="_blank" rel="noopener" style={{
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            padding: '13px 14px', borderRadius: 999, background: '#25D366', color: '#fff',
            fontFamily: 'var(--f-display)', fontSize: 12.5, fontWeight: 500,
            letterSpacing: '0.04em', textTransform: 'uppercase',
          }}>
            <Icon name="whatsapp" size={14} /> WhatsApp
          </a>
          <a href="tel:+97143772503" style={{
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            padding: '13px 14px', borderRadius: 999, border: '1px solid var(--border)', color: 'var(--text)',
            fontFamily: 'var(--f-display)', fontSize: 12.5, fontWeight: 500,
            letterSpacing: '0.04em', textTransform: 'uppercase',
          }}>
            <Icon name="phone" size={14} /> Call
          </a>
        </div>
      </div>

      {/* Trust footer */}
      <div style={{ background: 'var(--surface-2)', padding: 22, display: 'flex', flexDirection: 'column', gap: 12 }}>
        {[
          { i: 'shield', t: '150+ point inspection passed' },
          { i: 'check', t: 'RTA certified · paperwork in-house' },
          { i: 'sparkle', t: '1-year free warranty included' },
          { i: 'truck', t: 'UAE-wide delivery available' },
        ].map(x => (
          <div key={x.t} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13 }}>
            <span style={{ color: 'var(--alba-red)' }}><Icon name={x.i} size={14} /></span> {x.t}
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { VehiclePage });
