// 123 Auto Group NYC — main app

const { useState, useEffect, useRef } = React;

// Public Maps JS API key — must be referrer-restricted in Google Cloud Console.
// Restrict to: maps JavaScript API + Places API (New); referrers limited to this domain.
const GOOGLE_MAPS_API_KEY = "AIzaSyCrnoNcj2sKPR7FHIoExLaMlccy9ioCloM";
// Once we know the canonical Place ID, set GOOGLE_PLACE_ID and the text search becomes a direct lookup.
const GOOGLE_PLACE_ID = "ChIJKTj0hYpdwokRVR-hk1_e94Y";
const GOOGLE_PLACE_QUERY = "123 Auto Group";
const GOOGLE_PLACE_LOCATION = { lat: 40.6736742, lng: -73.8426271 }; // from Google share link

// Bootstrap loader for the modern Maps JS API. Required for the new Places (Place) class.
let _gmapsLoaded = false;
function loadGoogleMaps(apiKey) {
  if (window.google && window.google.maps && window.google.maps.importLibrary) {
    return Promise.resolve(window.google.maps);
  }
  if (!_gmapsLoaded) {
    _gmapsLoaded = true;
    ((g) => {
      var h, a, k, p = "The Google Maps JavaScript API", c = "google", l = "importLibrary",
          q = "__ib__", m = document, b = window;
      b = b[c] || (b[c] = {});
      var d = b.maps || (b.maps = {}), r = new Set(), e = new URLSearchParams(),
          u = () => h || (h = new Promise((f, n) => {
            a = m.createElement("script");
            e.set("libraries", [...r] + "");
            for (k in g) e.set(k.replace(/[A-Z]/g, (t) => "_" + t[0].toLowerCase()), g[k]);
            e.set("callback", c + ".maps." + q);
            a.src = `https://maps.${c}apis.com/maps/api/js?` + e;
            d[q] = f;
            a.onerror = () => { h = null; n(Error(p + " could not load.")); };
            a.nonce = m.querySelector("script[nonce]")?.nonce || "";
            m.head.append(a);
          }));
      d[l] ? console.warn(p + " only loads once. Ignoring:", g) :
        d[l] = (f, ...n) => r.add(f) && u().then(() => d[l](f, ...n));
    })({ key: apiKey, v: "weekly" });
  }
  // The bootstrap defines importLibrary synchronously after invocation.
  return Promise.resolve(window.google.maps);
}

async function fetchGoogleReviews() {
  const maps = await loadGoogleMaps(GOOGLE_MAPS_API_KEY);
  if (typeof maps.importLibrary !== "function") {
    throw new Error("Maps bootstrap loader didn't initialize importLibrary — Maps JS may have failed to load.");
  }
  const { Place } = await maps.importLibrary("places");
  if (!Place || typeof Place.searchByText !== "function") {
    throw new Error("Place class missing searchByText — confirm Places API (New) is enabled on your Google Cloud project.");
  }
  const fields = ["id", "displayName", "formattedAddress", "reviews", "rating", "userRatingCount"];

  let place;
  if (GOOGLE_PLACE_ID) {
    try {
      place = new Place({ id: GOOGLE_PLACE_ID });
      await place.fetchFields({ fields });
    } catch (err) {
      console.warn("[reviews] Hard-coded Place ID lookup failed (likely stale):", err && err.message ? err.message : err);
      console.warn("[reviews] Falling back to text search by name + location bias.");
      place = null;
    }
  }
  if (!place) {
    const { places } = await Place.searchByText({
      textQuery: GOOGLE_PLACE_QUERY,
      locationBias: {
        center: GOOGLE_PLACE_LOCATION,
        radius: 200,
      },
      fields,
      maxResultCount: 1,
    });
    place = places && places[0];
  }

  if (!place) {
    console.warn(`[reviews] No place matched query="${GOOGLE_PLACE_QUERY}"`);
    return [];
  }
  console.info(
    "[reviews] Matched place:", place.displayName,
    "—", place.formattedAddress,
    `(${place.userRatingCount || 0} ratings, ${place.rating || "?"}★)`
  );
  console.info("%c[reviews] Canonical Place ID — paste this back to update GOOGLE_PLACE_ID:", "font-weight: bold; color: #E11D2E", place.id);
  const raw = place.reviews || [];
  console.info(`[reviews] API returned ${raw.length} review(s)`);
  const reviews = raw.map((r) => ({
    rating: r.rating,
    quote: typeof r.text === "string" ? r.text : (r.text && r.text.text) || "",
    name: (r.authorAttribution && r.authorAttribution.displayName) || "Google reviewer",
    photo: (r.authorAttribution && (r.authorAttribution.photoURI || r.authorAttribution.photoUri)) || null,
    when: r.relativePublishTimeDescription || "",
  })).filter((r) => r.rating === 5 && r.quote);
  console.info(`[reviews] ${reviews.length} of those are 5-star with text`);
  return {
    reviews,
    rating: typeof place.rating === "number" ? place.rating : null,
    userRatingCount: typeof place.userRatingCount === "number" ? place.userRatingCount : null,
  };
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#E11D2E",
  "fontPair": "bebas-inter",
  "motion": 2,
  "heroVariant": "editorial"
} /*EDITMODE-END*/;

