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

function useRoute() {
  const [route, setRoute] = useState(() => parseHash(window.location.hash));
  useEffect(() => {
    const handler = () => setRoute(parseHash(window.location.hash));
    window.addEventListener("hashchange", handler);
    return () => window.removeEventListener("hashchange", handler);
  }, []);
  return route;
}

function parseHash(h) {
  let path = h.replace(/^#/, "") || "/";
  const query = {};
  const qIdx = path.indexOf("?");
  if (qIdx >= 0) {
    const qs = path.slice(qIdx + 1);
    path = path.slice(0, qIdx);
    qs.split("&").filter(Boolean).forEach(pair => {
      const [k, v] = pair.split("=");
      query[decodeURIComponent(k)] = decodeURIComponent(v || "");
    });
  }
  return { path: path || "/", query };
}

function navigate(path, query) {
  let h = "#" + path;
  if (query) {
    const qs = Object.entries(query).filter(([, v]) => v !== undefined && v !== null && v !== "").map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&");
    if (qs) h += "?" + qs;
  }
  window.location.hash = h;
  window.scrollTo({ top: 0, behavior: "instant" });
}

function Header({ currentPath }) {
  const [drawerOpen, setDrawerOpen] = useState(false);
  const close = () => setDrawerOpen(false);
  const links = [
    { to: "/", label: "Home" },
    { to: "/packages", label: "Packages" },
    { to: "/how-it-works", label: "How It Works" },
    { to: "/about", label: "About" },
    { to: "/contact", label: "Contact" },
  ];
  return <>
    <header className="site-header"><div className="container header-inner">
      <a className="logo" href="#/" onClick={close} aria-label={`${COMPANY.name} home`}><span className="logo-mark">GR</span><span><span>{COMPANY.name}</span><span className="logo-text-sm">Hamilton Garage Help</span></span></a>
      <nav className="nav" aria-label="Primary navigation">
        {links.slice(1).map(link => <a key={link.to} href={`#${link.to}`} className={currentPath === link.to ? "active" : ""}>{link.label}</a>)}
      </nav>
      <div className="header-actions">
        <a className="phone-link" href={`tel:${COMPANY.phoneRaw}`}><Icon.Phone /> <span className="full">{COMPANY.phone}</span></a>
        <a className="btn btn-primary" href="#/quote">Request Quote <Icon.ArrowRight /></a>
        <button className="hamburger" onClick={() => setDrawerOpen(o => !o)} aria-label="Menu" aria-expanded={drawerOpen}>{drawerOpen ? <Icon.X /> : <Icon.Menu />}</button>
      </div>
    </div></header>
    <div className={"mobile-drawer" + (drawerOpen ? " open" : "")}>{links.map(l => <a key={l.to} href={`#${l.to}`} onClick={close}>{l.label}</a>)}<a className="btn btn-primary btn-block" href="#/quote" onClick={close}>Request Quote <Icon.ArrowRight /></a></div>
  </>;
}

function MobileCTABar() {
  return <div className="mobile-cta-bar"><a className="btn btn-secondary" href={`tel:${COMPANY.phoneRaw}`}><Icon.Phone /> Call</a><a className="btn btn-primary" href="#/quote">Photo Quote <Icon.ArrowRight /></a></div>;
}

function Footer() {
  return <footer className="site-footer"><div className="container"><div className="footer-grid">
    <div className="footer-brand"><div className="logo footer-logo"><span className="logo-mark">GR</span><span><span>{COMPANY.name}</span><span className="logo-text-sm">Garage reset specialists</span></span></div><p className="footer-tagline">Hamilton-first garage clean-outs with sorting, hauling, donation, recycling, sweeping, and light organization.</p><a className="btn btn-primary" href="#/quote">Start with Photos <Icon.ArrowRight /></a></div>
    <div><h4>Company</h4><ul><li><a href="#/about">About</a></li><li><a href="#/packages">Packages</a></li><li><a href="#/how-it-works">How It Works</a></li><li><a href="#/contact">Contact</a></li></ul></div>
    <div><h4>Services</h4><ul><li><a href="#/services/garage-reset">Garage Reset</a></li><li><a href="#/services/garage-clean-out">Garage Clean-Out</a></li><li><a href="#/services/donation-recycling">Donation & Recycling</a></li><li><a href="#/quote">Photo Quote</a></li></ul></div>
    <div><h4>Contact</h4><ul><li><a href={`tel:${COMPANY.phoneRaw}`} className="mono">{COMPANY.phone}</a></li><li><a href={`mailto:${COMPANY.email}`}>{COMPANY.email}</a></li><li>{COMPANY.address}</li><li>Service area: {formatAreas()}</li></ul></div>
  </div><div className="footer-bottom"><span>© {new Date().getFullYear()} {COMPANY.name}</span><span><a href="#/privacy">Privacy</a> · <a href="#/terms">Terms</a></span></div></div></footer>;
}

function SectionHeader({ eyebrow, title, copy }) {
  return <div className="section-header"><div><span className="eyebrow">{eyebrow}</span><h2>{title}</h2></div>{copy && <p>{copy}</p>}</div>;
}

function PackageCard({ pkg, compact }) {
  return <article className={"package-card" + (pkg.highlight ? " featured" : "") }>
    {pkg.image && <figure className="package-image"><img src={pkg.image.src} alt={pkg.image.alt} loading="lazy" decoding="async" /></figure>}
    {pkg.highlight && <span className="popular-badge">Most requested</span>}
    <div className="package-head"><h3>{pkg.name}</h3><div className="package-price">{pkg.range}</div></div>
    <p>{pkg.summary}</p><p className="small muted"><strong>Best for:</strong> {pkg.bestFor}</p>
    {!compact && <ul className="check-list">{pkg.includes.map(item => <li key={item}><Icon.Check /> {item}</li>)}</ul>}
    <a className="btn btn-primary btn-block" href={`#/quote?package=${pkg.id}`}>Request Quote <Icon.ArrowRight /></a>
  </article>;
}

function BeforeAfterPanel() {
  return <div className="before-after-panel" aria-label="Before and after garage reset photos">
    <figure className="before-after-card before">
      <img src="/public/images/garage-before-illustrative.webp" alt="Cluttered residential garage before a reset" loading="eager" />
      <figcaption><span>Before</span><strong>Cluttered garage</strong></figcaption>
    </figure>
    <figure className="before-after-card after">
      <img src="/public/images/garage-after-illustrative.webp" alt="Broom-clean garage with simple storage zones after a reset" loading="eager" />
      <figcaption><span>After</span><strong>Broom-clean, zoned</strong></figcaption>
    </figure>
    <p>See how a garage reset turns cluttered floor space into clear, usable zones.</p>
  </div>;
}

function HeroShowcase({ selectedPackage, servicePackage, onPackageChange }) {
  const viewportRef = useRef(null);
  const emblaRef = useRef(null);
  const onSelectRef = useRef(null);
  const onReInitRef = useRef(null);
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [scrollSnaps, setScrollSnaps] = useState([0, 1]);
  const [canScrollPrev, setCanScrollPrev] = useState(false);
  const [canScrollNext, setCanScrollNext] = useState(true);
  const [emblaReady, setEmblaReady] = useState(false);
  const slideLabels = ["See the reset", "Estimate your range"];

  const syncEmblaState = useCallback((api) => {
    if (!api) return;
    setSelectedIndex(api.selectedScrollSnap());
    setScrollSnaps(api.scrollSnapList());
    setCanScrollPrev(api.canScrollPrev());
    setCanScrollNext(api.canScrollNext());
  }, []);

  useEffect(() => {
    if (!viewportRef.current || !window.EmblaCarousel) {
      setEmblaReady(false);
      return undefined;
    }
    const api = window.EmblaCarousel(viewportRef.current, {
      loop: false,
      align: "start",
      containScroll: "trimSnaps",
      dragFree: false,
      breakpoints: {
        "(prefers-reduced-motion: reduce)": { duration: 0 }
      }
    });
    emblaRef.current = api;
    const onSelect = () => syncEmblaState(api);
    const onReInit = () => syncEmblaState(api);
    onSelectRef.current = onSelect;
    onReInitRef.current = onReInit;
    api.on("select", onSelect);
    api.on("reInit", onReInit);
    syncEmblaState(api);
    setEmblaReady(true);
    return () => {
      api.off("select", onSelect);
      api.off("reInit", onReInit);
      api.destroy();
      emblaRef.current = null;
      onSelectRef.current = null;
      onReInitRef.current = null;
    };
  }, [syncEmblaState]);

  const scrollPrev = () => emblaRef.current?.scrollPrev();
  const scrollNext = () => emblaRef.current?.scrollNext();
  const scrollTo = (index) => emblaRef.current?.scrollTo(index);
  const slideA11y = (index) => {
    const active = !emblaReady || selectedIndex === index;
    return {
      "aria-hidden": !active,
      inert: !active ? "" : undefined
    };
  };
  const inactiveTabIndex = (index) => (!emblaReady || selectedIndex === index) ? undefined : -1;

  return <section className={"hero-showcase" + (!emblaReady ? " no-embla" : "")} role="region" aria-roledescription="carousel" aria-label="Garage reset preview and quote estimator">
    <div className="hero-showcase-head"><div><span className="eyebrow">Start here</span><h2>{slideLabels[selectedIndex]}</h2></div><span className="hero-slide-count">{selectedIndex + 1} of {scrollSnaps.length || 2}</span></div>
    <div className="hero-embla-viewport" ref={viewportRef}>
      <div className="hero-embla-container">
        <div className="hero-embla-slide" role="group" aria-roledescription="slide" aria-label="Slide 1 of 2, before and after garage reset photos" {...slideA11y(0)}>
          <BeforeAfterPanel />
        </div>
        <div className="hero-embla-slide" role="group" aria-roledescription="slide" aria-label="Slide 2 of 2, quote range estimator" {...slideA11y(1)}>
          <div className="quote-widget hero-quote-widget"><h3>Start with a quote range</h3><p className="small muted">Select the closest package, then send photos so we can confirm scope.</p><label className="field-label" htmlFor="hero-package-select">Likely package</label><select id="hero-package-select" className="field-select" value={servicePackage} onChange={e => onPackageChange(e.target.value)} tabIndex={inactiveTabIndex(1)}>{SERVICE_PACKAGES.map(pkg => <option key={pkg.id} value={pkg.id}>{pkg.name}</option>)}</select><div className="quote-result"><div><span className="label">Estimated range</span><span className="price">{selectedPackage.range}</span></div><button className="btn btn-primary" onClick={() => navigate('/quote', { package: selectedPackage.id })} tabIndex={inactiveTabIndex(1)}>Continue <Icon.ArrowRight /></button></div><p className="xs muted">Final quote depends on volume, weight, labour, access, extra trips, and disposal needs.</p></div>
        </div>
      </div>
    </div>
    <div className="hero-showcase-controls" aria-label="Hero carousel controls">
      <button className="hero-nav" type="button" onClick={scrollPrev} disabled={!canScrollPrev} aria-label="Show previous hero slide"><Icon.ArrowRight /></button>
      <div className="hero-dots" role="tablist" aria-label="Choose hero slide">
        {scrollSnaps.map((_, index) => <button key={index} type="button" className={"hero-dot" + (selectedIndex === index ? " active" : "")} onClick={() => scrollTo(index)} aria-label={`Show ${slideLabels[index]}`} aria-selected={selectedIndex === index} />)}
      </div>
      <button className="hero-nav next" type="button" onClick={scrollNext} disabled={!canScrollNext} aria-label="Show next hero slide"><Icon.ArrowRight /></button>
    </div>
    <p className="sr-only" aria-live="polite">Showing slide {selectedIndex + 1} of {scrollSnaps.length || 2}: {slideLabels[selectedIndex]}</p>
  </section>;
}

function ComparisonBlock() {
  return <section className="section comparison-section"><div className="container"><SectionHeader eyebrow="More than junk removal" title="The difference is what happens after the truck." copy="Garage Reset Hamilton focuses on the usable finish, not just removing items." />
    <div className="comparison-grid"><div className="comparison-card ordinary"><h3>Junk removal takes things away</h3>{COMPARISON_POINTS.map(p => <div className="compare-row" key={p.ordinary}><span>—</span><p>{p.ordinary}</p></div>)}</div><div className="comparison-card reset"><h3>A garage reset gives the space back</h3>{COMPARISON_POINTS.map(p => <div className="compare-row" key={p.reset}><span><Icon.Check /></span><p>{p.reset}</p></div>)}</div></div>
  </div></section>;
}

function RoutingBuckets() {
  return <section className="section routing-section"><div className="container"><SectionHeader eyebrow="Responsible routing" title="Less to landfill, by default." copy="Usable and recyclable items are separated where practical. It is part of every reset, not an upsell." />
    <div className="routing-grid">{ROUTING_BUCKETS.map((b, i) => <div className="routing-card" key={b.t}>{b.image && <figure className="routing-image"><img src={b.image.src} alt={b.image.alt} loading="lazy" decoding="async" /></figure>}<span className="num">{String(i + 1).padStart(2, "0")}</span><h3>{b.t}</h3><p>{b.d}</p></div>)}</div>
  </div></section>;
}

function CTAStrip({ title, sub }) {
  return <div className="cta-strip"><div><h2>{title}</h2><p>{sub}</p></div><a className="btn btn-primary btn-lg" href="#/quote">Request a Photo Quote <Icon.ArrowRight /></a></div>;
}

function ServiceAreaMap() {
  return <div className="service-area-card"><div><span className="eyebrow">Service area</span><h3>Hamilton first, nearby requests reviewed case by case.</h3><p>{formatAreas()} are the main service areas. Nearby communities can be reviewed based on scope, timing, and access.</p></div><div className="area-pills">{SERVICE_AREAS.map(a => <span key={a}>{a}</span>)}</div></div>;
}

function StubPage({ title }) {
  return <><div className="page-header"><div className="container"><h1>{title}</h1><p>We are finalizing this page. Contact us if you need details before it is published.</p></div></div><section className="section"><div className="container"><a className="btn btn-primary" href="#/contact">Contact Us</a></div></section></>;
}

Object.assign(window, { useRoute, navigate, Header, Footer, MobileCTABar, SectionHeader, PackageCard, BeforeAfterPanel, HeroShowcase, ComparisonBlock, RoutingBuckets, CTAStrip, ServiceAreaMap, StubPage });
