// Shared components for VIP Motors prototype
const { useState, useEffect, useRef, useMemo } = React;

// ── Logo ──────────────────────────────────────────────────────────
function Logo({ variant = "white", height = 28 }) {
  const src = variant === "white" ? "media/logo-white.webp" : "media/logo-dark.webp";
  return (
    <img
      src={src}
      alt="VIP Motors"
      style={{
        height: height,
        width: "auto",
        objectFit: "contain",
        // Logo files have black/dark padding around them — we want just the glyph
        mixBlendMode: variant === "white" ? "screen" : "normal"
      }}
    />
  );
}

// ── Icons (inline minimal SVG) ────────────────────────────────────
function Icon({ name, size = 16 }) {
  const s = size;
  const stroke = { fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (name) {
    case "arrow": return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M5 12h14M13 5l7 7-7 7"/></svg>;
    case "arrow-up-right": return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M7 17L17 7M8 7h9v9"/></svg>;
    case "close": return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M6 6l12 12M18 6L6 18"/></svg>;
    case "phone": return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><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>;
    case "whatsapp": return <svg width={s} height={s} viewBox="0 0 24 24" fill="currentColor"><path d="M19.05 4.91A9.9 9.9 0 0 0 12.05 2c-5.46 0-9.91 4.45-9.91 9.91 0 1.75.46 3.45 1.32 4.95L2.05 22l5.25-1.38a9.9 9.9 0 0 0 4.74 1.21h.01c5.46 0 9.91-4.45 9.91-9.91a9.8 9.8 0 0 0-2.91-7.01zM12.05 20.15a8.2 8.2 0 0 1-4.19-1.15l-.3-.18-3.12.82.83-3.04-.2-.31a8.2 8.2 0 0 1-1.26-4.39c0-4.54 3.7-8.24 8.24-8.24a8.2 8.2 0 0 1 5.83 2.42 8.2 8.2 0 0 1 2.41 5.83c0 4.54-3.7 8.24-8.24 8.24zm4.52-6.16c-.25-.12-1.47-.72-1.69-.81-.23-.08-.39-.12-.56.13-.16.25-.64.81-.78.97-.14.17-.29.19-.54.06-.25-.12-1.05-.39-2-1.23-.74-.66-1.23-1.47-1.38-1.72-.14-.25-.02-.39.11-.51.11-.11.25-.29.37-.43.12-.14.16-.25.25-.41.08-.17.04-.31-.02-.43-.06-.12-.56-1.34-.77-1.84-.2-.48-.41-.42-.56-.42l-.48-.01c-.17 0-.43.06-.65.31s-.86.84-.86 2.06.88 2.38 1 2.55c.12.17 1.74 2.66 4.22 3.73.59.26 1.05.41 1.41.52.59.19 1.13.16 1.56.1.48-.07 1.47-.6 1.67-1.18.21-.58.21-1.07.14-1.18-.06-.11-.22-.17-.46-.29z"/></svg>;
    case "mail": return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="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-2z"/><polyline points="22,6 12,13 2,6"/></svg>;
    case "pin": return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg>;
    case "menu": return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M3 7h18M3 12h18M3 17h18"/></svg>;
    case "filter": return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M22 3H2l8 9.46V19l4 2v-8.54L22 3z"/></svg>;
    case "back": return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M19 12H5M12 19l-7-7 7-7"/></svg>;
    case "share": return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.59 13.51l6.83 3.98M15.41 6.51l-6.82 3.98"/></svg>;
    case "heart": return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>;
    case "check": return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M20 6L9 17l-5-5"/></svg>;
    case "globe": return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>;
    case "camera": return <svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>;
    default: return null;
  }
}

// ── Navbar ────────────────────────────────────────────────────────
function Nav({ route, navigate, onEnquire, tweaks }) {
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [lang, setLang] = useState("EN");
  const onPaper = route === "sell" || route === "contact";

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const links = [
    { k: "inventory", label: "Inventory" },
    { k: "sell", label: "Sell / Trade-in" },
    { k: "finance", label: "Finance" },
    { k: "about", label: "About" },
    { k: "contact", label: "Contact" }
  ];

  const bg = scrolled || onPaper
    ? (onPaper ? "rgba(246,245,243,0.92)" : "rgba(11,12,14,0.82)")
    : "transparent";
  const color = onPaper ? "var(--ink-on-paper)" : "var(--text)";
  const borderB = scrolled || onPaper
    ? `1px solid ${onPaper ? "var(--rule)" : "var(--line)"}`
    : "1px solid transparent";

  return (
    <header
      className="nav-shell"
      style={{
        position: "fixed", top: 48, left: 0, right: 0, zIndex: 90,
        background: bg, color: color, borderBottom: borderB,
        backdropFilter: (scrolled || onPaper) ? "blur(14px) saturate(140%)" : "none",
        WebkitBackdropFilter: (scrolled || onPaper) ? "blur(14px) saturate(140%)" : "none",
        transition: "background 220ms, border-color 220ms, color 220ms"
      }}
    >
      <div className="wrap" style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "14px 0", gap: 24
      }}>
        <button
          onClick={() => navigate("home")}
          style={{ background: "none", border: 0, padding: 0, cursor: "pointer", display: "flex", alignItems: "center", gap: 12, color: "inherit" }}
          aria-label="VIP Motors home"
        >
          <Logo variant={onPaper ? "dark" : "white"} height={26} />
        </button>

        <nav style={{ display: "flex", alignItems: "center", gap: 28 }} className="nav-links">
          {links.map(l => (
            <button
              key={l.k}
              onClick={() => navigate(l.k)}
              style={{
                background: "none", border: 0, padding: "6px 0", cursor: "pointer",
                color: "inherit", opacity: route === l.k ? 1 : 0.72,
                fontSize: 13, letterSpacing: "0.06em", fontWeight: 500,
                position: "relative"
              }}
            >
              {l.label}
              {route === l.k && <span style={{
                position: "absolute", bottom: -4, left: 0, right: 0,
                height: 1, background: "var(--accent)"
              }} />}
            </button>
          ))}
        </nav>

        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <button
            onClick={() => setLang(lang === "EN" ? "AR" : lang === "AR" ? "RU" : lang === "RU" ? "ZH" : "EN")}
            style={{
              background: "none", border: 0, color: "inherit", cursor: "pointer",
              display: "flex", alignItems: "center", gap: 6, opacity: 0.8,
              fontSize: 11, letterSpacing: "0.2em", fontFamily: "var(--mono)"
            }}
            title="Language (demo)"
          >
            <Icon name="globe" size={14} />
            <span>{lang}</span>
          </button>
          <button className="btn btn-sm" onClick={onEnquire}>
            Enquire <Icon name="arrow" size={12} />
          </button>
        </div>
      </div>

      <style>{`
        @media (max-width: 900px) {
          .nav-links { display: none !important; }
        }
      `}</style>
    </header>
  );
}

