/* Shared UI primitives + Nav + Footer + Modal + WhatsApp FAB */
const { useState, useEffect, useRef, useMemo, Fragment } = React;

/* ============================================================
   NAV
   ============================================================ */
function Nav({ page, navigate, light, openEnquire, lang, setLang }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    onScroll();
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const items = [
    { id: "collection", label: "Collection" },
    { id: "wanted",     label: "Wanted" },
    { id: "services",   label: "Services" },
    { id: "about",      label: "About" },
    { id: "faqs",       label: "FAQs" },
    { id: "media",      label: "Media" },
    { id: "contact",    label: "Contact" },
  ];
  return (
    <header className={`nav ${scrolled ? "scrolled" : ""} ${light ? "light" : ""}`}>
      <div className="logo" onClick={() => navigate("home")}>
        <img src={light && !scrolled ? "media/logo-tomini-classics.svg" : "media/logo-tomini-classics-white.svg"} alt="Tomini Classics" />
      </div>
      <nav className="links">
        {items.map(it => (
          <a key={it.id} className={page === it.id ? "active" : ""} onClick={() => navigate(it.id)}>
            {it.label}
          </a>
        ))}
      </nav>
      <div className="right">
        <div className="lang">
          {["EN","AR","RU","ZH"].map(l => (
            <span key={l} className={lang === l ? "active" : ""} onClick={() => setLang(l)}>{l}</span>
          ))}
        </div>
        <button className="btn btn-solid" onClick={() => openEnquire({ kind: "general" })}>
          <span className="label">Enquire</span>
        </button>
      </div>
    </header>
  );
}

/* ============================================================
   FOOTER
   ============================================================ */
