/* Shared components: Nav, Footer, VehicleCard, LeadModal, icons */

const { useState, useEffect, useRef, useMemo, useCallback } = React;

/* ---------- inline icons (no emoji) ---------- */
const Icon = {
  arrow: (p) => (
    <svg width="14" height="10" viewBox="0 0 14 10" fill="none" {...p}>
      <path d="M1 5h12M9 1l4 4-4 4" stroke="currentColor" strokeWidth="1" />
    </svg>
  ),
  wa: (p) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" {...p}>
      <path d="M17.5 14.4l-2.1-1c-.3-.1-.6-.1-.8.1l-.9.9c-.2.2-.5.3-.8.1-1.1-.5-2.1-1.4-3-2.6-.2-.3-.2-.6 0-.8l.7-.8c.2-.2.2-.5.1-.8l-.9-2c-.2-.4-.7-.6-1.1-.4-.7.3-1.5.9-1.7 1.7-.4 1.5.2 3.2 2 5.4s3.9 3.3 5.4 2.9c.8-.2 1.4-1 1.6-1.7.2-.4 0-.9-.5-1zM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.5 1.3 5L2 22l5-1.3c1.5.8 3.2 1.3 5 1.3 5.5 0 10-4.5 10-10S17.5 2 12 2z"/>
    </svg>
  ),
  phone: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" {...p}>
      <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/>
    </svg>
  ),
  spark: (p) => (
    <svg width="14" height="14" viewBox="0 0 14 14" fill="none" {...p}>
      <path d="M7 1l1.5 4L13 7l-4.5 2L7 13 5.5 9 1 7l4.5-2L7 1z" stroke="currentColor" strokeWidth=".9" fill="none"/>
    </svg>
  ),
  close: (p) => (
    <svg width="14" height="14" viewBox="0 0 14 14" {...p}>
      <path d="M1 1l12 12M13 1L1 13" stroke="currentColor" strokeWidth="1" />
    </svg>
  ),
  search: (p) => (
    <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.2" {...p}>
      <circle cx="6" cy="6" r="4.5"/><path d="M9.5 9.5L13 13"/>
    </svg>
  ),
  check: (p) => (
    <svg width="12" height="10" viewBox="0 0 12 10" fill="none" stroke="currentColor" strokeWidth="1.4" {...p}>
      <path d="M1 5l3.5 3.5L11 1.5"/>
    </svg>
  ),
  diamond: (p) => (
    <svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" strokeWidth="1" {...p}>
      <path d="M5 .5L9.5 5 5 9.5.5 5z"/>
    </svg>
  ),
};

/* ---------- logo wordmark ---------- */
function Logo({ size = 19 }) {
  return (
    <div className="logo">
      <div className="logo__crest" aria-hidden="true"><span>E</span></div>
      <div className="logo__word" style={{ fontSize: size }}>
        THE <i>Elite</i> CARS
      </div>
    </div>
  );
}

/* ---------- top notice ticker ---------- */
function TopNotice({ items }) {
  return (
    <div className="topnotice">
      {items.map((t, i) => (
        <React.Fragment key={i}>
          <span>{t}</span>
          {i < items.length - 1 && <span className="dot">◆</span>}
        </React.Fragment>
      ))}
    </div>
  );
}

/* ---------- navbar ---------- */
function Navbar({ route, go, locale, setLocale, openLead }) {
  const t = I18N[locale];
  const links = [
    ['home', 'Home'],
    ['inventory', t.nav.inventory],
    ['vehicle', t.nav.approved],
    ['services', t.nav.services],
    ['export', t.nav.export],
    ['contact', t.nav.contact],
  ];
  return (
    <header className="nav">
      <div className="wrap nav__inner">
        <a className="logo-link" onClick={() => go('home')} style={{ cursor: 'pointer' }}>
          <Logo />
        </a>
        <nav className="nav__links">
          {links.map(([key, label]) => (
            <a key={key} className={'nav__link ' + (route === key ? 'active' : '')} onClick={() => go(key)}>
              {label}
            </a>
          ))}
        </nav>
        <div className="nav__cta">
          <div className="nav__locale">
            <button className={locale === 'en' ? 'active' : ''} onClick={() => setLocale('en')}>EN</button>
            <span>/</span>
            <button className={locale === 'ar' ? 'active' : ''} onClick={() => setLocale('ar')}>AR</button>
          </div>
          <button className="btn btn--accent btn--sm" onClick={() => openLead({ kind: 'enquire' })}>
            {t.nav.enquire}<Icon.arrow />
          </button>
        </div>
      </div>
    </header>
  );
}