// ── Vehicle Card ──────────────────────────────────────────────────
function VehicleCard({ v, onOpen, onEnquire, paper }) {
  return (
    <div className="vcard" onClick={() => onOpen(v.slug)}>
      <div className="vcard-img">
        <img src={v.images[0]} alt={`${v.year} ${v.make} ${v.model}`} loading="lazy" />
        {v.badges && v.badges.length > 0 && (
          <div style={{
            position: "absolute", top: 14, left: 14,
            display: "flex", gap: 6, flexWrap: "wrap"
          }}>
            {v.badges.slice(0, 2).map(b => (
              <span key={b} style={{
                fontFamily: "var(--mono)", fontSize: 10,
                letterSpacing: "0.18em", textTransform: "uppercase",
                padding: "4px 8px",
                background: b === "Limited" || b === "1 of 14" || b === "1 of 40" ? "var(--accent)" : "rgba(11,12,14,0.78)",
                color: "#fff",
                backdropFilter: "blur(6px)"
              }}>{b}</span>
            ))}
          </div>
        )}
      </div>
      <div style={{ paddingTop: 18, display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="num" style={{ fontSize: 11, color: paper ? "var(--muted-on-paper)" : "var(--text-muted)", letterSpacing: "0.12em" }}>
            {v.year} · {v.body}
          </div>
          <div className="serif" style={{ fontSize: 22, fontWeight: 500, marginTop: 4, lineHeight: 1.15 }}>
            {v.make} <span style={{ fontStyle: "italic" }}>{v.model}</span>
          </div>
          {v.headline && (
            <div style={{ fontSize: 12, marginTop: 6, color: paper ? "var(--muted-on-paper)" : "var(--text-muted)", letterSpacing: "0.04em" }}>
              {v.headline}
            </div>
          )}
        </div>
        <div className="vcard-cta" style={{
          fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.2em",
          textTransform: "uppercase", whiteSpace: "nowrap",
          opacity: 0.85, transition: "color 220ms",
          paddingTop: 4
        }}>
          Request price
        </div>
      </div>
    </div>
  );
}

// ── Modal ─────────────────────────────────────────────────────────
function Modal({ open, onClose, title, children }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);

  if (!open) return null;
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          padding: "18px 24px", borderBottom: "1px solid var(--line)"
        }}>
          <div className="eyebrow" style={{ color: "var(--text)" }}>{title}</div>
          <button onClick={onClose} aria-label="Close" style={{
            background: "none", border: 0, color: "var(--text-muted)", padding: 6
          }}>
            <Icon name="close" size={18} />
          </button>
        </div>
        <div style={{ padding: 24 }}>{children}</div>
      </div>
    </div>
  );
}

