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

/* ============================================================
   Icons (inline SVG, blue line style)
   ============================================================ */
const Icon = {
  Shield: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M12 3 4.5 6v6c0 5 3.3 8.4 7.5 9 4.2-.6 7.5-4 7.5-9V6L12 3Z" />
      <path d="m9 12 2 2 4-4" />
    </svg>
  ),
  Clock: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <circle cx="12" cy="12" r="9" />
      <path d="M12 7v5l3 2" />
    </svg>
  ),
  Box: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="m3.5 7.5 8.5-4 8.5 4-8.5 4-8.5-4Z" />
      <path d="M3.5 7.5v9l8.5 4 8.5-4v-9" />
      <path d="M12 11.5v9" />
    </svg>
  ),
  Pin: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M12 21s7-6.5 7-12a7 7 0 0 0-14 0c0 5.5 7 12 7 12Z" />
      <circle cx="12" cy="9" r="2.5" />
    </svg>
  ),
  Truck: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M2 17V6h12v11" />
      <path d="M14 9h4l3 4v4h-7" />
      <circle cx="6.5" cy="17.5" r="2" />
      <circle cx="17.5" cy="17.5" r="2" />
    </svg>
  ),
  Bolt: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="m13 2-9 12h7l-1 8 9-12h-7l1-8Z" />
    </svg>
  ),
  Route: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <circle cx="5.5" cy="5.5" r="2.5" />
      <circle cx="18.5" cy="18.5" r="2.5" />
      <path d="M8 5.5h7a4 4 0 0 1 0 8H9a4 4 0 0 0 0 8h7" />
    </svg>
  ),
  Home: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="m3 11 9-7 9 7" />
      <path d="M5 10v10h14V10" />
      <path d="M10 20v-6h4v6" />
    </svg>
  ),
  Phone: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A15 15 0 0 1 3 6a2 2 0 0 1 2-2Z" />
    </svg>
  ),
  Mail: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <rect x="3" y="5" width="18" height="14" rx="2" />
      <path d="m3 7 9 6 9-6" />
    </svg>
  ),
  Arrow: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M5 12h14" />
      <path d="m13 6 6 6-6 6" />
    </svg>
  ),
  Check: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="m5 12 4 4 10-10" />
    </svg>
  ),
};

/* ============================================================
   Brand mark
   ============================================================ */
function BrandMark() {
  return (
    <a className="brand" href="#top" aria-label="STALS — Sprinter tech auto line service">
      <img src="assets/logo-stals.png" alt="STALS — Sprinter tech auto line service" className="brand-logo" />
    </a>
  );
}

/* ============================================================
   NAV
   ============================================================ */
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [openMenu, setOpenMenu] = useState(null);
  const serviceRef = useRef(null);
  const contactsRef = useRef(null);

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

  useEffect(() => {
    if (!openMenu) return;
    const onDown = (e) => {
      const refs = { service: serviceRef, contacts: contactsRef };
      const active = refs[openMenu]?.current;
      if (active && !active.contains(e.target)) setOpenMenu(null);
    };
    const onKey = (e) => { if (e.key === "Escape") setOpenMenu(null); };
    document.addEventListener("mousedown", onDown);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDown);
      document.removeEventListener("keydown", onKey);
    };
  }, [openMenu]);

  const toggle = (name) => () => setOpenMenu((cur) => (cur === name ? null : name));
  const close = () => setOpenMenu(null);

  return (
    <nav className={`nav ${scrolled ? "scrolled" : ""}`} style={{ fontSize: "16px" }}>
      <div className="container nav-inner">
        <BrandMark />
        <div className="nav-links">
          <div className="nav-item" ref={serviceRef}>
            <button
              type="button"
              className={`nav-link nav-link-button ${openMenu === "service" ? "open" : ""}`}
              aria-haspopup="menu"
              aria-expanded={openMenu === "service"}
              onClick={toggle("service")}
            >
              Service
              <span className="caret" aria-hidden="true" />
            </button>
            {openMenu === "service" && (
              <div className="nav-popover" role="menu">
                <a className="nav-popover-item" href="#" role="menuitem" onClick={close}>Oil change</a>
                <a className="nav-popover-item" href="#" role="menuitem" onClick={close}>Suspension</a>
              </div>
            )}
          </div>
          <a className="nav-link" href="#about">About us</a>
          <div className="nav-item" ref={contactsRef}>
            <button
              type="button"
              className={`nav-link nav-link-button ${openMenu === "contacts" ? "open" : ""}`}
              aria-haspopup="menu"
              aria-expanded={openMenu === "contacts"}
              onClick={toggle("contacts")}
            >
              Contacts
              <span className="caret" aria-hidden="true" />
            </button>
            {openMenu === "contacts" && (
              <div className="nav-popover nav-popover-wide nav-popover-right" role="menu">
                <a className="nav-popover-card" href="tel:+17737518786" role="menuitem" onClick={close}>
                  <span className="card-label">HR department</span>
                  <span className="card-sub">Driver hiring & onboarding · Mon–Fri 9a–6p CT</span>
                  <span className="card-phone">+1 (773) 751-8786</span>
                </a>
                <a className="nav-popover-card" href="tel:+12248754029" role="menuitem" onClick={close}>
                  <span className="card-label">Service shop</span>
                  <span className="card-sub">Fleet maintenance & repairs · 24/7 emergency line</span>
                  <span className="card-phone">+1 (224) 875-4029</span>
                </a>
              </div>
            )}
          </div>
        </div>
      </div>
    </nav>
  );
}