/* ---------- footer ---------- */
function Footer({ go, locale }) {
  const t = I18N[locale];
  return (
    <footer className="footer dark-always">
      <div className="wrap">
        <div className="footer__grid">
          <div className="footer__brand">
            <h3>THE <em style={{fontFamily:'Cormorant Garamond',fontStyle:'italic',color:'#C7AE7E'}}>Elite</em> CARS</h3>
            <p>A multi-brand luxury & exotic car showroom — a subsidiary of Elite Group Holding, Dubai-headquartered with operations across the UAE.</p>
            <div style={{display:'flex',gap:10,alignItems:'center'}}>
              <a className="btn btn--ghost btn--sm" href="tel:800354832277" style={{borderColor:'#3A3F46',color:'#F2EFE7'}}><Icon.phone /> 800-ELITE-CARS</a>
              <a className="btn btn--sm" href="https://wa.me/971800354832277" style={{borderColor:'#25D366',color:'#25D366'}}><Icon.wa /> WhatsApp</a>
            </div>
          </div>
          <div>
            <h5>Inventory</h5>
            <ul>
              <li><a onClick={() => go('inventory')}>All Vehicles</a></li>
              <li><a>Hypercars</a></li>
              <li><a>Luxury Sedans</a></li>
              <li><a>SUVs</a></li>
              <li><a>Electric & Hybrid</a></li>
            </ul>
          </div>
          <div>
            <h5>Services</h5>
            <ul>
              <li><a>Elite Approved</a></li>
              <li><a>Finance & Leasing</a></li>
              <li><a>Trade-in</a></li>
              <li><a>Worldwide Export</a></li>
              <li><a>Service Centre</a></li>
            </ul>
          </div>
          <div>
            <h5>Brands</h5>
            <ul>
              {BRANDS.slice(0, 6).map((b) => <li key={b}><a>{b}</a></li>)}
              <li><a>Lynk & Co (UAE)</a></li>
            </ul>
          </div>
          <div>
            <h5>Visit</h5>
            <ul>
              <li><a>Dubai — Al Quoz</a></li>
              <li><a>Dubai — SZR</a></li>
              <li><a>Sharjah</a></li>
              <li><a>Abu Dhabi — Flagship</a></li>
              <li><a onClick={() => go('contact')}>Contact</a></li>
            </ul>
          </div>
        </div>
        <div className="footer__disclaimer">
          The Elite Cars is not endorsed by, directly affiliated with, maintained or sponsored by any car manufacturer.
          All trademarks and brand names are property of their respective owners. {t.archive}
        </div>
        <div className="footer__bottom">
          <span>© The Elite Cars · Elite Group Holding · ADGM-Registered</span>
          <span>customer-care@theelitecars.com · sales-product@theelitecars.com</span>
        </div>
      </div>
    </footer>
  );
}

/* ---------- floating action stack (always visible) ---------- */
function FabStack() {
  return (
    <div className="fab-stack">
      <a className="fab fab--wa" href="https://wa.me/971800354832277" aria-label="WhatsApp"><Icon.wa /></a>
      <a className="fab" href="tel:800354832277" aria-label="Call"><Icon.phone /></a>
    </div>
  );
}