// ── Enquiry form ──────────────────────────────────────────────────
function EnquiryForm({ vehicle, type = "Enquire", onSubmitted }) {
  const [data, setData] = useState({ name: "", phone: "", email: "", message: "" });
  const [sent, setSent] = useState(false);
  const update = (k) => (e) => setData({ ...data, [k]: e.target.value });

  const onSubmit = (e) => {
    e.preventDefault();
    setSent(true);
    setTimeout(() => onSubmitted && onSubmitted(), 1600);
  };

  if (sent) {
    return (
      <div style={{ textAlign: "center", padding: "12px 0 4px" }}>
        <div style={{
          width: 56, height: 56, borderRadius: "50%",
          background: "var(--accent)", color: "#fff",
          display: "flex", alignItems: "center", justifyContent: "center",
          margin: "0 auto 18px"
        }}>
          <Icon name="check" size={28} />
        </div>
        <div className="serif" style={{ fontSize: 24, fontWeight: 500, marginBottom: 6 }}>
          Enquiry received.
        </div>
        <div style={{ color: "var(--text-muted)", fontSize: 14, maxWidth: 360, margin: "0 auto" }}>
          A specialist will respond within one business day, typically by WhatsApp.
        </div>
      </div>
    );
  }

  return (
    <form onSubmit={onSubmit} style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      {vehicle && (
        <div style={{
          padding: "12px 14px",
          background: "var(--noir)",
          border: "1px solid var(--line)",
          display: "flex", alignItems: "center", gap: 14
        }}>
          <img src={vehicle.images[0]} alt="" style={{ width: 64, height: 40, objectFit: "cover" }} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="num" style={{ fontSize: 10, color: "var(--text-muted)", letterSpacing: "0.16em" }}>
              {vehicle.year} · {type.toUpperCase()}
            </div>
            <div className="serif" style={{ fontSize: 16, fontWeight: 500 }}>
              {vehicle.make} <span style={{ fontStyle: "italic" }}>{vehicle.model}</span>
            </div>
          </div>
        </div>
      )}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <div className="field">
          <label>Name</label>
          <input value={data.name} onChange={update("name")} required />
        </div>
        <div className="field">
          <label>Phone</label>
          <input value={data.phone} onChange={update("phone")} required placeholder="+971…" />
        </div>
      </div>
      <div className="field">
        <label>Email</label>
        <input type="email" value={data.email} onChange={update("email")} required />
      </div>
      <div className="field">
        <label>Message</label>
        <textarea value={data.message} onChange={update("message")} rows={3} placeholder="Optional — preferred contact time, viewing date, financing notes…" />
      </div>
      <div style={{ fontSize: 11, color: "var(--text-muted)", lineHeight: 1.5 }}>
        Demo form — no data is sent. In production, submissions route to your CRM and trigger a pre-filled WhatsApp deep link.
      </div>
      <div style={{ display: "flex", gap: 12 }}>
        <button type="submit" className="btn btn-primary" style={{ flex: 1, justifyContent: "center" }}>
          Send enquiry <Icon name="arrow" size={12} />
        </button>
      </div>
    </form>
  );
}