/* ============================================================
   HERO
   ============================================================ */
function Hero() {
  return (
    <header className="hero">
      <div className="hero-bg" />
      <div className="hero-overlay" />
      <div className="container hero-inner">
        <div>
          <h1>
            <span className="accent" style={{ fontSize: "55px", lineHeight: "1.05", display: "inline-block" }}>
              Nationwide Sprinter<br />Service
            </span>
          </h1>
          <p className="hero-sub">Reliable. Efficient. Always On Time.</p>
          <p className="hero-desc">
            Logistics and delivery services across the USA.<br />
            Built on trust, driven by technology.
          </p>
        </div>

        <div className="trust-strip">
          {[
            { icon: <Icon.Shield />, label: "Reliable", sub: "You can count on us" },
            { icon: <Icon.Clock />, label: "On Time", sub: "Every time" },
            { icon: <Icon.Box />, label: "Secure", sub: "Your cargo is safe" },
            { icon: <Icon.Pin />, label: "Nationwide", sub: "Across the USA" },
          ].map((t, i) => (
            <div className="trust-item" key={i}>
              <div className="trust-icon">{t.icon}</div>
              <div className="trust-text">
                <span className="label">{t.label}</span>
                <span className="sub">{t.sub}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </header>
  );
}

/* ============================================================
   SERVICES
   ============================================================ */
const SERVICES = [
  {
    icon: <Icon.Route />,
    title: "Long-haul delivery",
    desc: "Cross-country routes for high-value freight. Team drivers, real-time GPS, and live dispatch coverage.",
    pill: "48 states",
    meta: "Avg. 1,800 mi / leg",
  },
  {
    icon: <Icon.Bolt />,
    title: "Same-day Sprinter",
    desc: "Critical loads handled same-day in major metros. Direct point-to-point — no terminals, no transfers.",
    pill: "Same day",
    meta: "Pickup in 60 min",
  },
  {
    icon: <Icon.Truck />,
    title: "Expedited freight",
    desc: "Fast and reliable cargo van delivery across the USA for commercial and urgent shipments.",
    pill: "Time-critical",
    meta: "99.4% on-time",
  },
  {
    icon: <Icon.Home />,
    title: "Last-mile delivery",
    desc: "White-glove final-mile coverage with installation, signature capture, and proof of delivery.",
    pill: "B2B / B2C",
    meta: "Signature + POD",
  },
];

function ServiceCard({ s, idx }) {
  const ref = useRef(null);
  const onMove = (e) => {
    const r = ref.current.getBoundingClientRect();
    ref.current.style.setProperty("--mx", `${e.clientX - r.left}px`);
    ref.current.style.setProperty("--my", `${e.clientY - r.top}px`);
  };
  return (
    <article className="svc-card reveal" ref={ref} onMouseMove={onMove}>
      <span className="svc-num">0{idx + 1}</span>
      <div className="svc-icon">{s.icon}</div>
      <h3 className="svc-title">{s.title}</h3>
      <p className="svc-desc">{s.desc}</p>
    </article>
  );
}

function Services() {
  return (
    <section id="service" className="services">
      <div className="container">
        <div className="section-head">
          <div>
            <div className="eyebrow">Service</div>
            <h2 className="section-title">What we move,<br />and how we move it.</h2>
          </div>
          <p className="section-kicker reveal">
            Four core services covering everything from cross-country freight to white-glove final-mile.
            One fleet, one team, one accountable contact.
          </p>
        </div>
        <div className="svc-grid">
          {SERVICES.map((s, i) => (
            <ServiceCard s={s} key={i} idx={i} />
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   ABOUT — story + animated stat counters
   ============================================================ */
function useInView(ref, threshold = 0.2) {
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            setSeen(true);
            io.unobserve(e.target);
          }
        });
      },
      { threshold }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, [ref]);
  return seen;
}

function Counter({ to, suffix = "", duration = 1400 }) {
  const [v, setV] = useState(0);
  const ref = useRef(null);
  const seen = useInView(ref, 0.4);
  useEffect(() => {
    if (!seen) return;
    const start = performance.now();
    const ease = (t) => 1 - Math.pow(1 - t, 3);
    let id;
    const tick = (now) => {
      const t = Math.min(1, (now - start) / duration);
      setV(Math.round(ease(t) * to));
      if (t < 1) id = requestAnimationFrame(tick);
    };
    id = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(id);
  }, [seen, to, duration]);
  return (
    <span ref={ref}>
      {v.toLocaleString()}
      {suffix && <span className="unit">{suffix}</span>}
    </span>
  );
}

function About() {
  return (
    <section id="about" className="about">
      <div className="container">
        <div className="about-intro">
          <div className="about-copy reveal">
            <div className="eyebrow">Visit us</div>
            <h2 className="section-title">Office &amp; service shop.</h2>
            <p>
              Our Addison, IL location is both our dispatch office and a full-service shop.
              Drivers, fleet partners, and walk-in customers all get the same hands-on attention.
            </p>
            <p>
              We service more than just Sprinter cargo vans — our techs handle scheduled maintenance,
              brakes, suspension, oil &amp; fluids, diagnostics, and air-conditioning work on most
              vans, light trucks, and commercial vehicles. If it rolls, we can probably keep it rolling.
            </p>
          </div>

          <div className="info-card address-card reveal">
            <div className="icon"><Icon.Pin /></div>
            <div>
              <div className="label">Office &amp; service shop</div>
              <div className="value">1772 W Armitage Ct<br />Addison, IL 60101<br />United States</div>
              <div className="sub">Mon–Fri 8a–6p · Sat–Sun closed</div>
            </div>
          </div>
        </div>

        <div className="fleet-ribbon">
          {[
            { num: "01", name: "Vetted drivers", desc: "FMCSA-cleared, drug-tested, background-checked. Average 8+ years OTR." },
            { num: "02", name: "Live tracking", desc: "GPS telematics on every unit. Customer portal with milestone alerts." },
            { num: "03", name: "Air-ride equipped", desc: "Climate-controlled and lift-gate options for sensitive cargo." },
            { num: "04", name: "24/7 dispatch", desc: "U.S.-based dispatchers, real humans on every call, around the clock." },
          ].map((f, i) => (
            <div className="fleet-item reveal" key={i}>
              <span className="num">{f.num}</span>
              <div className="name">{f.name}</div>
              <div className="desc">{f.desc}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   CONTACTS — form + info cards + US map
   ============================================================ */
function ContactForm() {
  const [data, setData] = useState({ name: "", company: "", email: "", phone: "", service: "", message: "" });
  const [errors, setErrors] = useState({});
  const [sent, setSent] = useState(false);
  const set = (k) => (e) => setData({ ...data, [k]: e.target.value });

  const submit = (e) => {
    e.preventDefault();
    const errs = {};
    if (!data.name.trim()) errs.name = "Required";
    if (!data.email.trim()) errs.email = "Required";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) errs.email = "Invalid email";
    if (!data.message.trim()) errs.message = "Tell us a bit about your shipment";
    setErrors(errs);
    if (Object.keys(errs).length === 0) setSent(true);
  };

  if (sent) {
    return (
      <div className="contact-form-card">
        <div className="form-success">
          <div className="check"><Icon.Check width={28} height={28} /></div>
          <h3>Message received.</h3>
          <p>A dispatcher will reach out within the next 30 minutes. For urgent loads call our 24/7 line directly.</p>
          <button className="btn btn-ghost" onClick={() => { setSent(false); setData({ name: "", company: "", email: "", phone: "", service: "", message: "" }); }}>
            Send another
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="contact-form-card">
      <h3>Request a quote</h3>
      <p className="form-sub">Tell us about your shipment — we'll be back within 30 minutes.</p>
      <form className="form-grid" onSubmit={submit} noValidate>
        <div className={`field ${errors.name ? "error" : ""}`}>
          <label>Full name</label>
          <input type="text" value={data.name} onChange={set("name")} placeholder="Jordan Hayes" />
          {errors.name && <span className="err-msg">{errors.name}</span>}
        </div>
        <div className="field">
          <label>Company</label>
          <input type="text" value={data.company} onChange={set("company")} placeholder="Acme Logistics" />
        </div>
        <div className={`field ${errors.email ? "error" : ""}`}>
          <label>Email</label>
          <input type="email" value={data.email} onChange={set("email")} placeholder="jordan@acme.com" />
          {errors.email && <span className="err-msg">{errors.email}</span>}
        </div>
        <div className="field">
          <label>Phone</label>
          <input type="tel" value={data.phone} onChange={set("phone")} placeholder="(555) 555-0199" />
        </div>
        <div className="field full">
          <label>Service</label>
          <select value={data.service} onChange={set("service")}>
            <option value="">Select a service…</option>
            <option>Long-haul delivery</option>
            <option>Same-day Sprinter</option>
            <option>Expedited freight</option>
            <option>Last-mile delivery</option>
            <option>Not sure — talk to dispatch</option>
          </select>
        </div>
        <div className={`field full ${errors.message ? "error" : ""}`}>
          <label>Shipment details</label>
          <textarea
            value={data.message}
            onChange={set("message")}
            placeholder="Origin, destination, weight/dimensions, pickup window, anything else we should know…"
          />
          {errors.message && <span className="err-msg">{errors.message}</span>}
        </div>
        <div className="form-submit full">
          <button type="submit" className="btn">
            Send Request <span className="arrow"><Icon.Arrow width={16} height={16} /></span>
          </button>
          <p className="form-meta">By submitting you agree to be contacted by a STALS dispatcher about your inquiry.</p>
        </div>
      </form>
    </div>
  );
}

function USMap() {
  const pins = [
    { x: 24, y: 56, label: "Dallas, TX — HQ", hq: true },
    { x: 14, y: 50 },
    { x: 18, y: 28 },
    { x: 10, y: 36 },
    { x: 38, y: 28 },
    { x: 52, y: 38 },
    { x: 68, y: 30 },
    { x: 74, y: 44 },
    { x: 82, y: 36 },
    { x: 60, y: 60 },
    { x: 72, y: 70 },
    { x: 86, y: 56 },
  ];

  return (
    <div className="map-card">
      <div className="map-head">
        <span className="label">Coverage map</span>
        <span className="live"><span className="dot" />Live · 184 active routes</span>
      </div>
      <div className="map-wrap">
        <svg viewBox="0 0 800 500" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
          <defs>
            <pattern id="dots" width="10" height="10" patternUnits="userSpaceOnUse">
              <circle cx="1.2" cy="1.2" r="1.1" fill="rgba(255,255,255,0.16)" />
            </pattern>
            <clipPath id="us-clip">
              <path d="M86,180 L122,150 L160,128 L210,110 L260,98 L310,92 L360,90 L410,90 L470,92 L530,98 L590,108 L640,124 L685,148 L710,180 L720,220 L716,260 L702,300 L678,338 L640,370 L592,394 L540,408 L488,418 L436,420 L386,418 L340,410 L298,398 L262,386 L228,372 L196,354 L170,332 L150,308 L134,282 L116,254 L98,228 L86,202 Z" />
            </clipPath>
          </defs>

          <rect width="800" height="500" fill="url(#dots)" clipPath="url(#us-clip)" />

          <path
            d="M86,180 L122,150 L160,128 L210,110 L260,98 L310,92 L360,90 L410,90 L470,92 L530,98 L590,108 L640,124 L685,148 L710,180 L720,220 L716,260 L702,300 L678,338 L640,370 L592,394 L540,408 L488,418 L436,420 L386,418 L340,410 L298,398 L262,386 L228,372 L196,354 L170,332 L150,308 L134,282 L116,254 L98,228 L86,202 Z"
            fill="none"
            stroke="rgba(255,255,255,0.22)"
            strokeWidth="1.5"
          />

          <g stroke="rgba(255,255,255,0.06)" strokeWidth="1" fill="none">
            <path d="M200,120 L210,400" />
            <path d="M320,100 L320,418" />
            <path d="M440,92 L440,420" />
            <path d="M560,100 L560,410" />
            <path d="M100,240 L720,240" />
            <path d="M100,320 L700,320" />
          </g>

          <g stroke="rgba(31,95,232,0.5)" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeDasharray="2 4">
            {pins.filter((p) => !p.hq).slice(0, 8).map((p, i) => {
              const x1 = 24 * 8;
              const y1 = 56 * 5;
              const x2 = p.x * 8;
              const y2 = p.y * 5;
              const cx = (x1 + x2) / 2;
              const cy = Math.min(y1, y2) - 40;
              return <path key={i} d={`M${x1},${y1} Q${cx},${cy} ${x2},${y2}`} />;
            })}
          </g>
        </svg>

        {pins.map((p, i) => (
          <span
            key={i}
            className={`map-pin ${p.hq ? "hq" : ""}`}
            style={{ left: `${p.x}%`, top: `${p.y}%` }}
          >
            {p.label && <span className="pin-label">{p.label}</span>}
          </span>
        ))}
      </div>
    </div>
  );
}

function Contacts() {
  return (
    <section id="contacts" className="contacts">
      <div className="container">
        <div className="section-head">
          <div>
            <div className="eyebrow">Contacts</div>
            <h2 className="section-title">Let's move<br />something.</h2>
          </div>
          <p className="section-kicker reveal">
            Dispatch answers 24/7. Quotes typically inside 30 minutes.
            For time-critical loads, the phone is faster than the form.
          </p>
        </div>

        <div className="contacts-grid">
          <ContactForm />
          <div className="contact-info-col">
            <div className="info-card reveal">
              <div className="icon"><Icon.Phone /></div>
              <div>
                <div className="label">24/7 Dispatch</div>
                <div className="value">+1 (800) 555-7825</div>
                <div className="sub">Real humans, every call, every hour.</div>
              </div>
            </div>
            <div className="info-card reveal">
              <div className="icon"><Icon.Mail /></div>
              <div>
                <div className="label">Email</div>
                <div className="value">dispatch@stals.us</div>
                <div className="sub">Quotes within 30 minutes during business hours.</div>
              </div>
            </div>
            <div className="info-card reveal">
              <div className="icon"><Icon.Pin /></div>
              <div>
                <div className="label">Headquarters</div>
                <div className="value">2400 Logistics Pkwy<br />Dallas, TX 75201</div>
                <div className="sub">Operations centers in Atlanta, Chicago, and Reno.</div>
              </div>
            </div>
            <USMap />
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   FOOTER
   ============================================================ */
function Footer() {
  return (
    <footer>
      <div className="container">
        <div className="footer-bottom">
          <span>© 2026 STALS — Sprinter tech auto line service. All rights reserved.</span>
        </div>
      </div>
    </footer>
  );
}

/* ============================================================
   REVEAL on scroll
   ============================================================ */
function useScrollReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12 }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

/* ============================================================
   APP
   ============================================================ */
function App() {
  useScrollReveal();
  return (
    <>
      <Nav />
      <main id="main">
        <Hero />
        <Services />
        <About />
      </main>
      <Footer />
    </>
  );
}

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