const FONT_PAIRS = {
  "bebas-inter": {
    label: "Bebas Neue × Inter",
    display: "'Bebas Neue', Impact, sans-serif",
    serif: "'Instrument Serif', serif",
    sans: "'Inter', sans-serif",
    mono: "'JetBrains Mono', monospace",
    googleImports: ["Bebas+Neue", "Instrument+Serif:ital@0;1", "Inter:wght@300;400;500;600", "JetBrains+Mono:wght@400;500"]
  },
  "bebas-helvetica": {
    label: "Bebas Neue × Helvetica",
    display: "'Bebas Neue', Impact, sans-serif",
    serif: "'Instrument Serif', serif",
    sans: "'Helvetica Neue', Helvetica, Arial, sans-serif",
    mono: "'JetBrains Mono', monospace",
    googleImports: ["Bebas+Neue", "Instrument+Serif:ital@0;1", "JetBrains+Mono:wght@400;500"]
  },
  "oswald-inter": {
    label: "Oswald × Inter",
    display: "'Oswald', Impact, sans-serif",
    serif: "'Instrument Serif', serif",
    sans: "'Inter', sans-serif",
    mono: "'JetBrains Mono', monospace",
    googleImports: ["Oswald:wght@400;500;600", "Instrument+Serif:ital@0;1", "Inter:wght@300;400;500;600", "JetBrains+Mono:wght@400;500"]
  }
};

// ---------- Logo ----------
function Logo({ small }) {
  return (
    <a href="#top" className="nav__logo" aria-label="123 Auto Group NYC">
      <img src="logo.png" alt="123 Auto Group NYC" />
    </a>);

}

// ---------- Nav ----------
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <nav className={"nav" + (scrolled ? " scrolled" : "")}>
      <Logo />
      <div className="nav__links">
        <a href="#process">Process</a>
        <a href="#why">Why us</a>
        <a href="#brokers">Brokers</a>
        <a href="#brands">Brands</a>
        <a href="#faq">FAQ</a>
        <a href="#contact">Contact</a>
      </div>
      <a className="nav__cta" href="credit-application.html">
        Credit application
        <svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.5">
          <path d="M6 3l5 5-5 5" />
        </svg>
      </a>
    </nav>);

}