/* ---------- vehicle card ---------- */
function VehicleCard({ v, onOpen, locale }) {
  const t = I18N[locale];
  return (
    <article
      className="vcard"
      onClick={() => onOpen(v.id)}
      style={{
        cursor: 'pointer',
        background: 'var(--surface)',
        border: '1px solid var(--line)',
        display: 'flex',
        flexDirection: 'column',
        transition: 'border-color .2s, transform .25s',
      }}
      onMouseEnter={(e) => (e.currentTarget.style.borderColor = 'var(--accent)')}
      onMouseLeave={(e) => (e.currentTarget.style.borderColor = 'var(--line)')}
    >
      <div style={{ position: 'relative', aspectRatio: '4/3', overflow: 'hidden', background: 'var(--surface-2)' }}>
        <img src={v.photos[0]} alt={`${v.year} ${v.make} ${v.model}`}
          style={{ width: '100%', height: '100%', objectFit: 'cover', transition: 'transform .6s' }}
          onMouseEnter={(e) => (e.currentTarget.style.transform = 'scale(1.04)')}
          onMouseLeave={(e) => (e.currentTarget.style.transform = 'scale(1)')}
        />
        {v.certified && (
          <div style={{
            position: 'absolute', top: 14, left: 14,
            padding: '4px 10px', background: 'rgba(11,13,15,.78)', backdropFilter: 'blur(6px)',
            border: '1px solid var(--accent-dim)', color: 'var(--accent-soft)',
            fontFamily: 'var(--font-mono)', fontSize: 9.5, letterSpacing: '.18em', textTransform: 'uppercase',
          }}>
            Elite Approved
          </div>
        )}
        <div style={{
          position: 'absolute', top: 14, right: 14,
          fontFamily: 'var(--font-mono)', fontSize: 10, color: '#F2EFE7',
          background: 'rgba(11,13,15,.6)', backdropFilter: 'blur(6px)',
          padding: '4px 10px', letterSpacing: '.14em',
        }}>{v.stock}</div>
      </div>

      <div style={{ padding: '20px 22px 22px', display: 'flex', flexDirection: 'column', gap: 14, flex: 1 }}>
        <div>
          <div className="mono" style={{ color: 'var(--muted)', marginBottom: 6 }}>{v.year} · {v.body}</div>
          <h3 className="h-display" style={{ fontSize: 24, margin: 0, fontWeight: 400 }}>
            {v.make} <em style={{ color: 'var(--accent)', fontStyle: 'italic', fontWeight: 300 }}>{v.model}</em>
          </h3>
          <div style={{ color: 'var(--text-dim)', fontSize: 13, marginTop: 4 }}>{v.trim}</div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, fontSize: 12, color: 'var(--text-dim)' }}>
          <div><span className="mono" style={{ display: 'block', color: 'var(--muted)', marginBottom: 2 }}>Mileage</span>{v.mileage.toLocaleString()} km</div>
          <div><span className="mono" style={{ display: 'block', color: 'var(--muted)', marginBottom: 2 }}>Engine</span>{v.engine.split(' ').slice(0, 2).join(' ')}</div>
        </div>

        <div style={{ marginTop: 'auto', display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingTop: 12, borderTop: '1px solid var(--line)' }}>
          <div>
            <div className="mono" style={{ color: 'var(--muted)', fontSize: 9.5 }}>{t.poa}</div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, color: 'var(--accent)', letterSpacing: '.04em' }}>POA</div>
          </div>
          <a className="link-arrow" style={{ borderBottom: 'none' }}>View <Icon.arrow /></a>
        </div>
      </div>
    </article>
  );
}

