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

/* ============================================================
   Icons (inline SVGs — minimal, monoline)
   ============================================================ */
const Icon = ({ name, size = 14 }) => {
  const paths = {
    arrow: "M5 12h14M13 6l6 6-6 6",
    phone: "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-6A19.79 19.79 0 0 1 2.13 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 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-.45c.91.34 1.85.57 2.81.7a2 2 0 0 1 1.72 2.03z",
    whatsapp: "M17.5 14.4c-.3-.1-1.6-.8-1.9-.9-.3-.1-.5-.1-.6.1-.2.3-.7.9-.9 1.1-.2.2-.3.2-.6.1-1.7-.9-2.9-1.6-4-3.5-.3-.5.3-.5.8-1.5.1-.2 0-.4 0-.5-.1-.1-.6-1.4-.8-1.9-.2-.5-.4-.4-.6-.4h-.5c-.2 0-.5.1-.7.4-.3.3-1 .9-1 2.3 0 1.4 1 2.7 1.1 2.8.1.2 2 3.1 4.9 4.3 1.8.7 2.5.8 3.4.7.5-.1 1.6-.7 1.9-1.3.2-.7.2-1.2.2-1.3-.1-.1-.3-.2-.6-.3zM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.5 1.3 5L2 22l5.2-1.4c1.4.8 3 1.2 4.8 1.2 5.5 0 10-4.5 10-10S17.5 2 12 2z",
    mail: "M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2zM22 6l-10 7L2 6",
    pin: "M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0zM12 13a3 3 0 1 0 0-6 3 3 0 0 0 0 6z",
    close: "M18 6L6 18M6 6l12 12",
    search: "M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16zm10 2l-4.35-4.35",
    ship: "M2 20h20M3 16l9-9 9 9M5 16V8h4l3-3 3 3h4v8",
    sell: "M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7.5M16 8l-4-4-4 4M12 4v12",
    plus: "M12 5v14M5 12h14",
    minus: "M5 12h14",
    fuel: "M3 22V6a3 3 0 0 1 3-3h6a3 3 0 0 1 3 3v16M3 22h12M5 11h8M17 7l3 3v9a2 2 0 0 1-2 2",
    gauge: "M12 22a10 10 0 1 0-10-10c0 2.5 1 4.8 2.6 6.4L12 12V2",
    palette: "M12 22a10 10 0 1 1 10-10c0 2.2-1.8 4-4 4h-2a2 2 0 0 0-2 2c0 1.1.9 2 2 2v2zM7 14a1 1 0 1 0 0-2 1 1 0 0 0 0 2zM10 8a1 1 0 1 0 0-2 1 1 0 0 0 0 2zM15 8a1 1 0 1 0 0-2 1 1 0 0 0 0 2z"
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{display: "block"}}>
      <path d={paths[name]} />
    </svg>
  );
};
window.Icon = Icon;

/* ============================================================
   Brand mark (the SVG-redrawn logo)
   ============================================================ */
const BrandMark = ({ dark = false }) => (
  <span className="nav-logo" aria-label="Al Ain Class Motors">
    <span className="mark" aria-hidden="true">A</span>
    <span className="name">
      <b>Alain Class</b>
      <span>Motors · Dubai</span>
    </span>
  </span>
);
window.BrandMark = BrandMark;

/* ============================================================
   NAV
   ============================================================ */
const Nav = ({ route, navigate, dark = false }) => {
  const links = [
    { id: "inventory", label: "Inventory" },
    { id: "brands",    label: "Brands" },
    { id: "sell",      label: "Sell your car" },
    { id: "export",    label: "Export" },
    { id: "about",     label: "About" },
    { id: "contact",   label: "Contact" },
  ];
  return (
    <nav className={"nav " + (dark ? "dark" : "")} data-screen-label="Global Nav">
      <div className="container nav-inner">
        <button className="nav-logo" onClick={() => navigate("home")} aria-label="Home">
          <span className="mark">A</span>
          <span className="name">
            <b>Alain Class</b>
            <span>Motors · Dubai</span>
          </span>
        </button>
        <div className="nav-links">
          {links.map(l => (
            <button key={l.id}
              className={"nav-link " + (route === l.id ? "active" : "")}
              onClick={() => navigate(l.id)}>{l.label}</button>
          ))}
        </div>
        <div className="nav-actions">
          <button className="lang-toggle" title="Language">
            <b>EN</b> · AR · RU · 中文
          </button>
          <a className={"btn btn-sm " + (dark ? "btn-ghost-light" : "")}
             href="tel:+97143782222"
             onClick={e => e.stopPropagation()}>
            <Icon name="phone" size={12} />
            +971 4 378 2222
          </a>
        </div>
      </div>
    </nav>
  );
};
window.Nav = Nav;