// ── Footer ────────────────────────────────────────────────────────
function Footer({ navigate }) {
  return (
    <footer style={{
      background: "var(--noir)", color: "var(--text)",
      borderTop: "1px solid var(--line)",
      padding: "80px 0 32px"
    }}>
      <div className="wrap">
        <div style={{
          display: "grid",
          gridTemplateColumns: "1.4fr 1fr 1fr 1fr",
          gap: 40, marginBottom: 60
        }} className="footer-cols">
          <div>
            <Logo variant="white" height={32} />
            <p className="serif" style={{
              fontSize: 22, fontWeight: 400, fontStyle: "italic",
              marginTop: 28, lineHeight: 1.3, color: "var(--text)",
              maxWidth: 320
            }}>
              The world's rarest cars. One showroom on Sheikh Zayed Road.
            </p>
          </div>

          <div>
            <div className="eyebrow" style={{ marginBottom: 18 }}>Showroom</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10, fontSize: 14, lineHeight: 1.55 }}>
              <div>507 Sheikh Zayed Road<br/>near Mashreq Bank, Al Quoz 3<br/>Dubai, UAE</div>
              <a href="tel:+97143232999" className="num" style={{ marginTop: 6 }}>+971 4 323 2999</a>
              <a href="mailto:sales@vipmotors.ae">sales@vipmotors.ae</a>
            </div>
          </div>

          <div>
            <div className="eyebrow" style={{ marginBottom: 18 }}>Explore</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10, fontSize: 14 }}>
              <button className="footer-link" onClick={() => navigate("inventory")}>Inventory</button>
              <button className="footer-link" onClick={() => navigate("sell")}>Sell / Trade-in</button>
              <button className="footer-link" onClick={() => navigate("finance")}>Finance</button>
              <button className="footer-link" onClick={() => navigate("about")}>About</button>
              <button className="footer-link" onClick={() => navigate("contact")}>Contact</button>
            </div>
          </div>

          <div>
            <div className="eyebrow" style={{ marginBottom: 18 }}>Hours</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 6, fontSize: 14, color: "var(--text-muted)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 12 }}>
                <span>Mon — Thu</span><span className="num" style={{ color: "var(--text)" }}>10:00 – 21:00</span>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 12 }}>
                <span>Friday</span><span className="num" style={{ color: "var(--text)" }}>14:00 – 21:00</span>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 12 }}>
                <span>Saturday</span><span className="num" style={{ color: "var(--text)" }}>10:00 – 21:00</span>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 12 }}>
                <span>Sunday</span><span className="num" style={{ color: "var(--text-dim)" }}>Closed</span>
              </div>
            </div>
          </div>
        </div>

        <hr className="hr" />
        <div style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          paddingTop: 28, flexWrap: "wrap", gap: 16,
          fontSize: 12, color: "var(--text-muted)"
        }}>
          <div className="mono">© {new Date().getFullYear()} VIP MOTORS LLC — DUBAI</div>
          <div className="mono" style={{ display: "flex", gap: 24, flexWrap: "wrap" }}>
            <a href="#" style={{ color: "inherit" }}>Privacy</a>
            <a href="#" style={{ color: "inherit" }}>Terms</a>
            <a href="#" style={{ color: "inherit" }}>Cookies</a>
            <span>VIPMOTORS.AE</span>
          </div>
        </div>
      </div>

      <style>{`
        .footer-link {
          background: none; border: 0; padding: 0; cursor: pointer;
          color: var(--text); text-align: left; font: inherit;
          opacity: 0.78; transition: opacity 180ms, color 180ms;
        }
        .footer-link:hover { opacity: 1; color: var(--accent); }
        @media (max-width: 900px) {
          .footer-cols { grid-template-columns: 1fr 1fr !important; }
        }
        @media (max-width: 600px) {
          .footer-cols { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </footer>
  );
}

// ── Quick rail ────────────────────────────────────────────────────
function QuickRail({ onEnquire }) {
  return (
    <div className="rail">
      <a href="tel:+97143232999" className="rail-btn" title="Call showroom" aria-label="Call">
        <Icon name="phone" size={18} />
      </a>
      <button className="rail-btn" onClick={onEnquire} title="WhatsApp — placeholder; number TBC" aria-label="WhatsApp">
        <Icon name="whatsapp" size={20} />
      </button>
      <button className="rail-btn primary" onClick={onEnquire} aria-label="Enquire">
        <Icon name="mail" size={18} />
      </button>
    </div>
  );
}

Object.assign(window, { Logo, Icon, Nav, VehicleCard, Modal, EnquiryForm, Footer, QuickRail });