/* ---------- lead modal ---------- */
function LeadModal({ open, onClose, ctx, locale }) {
  const t = I18N[locale];
  const [stage, setStage] = useState('form'); // form | success
  const [intent, setIntent] = useState(ctx?.kind || 'enquire');

  useEffect(() => {
    if (open) {
      setStage('form');
      setIntent(ctx?.kind || 'enquire');
    }
  }, [open, ctx]);

  if (!open) return null;

  const labels = {
    enquire: 'General Enquiry',
    price: 'Request Price',
    viewing: 'Book a Viewing',
    tradein: 'Trade-in Valuation',
    finance: 'Finance Enquiry',
    export: 'Export Enquiry',
  };

  const vehicleLine = ctx?.vehicle
    ? `${ctx.vehicle.year} ${ctx.vehicle.make} ${ctx.vehicle.model} ${ctx.vehicle.trim} · Stock ${ctx.vehicle.stock}`
    : null;

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(11,13,15,.74)', zIndex: 100,
      display: 'grid', placeItems: 'center', padding: 20, backdropFilter: 'blur(6px)',
      animation: 'fadeUp .3s',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: 'var(--surface)', color: 'var(--text)', width: 'min(720px, 100%)',
        border: '1px solid var(--line-2)', maxHeight: '92vh', overflow: 'auto',
      }}>
        {/* header */}
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', padding: '28px 32px', borderBottom: '1px solid var(--line)' }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 8 }}>The Elite Cars · Concierge</div>
            <h3 className="h-display" style={{ margin: 0, fontSize: 28, fontWeight: 400 }}>
              {stage === 'success' ? <>Thank <em style={{color:'var(--accent)',fontStyle:'italic',fontWeight:300}}>you.</em></> : <>{labels[intent]}</>}
            </h3>
          </div>
          <button onClick={onClose} aria-label="Close" style={{ color: 'var(--muted)', padding: 6 }}><Icon.close /></button>
        </div>

        {stage === 'form' ? (
          <form
            onSubmit={(e) => { e.preventDefault(); setStage('success'); }}
            style={{ padding: '24px 32px 32px', display: 'flex', flexDirection: 'column', gap: 22 }}
          >
            {/* intent toggle */}
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {Object.entries(labels).map(([k, v]) => (
                <button key={k} type="button" onClick={() => setIntent(k)}
                  style={{
                    padding: '8px 14px', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.14em', textTransform: 'uppercase',
                    border: '1px solid ' + (intent === k ? 'var(--accent)' : 'var(--line)'),
                    color: intent === k ? 'var(--accent)' : 'var(--text-dim)',
                    background: intent === k ? 'color-mix(in srgb, var(--accent) 8%, transparent)' : 'transparent',
                    transition: 'all .2s',
                  }}>
                  {v}
                </button>
              ))}
            </div>

            {vehicleLine && (
              <div style={{ padding: '14px 16px', background: 'var(--surface-2)', border: '1px solid var(--line)', display: 'flex', gap: 12, alignItems: 'center' }}>
                <div style={{ color: 'var(--accent)' }}><Icon.diamond /></div>
                <div>
                  <div className="mono" style={{ color: 'var(--muted)', marginBottom: 2 }}>Vehicle</div>
                  <div style={{ fontSize: 14 }}>{vehicleLine}</div>
                </div>
              </div>
            )}

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <Field label="Full Name" defaultValue="" required />
              <Field label="Phone" type="tel" required />
              <Field label="Email" type="email" required />
              <Field label="Preferred Contact" tag="select" options={['WhatsApp', 'Phone Call', 'Email']} />
              {intent === 'tradein' && <>
                <Field label="Your Car · Make" />
                <Field label="Your Car · Model & Year" />
              </>}
              {intent === 'export' && <>
                <Field label="Destination Country" />
                <Field label="Port / City" />
              </>}
              {intent === 'finance' && <>
                <Field label="Budget Range" tag="select" options={['AED 200k–500k', 'AED 500k–1M', 'AED 1M–2M', 'AED 2M+']} />
                <Field label="Preferred Tenor" tag="select" options={['12 months', '24 months', '36 months', '48 months', '60 months']} />
              </>}
            </div>

            <Field label="Message" tag="textarea" rows={4} defaultValue={vehicleLine ? `Hi, I'm interested in the ${vehicleLine}. Please send details.` : ''} />

            <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
              <button type="submit" className="btn btn--accent">Send Enquiry<Icon.arrow /></button>
              <a className="btn" href="https://wa.me/971800354832277" style={{ borderColor: '#25D366', color: '#25D366' }}>
                <Icon.wa /> Or WhatsApp
              </a>
              <span style={{ fontSize: 11, color: 'var(--muted)', flex: 1 }}>
                We'll respond within 2 business hours. By submitting you agree to be contacted by The Elite Cars concierge team.
              </span>
            </div>
          </form>
        ) : (
          <div style={{ padding: '32px', display: 'flex', flexDirection: 'column', gap: 18, alignItems: 'flex-start' }}>
            <div style={{ width: 48, height: 48, border: '1px solid var(--accent)', display: 'grid', placeItems: 'center', color: 'var(--accent)' }}>
              <Icon.check />
            </div>
            <p style={{ margin: 0, fontSize: 18, lineHeight: 1.5, maxWidth: 500 }}>
              Your enquiry has been received. A member of the Elite concierge team will be in touch within two business hours.
              {vehicleLine && <><br/><span style={{color:'var(--text-dim)',fontSize:14}}>Reference: {vehicleLine}</span></>}
            </p>
            <div style={{ display: 'flex', gap: 12, marginTop: 8 }}>
              <a className="btn" href="https://wa.me/971800354832277" style={{ borderColor: '#25D366', color: '#25D366' }}><Icon.wa /> WhatsApp Us</a>
              <button className="btn btn--ghost" onClick={onClose}>Close</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function Field({ label, tag = 'input', options, rows = 3, ...rest }) {
  const baseStyle = {
    width: '100%', padding: '12px 0', background: 'transparent', border: 'none',
    borderBottom: '1px solid var(--line-2)', color: 'var(--text)', fontSize: 14,
    outline: 'none', transition: 'border-color .2s',
  };
  const onFocus = (e) => (e.target.style.borderBottomColor = 'var(--accent)');
  const onBlur = (e) => (e.target.style.borderBottomColor = 'var(--line-2)');
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      <span className="mono" style={{ color: 'var(--muted)' }}>{label}</span>
      {tag === 'input' && <input style={baseStyle} onFocus={onFocus} onBlur={onBlur} {...rest} />}
      {tag === 'select' && (
        <select style={baseStyle} onFocus={onFocus} onBlur={onBlur} {...rest}>
          <option>—</option>
          {options.map((o) => <option key={o} style={{background:'var(--surface)',color:'var(--text)'}}>{o}</option>)}
        </select>
      )}
      {tag === 'textarea' && <textarea style={{ ...baseStyle, resize: 'vertical' }} rows={rows} onFocus={onFocus} onBlur={onBlur} {...rest} />}
    </label>
  );
}

/* ---------- archival pill (re-usable) ---------- */
function ArchivePill() {
  return (
    <div className="archive-pill">
      <span className="dot-amber"/>
      Demo build · archival photography · live inventory consumed from feed
    </div>
  );
}

Object.assign(window, {
  Icon, Logo, TopNotice, Navbar, Footer, FabStack, VehicleCard, LeadModal, Field, ArchivePill,
});