/* ============================================================
   CTA fab (WhatsApp + Call, always visible)
   ============================================================ */
const CtaFab = ({ onEnquire }) => (
  <div className="cta-fab">
    <button className="pill wa" onClick={onEnquire} title="WhatsApp — once supplied by client">
      <Icon name="whatsapp" size={14} />
      WhatsApp
    </button>
    <a className="pill" href="tel:+97143782222">
      <Icon name="phone" size={12} />
      Call
    </a>
  </div>
);
window.CtaFab = CtaFab;

/* ============================================================
   Vehicle card
   ============================================================ */
const VehicleCard = ({ v, onOpen, onDark = false }) => (
  <button className={"vcard " + (onDark ? "on-dark" : "")} onClick={() => onOpen(v)}>
    <div className="photo">
      <img src={v.photo} alt={`${v.make} ${v.model}`} loading="lazy" />
      <span className={"tag " + (v.condition === "new" ? "new" : "")}>
        {v.condition === "new" ? "New" : "Pre-owned"}
      </span>
      <span className="stockid">{v.stockId}</span>
    </div>
    <div className="info">
      <div className="yr">{v.year} · {v.make}</div>
      <h3 className="ttl">{v.model}</h3>
      <div className="spec tabular">
        <span><Icon name="gauge" size={12} />{v.mileage}</span>
        <span><Icon name="fuel" size={12} />{v.engine.split(" ").slice(0, 2).join(" ")}</span>
        <span><Icon name="palette" size={12} />{v.exterior.split(" ")[0]}</span>
      </div>
      <div className="row">
        <span className="poa">POA · Enquire</span>
        <span className="more">View <Icon name="arrow" size={12} /></span>
      </div>
    </div>
  </button>
);
window.VehicleCard = VehicleCard;

/* ============================================================
   Enquire / Request Price modal
   ============================================================ */
const EnquireModal = ({ open, onClose, vehicle, mode = "enquire" }) => {
  const [sent, setSent] = useState(false);
  const [form, setForm] = useState({ name: "", email: "", phone: "", country: "United Arab Emirates", notes: "" });
  useEffect(() => {
    if (open) { setSent(false); setForm(f => ({ ...f, notes: vehicle ? "I'd like more information on the " + vehicle.year + " " + vehicle.make + " " + vehicle.model + " (Stock " + vehicle.stockId + ")." : "" })); }
  }, [open, vehicle]);
  if (!open) return null;
  const titles = {
    enquire: { eyebrow: "Enquire", h: ["Speak with our", "concierge"] },
    price:   { eyebrow: "Request price", h: ["Receive a private", "valuation"] },
    export:  { eyebrow: "Export enquiry", h: ["Worldwide", "delivery"] },
    sell:    { eyebrow: "Sell your car", h: ["Trade with", "Alain Class"] },
    whatsapp:{ eyebrow: "WhatsApp", h: ["Reach us on", "WhatsApp"] },
  };
  const t = titles[mode] || titles.enquire;

  const submit = (e) => { e.preventDefault(); setSent(true); };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} role="dialog" aria-modal="true">
        <button className="modal-close" onClick={onClose} aria-label="Close">
          <Icon name="close" size={16} />
        </button>
        <aside className="modal-art" style={{
          backgroundImage: `url(${vehicle ? vehicle.photo : 'media/showroom.webp'})`
        }}>
          <div className="veil" />
          <div>
            <div className="car-meta">{vehicle ? (vehicle.year + " · " + vehicle.stockId) : "Al Ain Class Motors · Since 1995"}</div>
            {vehicle ? (
              <h3>{vehicle.make} <i>{vehicle.model}</i></h3>
            ) : (
              <h3>The world's most <i>exclusive</i><br/>automobile showroom.</h3>
            )}
          </div>
          <p className="quote">
            <i>"The best supercar dealership in the world."</i>
            <span>— BBC Top Gear, cited</span>
          </p>
        </aside>
        <div className="modal-form">
          {sent ? (
            <div className="modal-success">
              <div className="check">✓</div>
              <h2>Enquiry received.</h2>
              <p>A member of our concierge team will reply within one business hour.<br/>For urgent matters please call <b>+971 4 378 2222</b>.</p>
              <button className="btn btn-primary" onClick={onClose}>Close</button>
            </div>
          ) : (
            <>
              <div className="eyebrow" style={{marginBottom: 8}}>{t.eyebrow}</div>
              <h2>{t.h[0]} <span className="ital" style={{fontStyle:"italic", color:"var(--champagne-deep)"}}>{t.h[1]}</span></h2>
              <p className="lede">
                {mode === "export"
                  ? "Tell us where in the world you'd like the car delivered and we'll arrange logistics to any port or airport."
                  : "Prices are quoted on application. Share a few details and we'll respond personally with availability, full specification and a private viewing."}
              </p>
              <form onSubmit={submit}>
                <div className="field-row">
                  <div className="field"><label>Full name</label><input required value={form.name} onChange={e=>setForm({...form, name:e.target.value})}/></div>
                  <div className="field"><label>Phone</label><input required type="tel" placeholder="+971 …" value={form.phone} onChange={e=>setForm({...form, phone:e.target.value})}/></div>
                </div>
                <div className="field-row">
                  <div className="field"><label>Email</label><input required type="email" value={form.email} onChange={e=>setForm({...form, email:e.target.value})}/></div>
                  <div className="field"><label>{mode === "export" ? "Destination country" : "Country of residence"}</label>
                    <input value={form.country} onChange={e=>setForm({...form, country:e.target.value})}/></div>
                </div>
                {vehicle && (
                  <div className="field">
                    <label>Vehicle</label>
                    <input value={vehicle.year + " " + vehicle.make + " " + vehicle.model + "  ·  " + vehicle.stockId} readOnly style={{color: "var(--champagne-deep)", fontStyle: "italic"}}/>
                  </div>
                )}
                <div className="field"><label>Message</label>
                  <textarea rows={3} value={form.notes} onChange={e=>setForm({...form, notes:e.target.value})}/></div>
                <div style={{display:"flex", gap:10, marginTop:24, flexWrap:"wrap"}}>
                  <button type="submit" className="btn btn-gold">Send enquiry <Icon name="arrow" size={12} /></button>
                  <a href="tel:+97143782222" className="btn">
                    <Icon name="phone" size={12} /> Call instead
                  </a>
                </div>
                <p style={{fontSize:11, color:"var(--muted)", marginTop:20, lineHeight:1.6}}>
                  By submitting you agree to be contacted by Alain Class Motors. We never share data with third parties. WhatsApp handoff will be enabled once the client confirms a number.
                </p>
              </form>
            </>
          )}
        </div>
      </div>
    </div>
  );
};
window.EnquireModal = EnquireModal;