function Footer({ navigate, openEnquire }) {
  return (
    <footer className="footer">
      <div className="shell">
        <div className="footer-grid">
          <div>
            <img src="media/logo-tomini-classics-white.svg" alt="Tomini Classics" style={{ height: 44, marginBottom: 24 }} />
            <p style={{ maxWidth: "32ch", opacity: 0.75, margin: 0 }}>
              Dubai's premier classic car showroom and gallery — the automotive division of the Tomini Group.
            </p>
            <p style={{ marginTop: 18, fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.16em", opacity: 0.6, textTransform: "uppercase" }}>
              Est. 2014 · Collection since 2010
            </p>
          </div>

          <div>
            <h5>Explore</h5>
            <ul>
              <li><a onClick={() => navigate("collection")}>Collection</a></li>
              <li><a onClick={() => navigate("wanted")}>Wanted</a></li>
              <li><a onClick={() => navigate("services")}>Services</a></li>
              <li><a onClick={() => navigate("media")}>Press</a></li>
            </ul>
          </div>

          <div>
            <h5>Company</h5>
            <ul>
              <li><a onClick={() => navigate("about")}>About</a></li>
              <li><a onClick={() => navigate("faqs")}>FAQs</a></li>
              <li><a onClick={() => navigate("contact")}>Contact</a></li>
              <li><a href="https://tominigroup.com" target="_blank" rel="noreferrer">Tomini Group ↗</a></li>
            </ul>
          </div>

          <div>
            <h5>Contact</h5>
            <ul>
              <li><a href="tel:+97143062032">+971 4 306 2032</a></li>
              <li><a href="mailto:contact@tominiclassics.com">contact@tominiclassics.com</a></li>
              <li style={{ opacity: 0.7, fontSize: 13, lineHeight: 1.55, marginTop: 6 }}>
                Tomini Building, Umm Suqeim Road,<br/>Al Barsha 2, Dubai, UAE
              </li>
            </ul>
            <h5 style={{ marginTop: 28 }}>Newsletter</h5>
            <div className="newsletter">
              <input placeholder="Email address" />
              <button>Subscribe →</button>
            </div>
          </div>
        </div>
        <div className="legal">
          <span>© 2026 Tomini Classics · Tomini Trading LLC</span>
          <span style={{ display: "flex", gap: 18 }}>
            <a href="https://instagram.com/tomini.classics" target="_blank" rel="noreferrer">Instagram</a>
            <a href="https://facebook.com/tominiclassics" target="_blank" rel="noreferrer">Facebook</a>
          </span>
        </div>
      </div>
    </footer>
  );
}

/* ============================================================
   ENQUIRE MODAL  (kind: 'general' | 'vehicle' | 'viewing' | 'valuation' | 'storage' | 'sell')
   ============================================================ */
function EnquireModal({ kind, vehicle, onClose, onSubmit, whatsappOn, defaultTab }) {
  const tabs = useMemo(() => [
    { id: "enquire", label: "Enquire" },
    { id: "details", label: "Request Details" },
    { id: "viewing", label: "Book Viewing" },
  ], []);
  const [tab, setTab] = useState(defaultTab || (kind === "viewing" ? "viewing" : "enquire"));
  const [sent, setSent] = useState(false);

  const title = useMemo(() => {
    if (kind === "vehicle") return `Enquire — ${vehicle.year} ${vehicle.make} ${vehicle.model}`;
    if (kind === "valuation") return "Request a Valuation";
    if (kind === "storage")   return "Storage Enquiry";
    if (kind === "sell")      return "Sell Us Your Car";
    if (kind === "viewing")   return "Book a Viewing";
    return "Enquire";
  }, [kind, vehicle]);

  const deck = useMemo(() => {
    if (kind === "vehicle") return "We'll come back to you personally — usually within one business day.";
    if (kind === "sell")    return "Tell us about your car. If it fits our profile of post-war collectible sportscars, we'll be in touch.";
    if (kind === "storage") return "White-glove, climate-controlled, monthly. Minimum one month — twenty-four-hour access by prior arrangement.";
    return "A direct line to our Classics team. We answer in person, not by template.";
  }, [kind]);

  function submit(e) {
    e.preventDefault();
    setSent(true);
    onSubmit && onSubmit({ kind, tab, vehicle });
  }

  return (
    <div className="modal-shade" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <button className="close" onClick={onClose} aria-label="Close">✕</button>
        {!sent ? (
          <Fragment>
            <h2 className="display">{title}</h2>
            <p className="modal-deck">{deck}</p>

            {kind === "vehicle" && (
              <div className="tab-row">
                {tabs.map(t => (
                  <button key={t.id} className={tab === t.id ? "active" : ""} onClick={() => setTab(t.id)}>{t.label}</button>
                ))}
              </div>
            )}

            <form onSubmit={submit}>
              <div className="two-col">
                <div className="field">
                  <label>First name</label>
                  <input required defaultValue="" />
                </div>
                <div className="field">
                  <label>Last name</label>
                  <input required defaultValue="" />
                </div>
              </div>
              <div className="two-col">
                <div className="field">
                  <label>Email</label>
                  <input type="email" required />
                </div>
                <div className="field">
                  <label>Phone (incl. country code)</label>
                  <input type="tel" />
                </div>
              </div>
              <div className="field">
                <label>Country of residence</label>
                <input />
              </div>

              {kind === "viewing" || tab === "viewing" ? (
                <div className="two-col">
                  <div className="field">
                    <label>Preferred date</label>
                    <input type="date" />
                  </div>
                  <div className="field">
                    <label>Preferred time</label>
                    <select defaultValue="">
                      <option value="" disabled>Select…</option>
                      <option>Morning (09:00 – 12:00)</option>
                      <option>Afternoon (13:00 – 17:00)</option>
                      <option>Evening (17:00 – 22:00)</option>
                    </select>
                  </div>
                </div>
              ) : null}

              {kind === "sell" && (
                <Fragment>
                  <div className="two-col">
                    <div className="field"><label>Make</label><input placeholder="e.g. Mercedes-Benz" /></div>
                    <div className="field"><label>Model</label><input placeholder="e.g. 280 SL Pagoda" /></div>
                  </div>
                  <div className="two-col">
                    <div className="field"><label>Year</label><input type="number" min="1900" max="2026" /></div>
                    <div className="field"><label>Condition</label>
                      <select defaultValue=""><option value="" disabled>Select…</option><option>Concours</option><option>Excellent</option><option>Good driver</option><option>Project</option></select></div>
                  </div>
                  <div className="field">
                    <label>History & documentation</label>
                    <textarea placeholder="Ownership, service records, originality, accidents…" />
                  </div>
                </Fragment>
              )}

              <div className="field">
                <label>{tab === "details" ? "What would you like to know?" : "Message"}</label>
                <textarea defaultValue={
                  kind === "vehicle"
                    ? (tab === "details"
                        ? `Hello — I'd like to request a full condition report and additional images for the ${vehicle.year} ${vehicle.make} ${vehicle.model}.`
                        : `Hello — I'm interested in the ${vehicle.year} ${vehicle.make} ${vehicle.model}. Could you share its current status and any further provenance you can?`)
                    : ""
                } placeholder="How can we help?" />
              </div>

              <div style={{ display: "flex", gap: 12, marginTop: 12, flexWrap: "wrap" }}>
                <button type="submit" className="btn btn-solid" style={{ flex: 1, justifyContent: "center" }}>
                  <span className="label">Send Enquiry →</span>
                </button>
                {whatsappOn && (
                  <button type="button" className="btn btn-light" onClick={() => alert("Opens WhatsApp once client number is supplied")}>
                    <span className="label">WhatsApp</span>
                  </button>
                )}
              </div>
              <p style={{ fontSize: 12, color: "var(--muted)", marginTop: 4 }}>
                We reply personally — usually within one business day. We never share your details.
              </p>
            </form>
          </Fragment>
        ) : (
          <div className="success">
            <div className="check">✓</div>
            <h2 className="display">Thank you.</h2>
            <p className="modal-deck">Your enquiry has reached our Classics team. Expect a personal reply, usually within one business day.</p>
            <button className="btn" onClick={onClose}><span className="label">Close</span></button>
          </div>
        )}
      </div>
    </div>
  );
}

/* ============================================================
   WHATSAPP FAB (only when toggled on)
   ============================================================ */
function WhatsAppFab({ enabled, onClick }) {
  if (!enabled) return null;
  return (
    <button className="whatsapp-fab" onClick={onClick}>
      <span className="dot"></span>
      <span>WhatsApp our Classics Team</span>
    </button>
  );
}

/* ============================================================
   VEHICLE CARD
   ============================================================ */
function VehicleCard({ v, navigate }) {
  const statusLabel = {
    available: "Available",
    sold: "Sold",
    reserved: "Reserved",
  }[v.status] || "";
  return (
    <a className="v-card fade-in" onClick={() => navigate("vehicle", v.id)}>
      <div className="img-wrap">
        <img src={v.thumb} alt={`${v.year} ${v.make} ${v.model}`} loading="lazy" />
        {statusLabel && <span className={`badge ${v.status}`}>{statusLabel}</span>}
      </div>
      <div className="meta">
        <div>
          <div className="eyebrow muted" style={{ marginBottom: 4 }}>{v.year}</div>
          <div className="name">{v.make} {v.model}</div>
        </div>
        <div className="price">{v.price === "Sold" ? "Sold" : "POA"}</div>
      </div>
      <div className="submeta">
        <span>{v.bodyType}</span>
        <span>{v.transmission.split(" ")[0]}</span>
        <span>{v.colorExt}</span>
      </div>
    </a>
  );
}

/* ============================================================
   PRESS STRIP
   ============================================================ */
function PressStrip() {
  return (
    <div className="press-strip">
      <span className="press-mark serif-cap">The National</span>
      <span className="press-mark">Petrolicious</span>
      <span className="press-mark serif-cap">Gulf News</span>
      <span className="press-mark mono">Automobili Ardent</span>
      <span className="press-mark">Friday</span>
    </div>
  );
}

Object.assign(window, { Nav, Footer, EnquireModal, WhatsAppFab, VehicleCard, PressStrip });