// ---------- Hero ----------
function Hero({ variant }) {
  const bgRef = useRef(null);
  useEffect(() => {
    const el = bgRef.current;
    if (!el) return;
    const onScroll = () => {
      const y = window.scrollY;
      el.style.transform = `scale(1.05) translateY(${y * 0.25}px)`;
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <section className="hero" data-variant={variant} id="top">
      <div className="hero__media">
        <img
          ref={bgRef}
          className="hero__bg"
          src="https://images.unsplash.com/photo-1503376780353-7e6692767b70?auto=format&fit=crop&w=2400&q=80"
          alt=""
          onError={(e) => {e.currentTarget.src = "https://images.unsplash.com/photo-1494976388531-d1058494cdd8?auto=format&fit=crop&w=2400&q=80";}} />
        
      </div>
      <div className="hero__topline">123 Auto Group · Est. 2009 · NYC</div>
      <div className="hero__inner">
        <h1 className="hero__title reveal" style={{ "--delay": 0 }}>
          Your dream car.<br />
          <em>Without the</em> <span className="accent">dealership.</span>
        </h1>
        <div className="hero__meta">
          <p className="hero__sub reveal" style={{ "--delay": 1 }}>
            We're brokers, not salespeople. Tell us the car — we shop every dealer in the network, lock the number, and deliver to your door. Most clients have keys within 72 hours.
          </p>
          <div className="hero__cta-row reveal" style={{ "--delay": 2 }}>
            <a className="btn btn--primary" href="#contact">
              Start the search
              <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M6 3l5 5-5 5" /></svg>
            </a>
            <a className="btn btn--ghost" href="credit-application.html">Apply for credit</a>
          </div>
        </div>
      </div>
      <div className="hero__scroll">Scroll</div>
    </section>);

}

// ---------- Value Prop ----------
function ValueProp() {
  const items = [
  { num: "01", title: "We work for you.", copy: "Dealers work for the dealer. We're hired by you to find the deal — and we shop every showroom in the tri-state." },
  { num: "02", title: "Delivered to your door.", copy: "Sign at your kitchen table. The car shows up the same week — tank full, plates on, ready to drive. Home, office, anywhere in the tri-state." },
  { num: "03", title: "Every brand, every tier.", copy: "Acura to BMW. First-time buyer or third-time client. Spotless credit or rebuilding. We've placed every spec, every situation." }];

  return (
    <section className="section" id="why">
      <div className="section__head">
        <div>
          <div className="section__eyebrow reveal">What we do</div>
        </div>
        <h2 className="section__title reveal">
          The dealership is <em>built to sell.</em> We're built to find.
        </h2>
      </div>
      <div className="value">
        {items.map((it, i) =>
        <div key={it.num} className="value__item reveal" style={{ "--delay": i }}>
            <div className="value__num">{it.num}</div>
            <h3 className="value__title">{it.title}</h3>
            <p className="value__copy">{it.copy}</p>
          </div>
        )}
      </div>
      <div className="stats">
        <Stat num="17" small="yrs" label="In business since 2009" />
        <Stat num="6,400" small="+" label="Vehicles placed" />
        <Stat num="0" small="hr" label="Showroom time required" />
        <Stat num="48" small="hr" label="Avg. deal turnaround" />
      </div>
    </section>);

}
function Stat({ num, small, label }) {
  return (
    <div className="reveal">
      <div className="stat__num">{num}{small && <small>{small}</small>}</div>
      <div className="stat__label">{label}</div>
    </div>);

}

// ---------- Process ----------
function Process() {
  const steps = [
  {
    num: "Step 01",
    title: "Tell us the car.",
    copy: "A make, a model, a vibe — even just a budget. Phone call, text, or form. We do the rest.",
    img: "https://images.unsplash.com/photo-1606664515524-ed2f786a0bd6?auto=format&fit=crop&w=1200&q=80",
    meta: "Brief"
  },
  {
    num: "Step 02",
    title: "We shop the market.",
    copy: "Our team works every dealer in the network — we don't take the first quote, and we never accept the markup tax.",
    img: "https://images.unsplash.com/photo-1583121274602-3e2820c69888?auto=format&fit=crop&w=1200&q=80",
    meta: "Source"
  },
  {
    num: "Step 03",
    title: "Review the terms.",
    copy: "You see the numbers next to each other — money factor, residual, fees. No surprises, no upsell, no four-square nonsense.",
    img: "https://images.unsplash.com/photo-1493238792000-8113da705763?auto=format&fit=crop&w=1200&q=80",
    meta: "Negotiate"
  },
  {
    num: "Step 04",
    title: "We deliver.",
    copy: "Sign at your kitchen table. The car shows up clean, full tank, plates on. Welcome home.",
    img: "https://images.unsplash.com/photo-1606664515524-ed2f786a0bd6?auto=format&fit=crop&w=1200&q=80",
    meta: "Deliver"
  }];

  const [active, setActive] = useState(0);
  return (
    <section className="section" id="process">
      <div className="section__head">
        <div>
          <div className="section__eyebrow reveal">How it works</div>
        </div>
        <h2 className="section__title reveal">
          Four steps. <em>Zero showrooms.</em>
        </h2>
      </div>
      <div className="process">
        <div className="process__list reveal">
          {steps.map((s, i) =>
          <div
            key={s.num}
            className={"process__step" + (active === i ? " is-active" : "")}
            onClick={() => setActive(i)}
            onMouseEnter={() => setActive(i)}>
            
              <div className="process__step-num">{s.num}</div>
              <div>
                <h3 className="process__step-title">{s.title}</h3>
                <p className="process__step-copy">{s.copy}</p>
              </div>
            </div>
          )}
        </div>
        <div className="process__visual reveal">
          {steps.map((s, i) =>
          <img
            key={i}
            className={"process__visual-img" + (active === i ? " is-active" : "")}
            src={s.img}
            alt=""
            onError={(e) => {e.currentTarget.style.display = 'none';}} />

          )}
          <div className="process__visual-meta">
            <span>0{active + 1} / 0{steps.length}</span>
            <span>{steps[active].meta}</span>
          </div>
        </div>
      </div>
    </section>);

}

// ---------- Brokers ----------
function Brokers() {
  // EDIT ME: bios are placeholder copy — replace with real backgrounds when ready.
  // EDIT ME: drop /jimmy.jpg and /jeremy.jpg in the project root to use real photos; otherwise the monogram fallback shows.
  const brokers = [
  {
    name: "Jimmy",
    role: "Co-broker",
    bio: "One half of 123 Auto Group. Specializes in the spec hunt — finding the exact build, color, and trim a client wants, even when no dealer in five states has it on the ground.",
    quote: "Jimmy was incredibly thorough, patient, and helpful from start to finish. After just a few quick calls and texts, he had the car registered and delivered locally.",
    quoteFrom: "Rosy R., Local Guide on Google",
    photo: "/jimmy.jpg",
    phone: "+17188802418",
    phoneDisplay: "(718) 880-2418",
    whatsapp: "https://wa.me/17188802418",
    email: "jimmy@123autogroupnyc.com"
  },
  {
    name: "Jeremy",
    role: "Co-broker",
    bio: "One half of 123 Auto Group. The broker first-timers and repeat clients ask for by name. Runs the deal floor — pricing, money-factor negotiation, and door-step delivery.",
    quote: "Jeremy is literally a genie in a bottle when it comes to making your car purchase dream come true. He kept me at the budget that I asked for.",
    quoteFrom: "Monica G. on Google",
    photo: "/jeremy.jpg",
    phone: "+17188802418",
    phoneDisplay: "(718) 880-2418",
    whatsapp: "https://wa.me/17188802418",
    email: "jeremy@123autogroupnyc.com"
  }];

  return (
    <section className="section" id="brokers">
      <div className="section__head">
        <div>
          <div className="section__eyebrow reveal">Meet the brokers</div>
        </div>
        <h2 className="section__title reveal">
          Two names. <em>One phone call</em> away.
        </h2>
      </div>
      <div className="brokers">
        {brokers.map((b, i) =>
        <div key={b.name} className="broker reveal" style={{ "--delay": i }}>
            <div className="broker__media">
              <img
              src={b.photo}
              alt={b.name}
              onError={(e) => {
                e.currentTarget.style.display = "none";
                e.currentTarget.parentElement.classList.add("broker__media--placeholder");
                e.currentTarget.parentElement.dataset.initial = b.name[0];
              }} />

            </div>
            <div className="broker__body">
              <div className="broker__role">{b.role}</div>
              <h3 className="broker__name">{b.name}</h3>
              <p className="broker__bio">{b.bio}</p>
              <blockquote className="broker__quote">
                <span>"{b.quote}"</span>
                <cite>— {b.quoteFrom}</cite>
              </blockquote>
              <div className="broker__contact">
                <a href={`tel:${b.phone}`} aria-label={`Call ${b.name}`}>
                  <svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M3 3.5a1 1 0 0 1 1-1h2l1.5 3-1.5 1a8 8 0 0 0 4 4l1-1.5L14 10v2a1 1 0 0 1-1 1A10 10 0 0 1 3 3.5z" /></svg>
                  Call
                </a>
                <a href={b.whatsapp} target="_blank" rel="noopener noreferrer" aria-label={`WhatsApp ${b.name}`}>
                  <svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M2.5 13.5l1-3.5a6 6 0 1 1 2.5 2.5l-3.5 1z" /></svg>
                  WhatsApp
                </a>
                <a href={`mailto:${b.email}`} aria-label={`Email ${b.name}`}>
                  <svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M2 4h12v8H2zM2 4l6 5 6-5" /></svg>
                  Email
                </a>
              </div>
            </div>
          </div>
        )}
      </div>
    </section>);

}

// ---------- Brands ----------
function Brands() {
  const list = [
  "Mercedes-Benz", "BMW", "Audi", "Acura", "Lexus", "Tesla",
  "Porsche", "Range Rover", "Mazda", "Genesis", "Cadillac",
  "Maserati", "Jaguar", "Volvo", "Infiniti", "Land Rover"];

  return (
    <section className="brands" id="brands" aria-label="Brands we lease">
      <div className="brands__track">
        {[...list, ...list].map((b, i) =>
        <span key={i} className="brand">{b}</span>
        )}
      </div>
    </section>);

}

// ---------- Testimonials ----------
const FALLBACK_REVIEWS = [
  { quote: "I told them the car, the color, and my number. Three days later it was in my driveway. Zero showroom time.", name: "Daniela R." },
  { quote: "Beat the lease quote my dealer 'couldn't go any lower' on by $140/month. I've sent them four friends since.", name: "Marcus T." },
  { quote: "Made my first lease feel boring in the best way — they explained every line and saved me from a fee I'd have signed.", name: "Priya S." },
  { quote: "Walked in expecting the usual back-and-forth. Walked out with a number I didn't have to negotiate. That alone was worth it.", name: "Anthony M." },
  { quote: "Third lease through 123 Auto. At this point I don't even shop anywhere else — they just know what I'll like.", name: "Jenna K." },
  { quote: "They found the exact spec I'd been hunting for two months. Picked it up out of state, delivered to my building. Flawless.", name: "David L." },
  { quote: "Honest about what I'd qualify for, no upsell, no surprise fees at signing. First time buying a car didn't feel like a fight.", name: "Sofia A." },
  { quote: "Dealership quoted me 9% — 123 Auto came back with 5.4% the next morning. Still don't know how they pulled it off.", name: "Rafael C." }];

function getCardsPerView() {
  if (typeof window === "undefined") return 3;
  const w = window.innerWidth;
  if (w < 640) return 1;
  if (w < 1024) return 2;
  return 3;
}

function Testimonials() {
  const [items, setItems] = useState(FALLBACK_REVIEWS);
  const [source, setSource] = useState("fallback"); // "fallback" | "google"
  const [placeMeta, setPlaceMeta] = useState({ rating: null, count: null });
  const [index, setIndex] = useState(0);
  const [paused, setPaused] = useState(false);
  const [cardsPerView, setCardsPerView] = useState(getCardsPerView);
  const [selected, setSelected] = useState(null);
  const touchX = useRef(null);
  const lastWasSwipe = useRef(false);
  const googleUrl = GOOGLE_PLACE_ID
    ? `https://www.google.com/maps/place/?q=place_id:${GOOGLE_PLACE_ID}`
    : null;

  const total = items.length;
  const maxIndex = Math.max(0, total - cardsPerView);
  const slideWidth = 100 / cardsPerView;
  const showControls = total > cardsPerView;

  // Fetch real Google reviews; fall back silently on failure.
  useEffect(() => {
    let cancelled = false;
    fetchGoogleReviews()
      .then((data) => {
        if (cancelled || !data || !data.reviews || data.reviews.length === 0) return;
        const mapped = data.reviews.map((r) => ({
          quote: r.quote,
          name: r.name,
          meta: r.when || "",
          photo: r.photo
        }));
        setItems(mapped);
        setSource("google");
        setPlaceMeta({ rating: data.rating, count: data.userRatingCount });
      })
      .catch((err) => console.error("[reviews] Google fetch failed:", err));
    // Maps JS calls this global on auth failure (instead of throwing). Hook it for visibility.
    window.gm_authFailure = () => {
      console.error("[reviews] Google Maps JS auth failed — check that your API key has Places API (New) + Maps JavaScript API enabled, and that the current domain is in the key's HTTP referrer allowlist.");
    };
    return () => { cancelled = true; };
  }, []);

  // Responsive: recompute cards-per-view on resize.
  useEffect(() => {
    const onResize = () => setCardsPerView(getCardsPerView());
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);

  // Clamp index when item count or cards-per-view changes.
  useEffect(() => {
    if (index > maxIndex) setIndex(maxIndex);
  }, [maxIndex, index]);

  const go = (n) => {
    if (maxIndex === 0) return setIndex(0);
    setIndex(((n % (maxIndex + 1)) + (maxIndex + 1)) % (maxIndex + 1));
  };
  const next = () => go(index + 1);
  const prev = () => go(index - 1);

  // Auto-advance (respects motion=0 setting).
  useEffect(() => {
    if (paused || !showControls) return;
    const motion = parseInt(document.documentElement.dataset.motion || "2", 10);
    if (motion === 0) return;
    const id = setInterval(() => {
      setIndex((i) => (i >= maxIndex ? 0 : i + 1));
    }, 6000);
    return () => clearInterval(id);
  }, [paused, showControls, maxIndex]);

  const onKeyDown = (e) => {
    if (!showControls) return;
    if (e.key === "ArrowRight") { e.preventDefault(); next(); }
    if (e.key === "ArrowLeft") { e.preventDefault(); prev(); }
  };
  const onTouchStart = (e) => {
    touchX.current = e.touches[0].clientX;
    lastWasSwipe.current = false;
    setPaused(true);
  };
  const onTouchEnd = (e) => {
    if (touchX.current == null) return;
    const dx = e.changedTouches[0].clientX - touchX.current;
    if (Math.abs(dx) > 40) {
      lastWasSwipe.current = true;
      dx < 0 ? next() : prev();
    }
    touchX.current = null;
    setPaused(false);
  };

  const openCard = (i) => {
    if (lastWasSwipe.current) { lastWasSwipe.current = false; return; }
    setSelected(i);
  };
  const onCardKey = (i) => (e) => {
    if (e.key === "Enter" || e.key === " ") { e.preventDefault(); setSelected(i); }
  };

  const initials = (name) => name.split(" ").filter(Boolean).map((s) => s[0]).join("").slice(0, 2).toUpperCase();

  return (
    <section className="section">
      <div className="section__head">
        <div>
          <div className="section__eyebrow reveal">
            {source === "google" ? "5-star Google reviews" : "5-star reviews"}
          </div>
        </div>
        <h2 className="section__title reveal">
          Repeat business is <em>the only review</em> that matters.
        </h2>
      </div>

      {source === "google" && placeMeta.rating != null && placeMeta.count != null && googleUrl &&
      <div className="reviews__badge-row">
          <a
          className="reviews__badge"
          href={googleUrl}
          target="_blank"
          rel="noopener noreferrer"
          aria-label={`Rated ${placeMeta.rating} out of 5 on Google with ${placeMeta.count} reviews`}>

            <svg viewBox="0 0 18 18" width="14" height="14" aria-hidden="true">
              <path fill="#4285F4" d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844a4.14 4.14 0 0 1-1.796 2.716v2.258h2.908c1.702-1.567 2.684-3.875 2.684-6.615z" />
              <path fill="#34A853" d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 0 0 9 18z" />
              <path fill="#FBBC05" d="M3.964 10.71A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.007-2.332z" />
              <path fill="#EA4335" d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 0 0 .957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z" />
            </svg>
            <span className="reviews__badge-rating">{placeMeta.rating.toFixed(1)}</span>
            <span className="reviews__badge-stars" aria-hidden="true">★★★★★</span>
            <span className="reviews__badge-count">{placeMeta.count} reviews</span>
          </a>
        </div>
      }

      <div
        className="reviews reveal"
        onMouseEnter={() => setPaused(true)}
        onMouseLeave={() => setPaused(false)}
        onFocus={() => setPaused(true)}
        onBlur={() => setPaused(false)}
        onKeyDown={onKeyDown}
        tabIndex={0}
        role="region"
        aria-roledescription="carousel"
        aria-label="Client reviews">

        <div
          className="reviews__viewport"
          onTouchStart={onTouchStart}
          onTouchEnd={onTouchEnd}>
          <div
            className="reviews__track"
            style={{ transform: `translateX(-${index * slideWidth}%)` }}>
            {items.map((t, i) =>
            <div
              key={i}
              className="reviews__slide"
              style={{ flexBasis: `${slideWidth}%` }}
              role="group"
              aria-roledescription="slide"
              aria-label={`${i + 1} of ${total}`}
              aria-hidden={i < index || i >= index + cardsPerView}>
                <div
                className="testimonial testimonial--clickable"
                role="button"
                tabIndex={i >= index && i < index + cardsPerView ? 0 : -1}
                onClick={() => openCard(i)}
                onKeyDown={onCardKey(i)}
                aria-label={`Read full review by ${t.name}`}>
                  <div className="testimonial__stars" aria-label="5 out of 5 stars">★★★★★</div>
                  <p className="testimonial__quote">"{t.quote}"</p>
                  <div className="testimonial__footer">
                    <div className="testimonial__author">
                      {t.photo ?
                    <img className="testimonial__avatar testimonial__avatar--photo" src={t.photo} alt="" loading="lazy" referrerPolicy="no-referrer" /> :
                    <div className="testimonial__avatar">{initials(t.name)}</div>}
                      <div>
                        <div className="testimonial__name">{t.name}</div>
                        {t.meta && <div className="testimonial__meta">{t.meta}</div>}
                      </div>
                    </div>
                    <span className="testimonial__cta">Read full →</span>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>

        {showControls &&
        <div className="reviews__controls">
            <button className="reviews__arrow" onClick={prev} aria-label="Previous reviews">
              <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M10 3L5 8l5 5" /></svg>
            </button>
            <div className="reviews__dots" role="tablist" aria-label="Select review group">
              {Array.from({ length: maxIndex + 1 }).map((_, i) =>
            <button
              key={i}
              role="tab"
              aria-selected={index === i}
              aria-label={`Reviews ${i + 1} to ${Math.min(i + cardsPerView, total)}`}
              className={"reviews__dot" + (index === i ? " is-active" : "")}
              onClick={() => go(i)} />
            )}
            </div>
            <button className="reviews__arrow" onClick={next} aria-label="Next reviews">
              <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M6 3l5 5-5 5" /></svg>
            </button>
          </div>
        }

        {googleUrl &&
        <div className="reviews__google-row">
            <a
            className="reviews__google"
            href={googleUrl}
            target="_blank"
            rel="noopener noreferrer">

              <svg viewBox="0 0 18 18" width="14" height="14" aria-hidden="true">
                <path fill="#4285F4" d="M17.64 9.2c0-.637-.057-1.251-.164-1.84H9v3.481h4.844a4.14 4.14 0 0 1-1.796 2.716v2.258h2.908c1.702-1.567 2.684-3.875 2.684-6.615z" />
                <path fill="#34A853" d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 0 0 9 18z" />
                <path fill="#FBBC05" d="M3.964 10.71A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.007-2.332z" />
                <path fill="#EA4335" d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 0 0 .957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z" />
              </svg>
              See all reviews on Google
              <svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true"><path d="M6 3l5 5-5 5" /></svg>
            </a>
          </div>
        }
      </div>

      {selected != null &&
      <ReviewModal
        review={items[selected]}
        googleUrl={googleUrl}
        initials={initials}
        onClose={() => setSelected(null)} />

      }
    </section>);

}

// ---------- Review Modal ----------
function ReviewModal({ review, googleUrl, initials, onClose }) {
  const closeRef = useRef(null);

  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    if (closeRef.current) closeRef.current.focus();
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [onClose]);

  return (
    <div className="modal" role="dialog" aria-modal="true" aria-label="Review details" onClick={onClose}>
      <div className="modal__card" onClick={(e) => e.stopPropagation()}>
        <button ref={closeRef} className="modal__close" onClick={onClose} aria-label="Close review">
          <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5">
            <path d="M3 3l10 10M13 3L3 13" />
          </svg>
        </button>

        <div className="modal__stars" aria-label="5 out of 5 stars">★★★★★</div>
        <p className="modal__quote">"{review.quote}"</p>

        <div className="modal__author">
          {review.photo ?
          <img className="modal__avatar" src={review.photo} alt="" referrerPolicy="no-referrer" /> :

          <div className="modal__avatar modal__avatar--initials">{initials(review.name)}</div>
          }
          <div>
            <div className="modal__name">{review.name}</div>
            {review.meta && <div className="modal__meta">{review.meta}</div>}
          </div>
        </div>

        {googleUrl &&
        <a
          className="btn btn--ghost modal__google"
          href={googleUrl}
          target="_blank"
          rel="noopener noreferrer">

            View on Google
            <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M6 3l5 5-5 5" /></svg>
          </a>
        }
      </div>
    </div>);

}

// ---------- FAQ ----------
function FAQ() {
  const items = [
  { q: "What does a broker actually cost me?", a: "Nothing out of pocket. We're paid by the dealer that wins your business — but unlike a salesperson, our incentive is to get you the right car at the right number, because that's how we earn referrals." },
  { q: "Do you really deliver the car?", a: "Yes — to your home, your office, or wherever's convenient. Tank full, plates on, ready to drive. Most clients sign at their kitchen table and never set foot in a dealership." },
  { q: "Can you really beat my dealer's quote?", a: "Almost always. Dealers quote you based on what they think you'll accept. We quote you based on what the manufacturer is paying the dealer that month — different math, different number." },
  { q: "What if my credit isn't perfect, or this is my first car?", a: "First-time buyers and rebuilding credit are a big part of our book — we place across every tier. Submit our application; we'll tell you honestly what you qualify for and what we can negotiate. No fee, no obligation, no soft-sell." },
  { q: "Lease, finance, or buy outright?", a: "Whichever makes sense for you — we don't push one over another. We'll model all three side-by-side so you can pick the structure, not just the car." },
  { q: "How fast can I get my car?", a: "If it's on the ground, often within 48-72 hours. Custom orders or rare specs follow the manufacturer's timeline, but we shave weeks off by knowing where the inventory is." }];

  const [open, setOpen] = React.useState(0);
  return (
    <section className="section" id="faq">
      <div className="section__head section__head--stack" style={{ textAlign: "center", justifyItems: "center" }}>
        <div className="section__eyebrow reveal" style={{ justifySelf: "center" }}>Common questions</div>
        <h2 className="section__title reveal" style={{ textAlign: "center" }}>
          Everything you'd ask <em>before signing.</em>
        </h2>
      </div>
      <div className="faq reveal">
        {items.map((it, i) =>
        <div key={i} className={"faq__item" + (open === i ? " is-open" : "")} onClick={() => setOpen(open === i ? -1 : i)}>
            <div className="faq__q">
              <span>{it.q}</span>
              <span className="faq__icon">+</span>
            </div>
            <div className="faq__a">{it.a}</div>
          </div>
        )}
      </div>
    </section>);

}

// ---------- Contact ----------
function Contact() {
  const [state, setState] = useState({ name: "", email: "", phone: "", car: "", timeline: "asap", note: "" });
  const [sent, setSent] = useState(false);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState("");
  const update = (k) => (e) => setState({ ...state, [k]: e.target.value });
  const submit = async (e) => {
    e.preventDefault();
    setSending(true);
    setError("");
    try {
      const res = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify({
          access_key: "54e7cb7f-fa6c-40d0-96fc-a326fa54a49c",
          subject: `New brief from ${state.name} — 123 Auto Group`,
          from_name: "123 Auto Group Site",
          name: state.name,
          email: state.email,
          phone: state.phone,
          car: state.car,
          timeline: state.timeline,
          note: state.note,
        }),
      });
      const data = await res.json();
      if (data.success) {
        setSent(true);
      } else {
        setError(data.message || "Something went wrong. Please try again or call us.");
      }
    } catch (err) {
      setError("Network error. Please try again or call us directly.");
    } finally {
      setSending(false);
    }
  };

  return (
    <section className="section" id="contact">
      <div className="section__head">
        <div>
          <div className="section__eyebrow reveal">Get in touch</div>
        </div>
        <h2 className="section__title reveal">
          Tell us the car. <em>We'll handle the rest.</em>
        </h2>
      </div>
      <div className="contact">
        <div className="contact__info reveal">
          <a href="tel:+17188802418" className="contact__row">
            <span className="contact__label">Phone</span>
            <span className="contact__value">(718) 880-2418</span>
            <span className="contact__action">Call →</span>
          </a>
          <a href="https://wa.me/17188802418" className="contact__row">
            <span className="contact__label">WhatsApp</span>
            <span className="contact__value">+1 (718) 880-2418</span>
            <span className="contact__action">Message →</span>
          </a>
          <a href="mailto:info@123autogroupnyc.com" className="contact__row">
            <span className="contact__label">Email</span>
            <span className="contact__value">info@123autogroupnyc.com</span>
            <span className="contact__action">Send →</span>
          </a>
          <a href="#" className="contact__row">
            <span className="contact__label">Schedule</span>
            <span className="contact__value">Book a 20-min call</span>
            <span className="contact__action">Calendar →</span>
          </a>
          <a href="#" className="contact__row">
            <span className="contact__label">Office</span>
            <span className="contact__value">By appointment, NYC</span>
            <span className="contact__action">Map →</span>
          </a>
        </div>

        <form className="form reveal" onSubmit={submit}>
          <h3 className="form__title">{sent ? "We're on it." : "Quick brief"}</h3>
          {sent ?
          <div>
              <p style={{ color: 'var(--fg-dim)', lineHeight: 1.55 }}>
                Got it, {state.name || "friend"}. A broker will reach out within the hour during business hours, or first thing tomorrow.
              </p>
              <button type="button" className="btn btn--ghost form__submit" onClick={() => {setSent(false);setState({ name: "", email: "", phone: "", car: "", timeline: "asap", note: "" });}}>Submit another</button>
            </div> :

          <>
              <div className="field--row">
                <div className="field">
                  <label>Name</label>
                  <input required value={state.name} onChange={update("name")} placeholder="Jane Doe" />
                </div>
                <div className="field">
                  <label>Phone</label>
                  <input required type="tel" value={state.phone} onChange={update("phone")} placeholder="(212) 555-0100" />
                </div>
              </div>
              <div className="field">
                <label>Email</label>
                <input required type="email" value={state.email} onChange={update("email")} placeholder="jane@email.com" />
              </div>
              <div className="field">
                <label>Car you want</label>
                <input value={state.car} onChange={update("car")} placeholder="2026 BMW M3 Competition, Frozen Black" />
              </div>
              <div className="field">
                <label>Timeline</label>
                <select value={state.timeline} onChange={update("timeline")}>
                  <option value="asap">As soon as possible</option>
                  <option value="month">Within a month</option>
                  <option value="quarter">Next 90 days</option>
                  <option value="exploring">Just exploring</option>
                </select>
              </div>
              <div className="field">
                <label>Anything else</label>
                <textarea value={state.note} onChange={update("note")} placeholder="Trade-in, must-have specs, target payment, etc." />
              </div>
              <button type="submit" disabled={sending} className="btn btn--primary form__submit" style={sending ? { opacity: 0.6, cursor: 'wait' } : {}}>
                {sending ? "Sending…" : "Send brief"}
                <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M6 3l5 5-5 5" /></svg>
              </button>
              {error && <p style={{ color: 'var(--accent)', fontSize: 13, marginTop: 8 }}>{error}</p>}
              <p className="form__legal">By submitting you agree to be contacted about your inquiry. We never share your info.</p>
            </>
          }
        </form>
      </div>
    </section>);

}

// ---------- Footer ----------
function Footer() {
  return (
    <footer className="footer">
      <div className="footer__top">
        <div>
          <img className="footer__logo" src="logo.png" alt="123 Auto Group NYC" />
          <p className="footer__brand-line">An auto brokerage in New York City. We find the car. You enjoy the drive.</p>
        </div>
        <div className="footer__col">
          <h4>Site</h4>
          <ul>
            <li><a href="#process">Process</a></li>
            <li><a href="#why">Why us</a></li>
            <li><a href="#brands">Brands</a></li>
            <li><a href="#faq">FAQ</a></li>
          </ul>
        </div>
        <div className="footer__col">
          <h4>Get started</h4>
          <ul>
            <li><a href="#contact">Contact</a></li>
            <li><a href="credit-application.html">Credit application</a></li>
            <li><a href="tel:+17188802418">Call us</a></li>
            <li><a href="https://wa.me/17188802418">WhatsApp</a></li>
          </ul>
        </div>
        <div className="footer__col">
          <h4>Hours</h4>
          <ul>
            <li><a>Mon–Fri · 9–7</a></li>
            <li><a>Sat · 10–5</a></li>
            <li><a>Sun · By appt.</a></li>
          </ul>
        </div>
      </div>
      <div className="footer__giant" style={{ color: "rgb(32, 32, 32)" }}>123 Auto Group</div>
      <div className="footer__bottom">
        <span>© 2026 · 123 Auto Group NYC</span>
        <span>Licensed broker · NY DMV</span>
        <span><a href="privacy-policy.html">Privacy</a> · <a href="#">Terms</a></span>
      </div>
    </footer>);

}

// ---------- Reveal observer ----------
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add("is-in");
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -40px 0px" });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

// ---------- Tweaks ----------
function FontImports({ pair }) {
  const conf = FONT_PAIRS[pair] || FONT_PAIRS["bebas-inter"];
  const href = `https://fonts.googleapis.com/css2?${conf.googleImports.map((f) => "family=" + f).join("&")}&display=swap`;
  useEffect(() => {
    const id = "dyn-fonts";
    let l = document.getElementById(id);
    if (!l) {
      l = document.createElement("link");
      l.rel = "stylesheet";
      l.id = id;
      document.head.appendChild(l);
    }
    l.href = href;
    if (conf.display) document.documentElement.style.setProperty("--display", conf.display);
    document.documentElement.style.setProperty("--serif", conf.serif);
    document.documentElement.style.setProperty("--sans", conf.sans);
    document.documentElement.style.setProperty("--mono", conf.mono);
  }, [pair, href, conf]);
  return null;
}

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useReveal();

  // Apply accent + motion globally
  useEffect(() => {
    document.documentElement.style.setProperty("--accent", tweaks.accent);
    // derived glow
    document.documentElement.style.setProperty("--accent-glow", tweaks.accent + "55");
    document.documentElement.dataset.motion = tweaks.motion;
  }, [tweaks.accent, tweaks.motion]);

  return (
    <>
      <FontImports pair={tweaks.fontPair} />
      <Nav />
      <Hero variant={tweaks.heroVariant} />
      <ValueProp />
      <Process />
      <Brokers />
      <Brands />
      <Testimonials />
      <FAQ />
      <Contact />
      <Footer />

      <TweaksPanel title="Tweaks">
        <TweakSection title="Accent">
          <TweakColor label="Color" value={tweaks.accent} onChange={(v) => setTweak("accent", v)} />
          <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
            {["#E11D2E", "#D4AF37", "#3B82F6", "#10B981", "#F5F1EA"].map((c) =>
            <button key={c} onClick={() => setTweak("accent", c)} style={{
              width: 24, height: 24, borderRadius: "50%", background: c,
              border: tweaks.accent === c ? "2px solid #fff" : "1px solid rgba(255,255,255,0.2)",
              cursor: "pointer", padding: 0
            }} />
            )}
          </div>
        </TweakSection>
        <TweakSection title="Typography">
          <TweakSelect
            label="Font pairing"
            value={tweaks.fontPair}
            onChange={(v) => setTweak("fontPair", v)}
            options={Object.entries(FONT_PAIRS).map(([k, v]) => ({ value: k, label: v.label }))} />
          
        </TweakSection>
        <TweakSection title="Motion">
          <TweakRadio
            label="Animation intensity"
            value={tweaks.motion}
            onChange={(v) => setTweak("motion", v)}
            options={[
            { value: 0, label: "Off" },
            { value: 1, label: "Subtle" },
            { value: 2, label: "Default" },
            { value: 3, label: "Bold" }]
            } />
          
        </TweakSection>
        <TweakSection title="Hero layout">
          <TweakRadio
            label="Variant"
            value={tweaks.heroVariant}
            onChange={(v) => setTweak("heroVariant", v)}
            options={[
            { value: "editorial", label: "Editorial" },
            { value: "centered", label: "Centered" },
            { value: "split", label: "Split" }]
            } />
          
        </TweakSection>
      </TweaksPanel>
    </>);

}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);