/* ============================================================
   Footer
   ============================================================ */
const Footer = ({ navigate }) => (
  <footer className="footer" data-screen-label="Footer">
    <div className="container">
      <div className="footer-top">
        <div className="footer-brand">
          <h3>Alain <i>Class</i> Motors</h3>
          <p>Dubai-headquartered luxury, exotic and classic car showroom and worldwide importer-exporter. Since 1995. Five branches across the U.A.E.</p>
          <div style={{display:"flex", gap:10, marginTop:24}}>
            <a className="btn btn-sm btn-ghost-light" href="tel:+97143782222"><Icon name="phone" size={12}/> +971 4 378 2222</a>
            <a className="btn btn-sm btn-ghost-light" href="mailto:info@alainclass.com"><Icon name="mail" size={12}/> Email</a>
          </div>
        </div>
        <div>
          <h4>Inventory</h4>
          <ul>
            <li><a onClick={()=>navigate("inventory")}>All vehicles</a></li>
            <li><a onClick={()=>navigate("inventory")}>New arrivals</a></li>
            <li><a onClick={()=>navigate("inventory")}>Pre-owned</a></li>
            <li><a onClick={()=>navigate("inventory")}>Sold archive</a></li>
            <li><a onClick={()=>navigate("brands")}>Browse by brand</a></li>
          </ul>
        </div>
        <div>
          <h4>Services</h4>
          <ul>
            <li><a onClick={()=>navigate("sell")}>Sell your car</a></li>
            <li><a onClick={()=>navigate("export")}>Worldwide export</a></li>
            <li><a onClick={()=>navigate("sell")}>Trade-in valuation</a></li>
            <li><a>After-sale concierge</a></li>
            <li><a>Sourcing on commission</a></li>
          </ul>
        </div>
        <div>
          <h4>Company</h4>
          <ul>
            <li><a onClick={()=>navigate("about")}>About / Heritage</a></li>
            <li><a onClick={()=>navigate("contact")}>Five branches</a></li>
            <li><a>News & events</a></li>
            <li><a>Press</a></li>
            <li><a>Careers</a></li>
          </ul>
        </div>
        <div>
          <h4>Languages</h4>
          <ul>
            <li><a><b>English</b> — current</a></li>
            <li><a>العربية · Arabic</a></li>
            <li><a>Русский · Russian</a></li>
            <li><a>中文 · Chinese</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 1995–2026 Alain Class Motors L.L.C.</span>
        <span className="disclaimer">
          Alain Class Motors is an independent multi-brand showroom and is not affiliated with, endorsed by, or sponsored by any of the vehicle manufacturers whose marks appear on this site. All trademarks are the property of their respective owners.
        </span>
        <span>TRN 100·XXXX·XXXX</span>
      </div>
    </div>
  </footer>
);
window.Footer = Footer;
