
// Panels — one stage-panel per camera stop. They float inside the scene.
// GSAP fades + lifts them in/out as the camera enters/leaves their stop.

const SERVICES = [
  { n: '01', i: IconScan,    t: 'Diagnostics',            d: 'OBD-II scan + visual. Codes translated, price quoted upfront.',
    more: 'We run a full multi-system scan, walk the bay with your car, and call you with photos + a flat price before any work starts. Most diagnostics: 30–60 minutes.' },
  { n: '02', i: IconDisc,    t: 'Brake Service',          d: 'Pads, rotors, lines, fluid flush. Every wheel pulled and measured.',
    more: 'Pad + rotor inspection at all four corners, brake-line bleed, fluid moisture check, and a road test. OEM-quality parts. Lifetime pad warranty on most vehicles.' },
  { n: '03', i: IconDrop,    t: 'Oil Changes',            d: 'Synthetic or conventional — next service logged for you.',
    more: 'Full-synthetic, blend, or conventional. Filter swap, 20-point check (lights, wipers, belts, fluids), reset reminder, sticker for the next interval.' },
  { n: '04', i: IconEngine,  t: 'Engine Repair',          d: 'Timing belts, water pumps, gaskets, turbos. Master-tech work.',
    more: 'From check-engine codes to head-gasket rebuilds. ASE Master-Tech on staff. We send photos of worn parts before and after. Most jobs back same week.' },
  { n: '05', i: IconBolt,    t: 'AC Service',             d: 'Refrigerant, compressor, evap diagnosis. Cold air same-day.',
    more: 'R-134a + R-1234yf machines on-site. Leak detection, compressor and condenser swap, cabin filter refresh. Most AC repairs done same day.' },
  { n: '06', i: IconCar,     t: 'Suspension & Steering',  d: 'Struts, shocks, control arms, tie rods, alignments.',
    more: 'Hunter alignment rack on-site. Strut + shock replacement, control-arm bushings, ball joints, tie rods. Test-drive after every alignment.' },
  { n: '07', i: IconGauge,   t: 'Electrical Repair',      d: 'Batteries, alternators, starters, harness diagnostics.',
    more: 'Charging-system tests, parasitic-draw tracing, harness repairs, module reflashing. We chase electrical gremlins so you do not have to.' },
  { n: '08', i: IconShield,  t: 'Preventive Maintenance', d: 'Manufacturer schedules followed honestly.',
    more: 'We follow the factory schedule for your make + mileage — fluids, filters, belts, plugs — and only what is due. No upsells, no "while we are in there" guilt trips.' },
];

const PROCESS = [
  { n: '01', t: 'Inspect',     d: 'Visual walk + tire/fluid check.' },
  { n: '02', t: 'Diagnose',    d: 'OBD-II + bay-side test drive.' },
  { n: '03', t: 'Explain',     d: 'We call. Parts, hours, exact price.' },
  { n: '04', t: 'Repair',      d: 'You sign off. We pick up the wrench.' },
  { n: '05', t: 'Final Check', d: 'Drive, scan again, hand back keys.' },
];

const WHYUS = [
  { i: IconShield, t: 'Honest diagnostics',      d: 'No mystery items. Codes and photos every time.' },
  { i: IconPhone,  t: 'Clear communication',     d: 'We call before we touch a wrench.' },
  { i: IconBolt,   t: 'Reliable repairs',        d: 'ASE-certified work that holds up.' },
  { i: IconPin,    t: 'Local Fort Myers',        d: 'Family-owned at 4036 Fowler since 2010.' },
  { i: IconScan,   t: 'Modern tools',            d: 'OBD-II, brake lathe, alignment rack on-site.' },
  { i: IconGauge,  t: 'Craftsmanship mindset',   d: 'We sweat the small stuff so your car runs right.' },
];

const REVIEWS = [
  { who: 'Robert Fox',    loc: 'FORT MYERS · 2024',
    q: 'Brought my Tacoma in for a check-engine light. Straight answer, exact price in 20 minutes. Drove home same day.' },
  { who: 'Eleanor Pena',  loc: 'CAPE CORAL · 2024',
    q: 'My A/C died in August. Squeezed me in the same day, fixed it for less than the dealer quoted. I trust these guys.' },
  { who: 'Marcus Wynn',   loc: 'FORT MYERS · 2023',
    q: 'Timing belt + water pump on a 2014 Civic. Photos of the old parts, walked through it. Perfect for 18 months.' },
];

const StagePanels = ({ onBook, currentStop }) => {
  const isActive = (stop) => currentStop === stop;
  const [siteContent, setSiteContent] = React.useState(() =>
    typeof window.getSiteContent === 'function' ? window.getSiteContent() : null
  );
  React.useEffect(() => {
    const refresh = () => setSiteContent(window.getSiteContent());
    window.addEventListener('site-content-updated', refresh);
    return () => window.removeEventListener('site-content-updated', refresh);
  }, []);
  const heroCopy = siteContent?.hero || {
    headline: 'Infinite Auto', headlineAccent: 'Garage.',
    sub: 'Precision auto repair in Fort Myers — modern diagnostics, honest service, and garage-grade craftsmanship.',
    address: '4036 Fowler St · Fort Myers, FL 33901',
    phone: '239-355-8787',
  };
  const hoursList = siteContent?.hours || [];
  const phoneTel  = window.phoneToTel ? window.phoneToTel(heroCopy.phone) : `tel:${heroCopy.phone}`;
  const mapsUrl   = `https://maps.google.com/?q=${encodeURIComponent(heroCopy.address)}`;
  const hoursLine = (() => {
    if (!hoursList.length) return 'Mon–Fri 8a–6p · Sat 8a–2p · Closed Sun';
    const fmt = (t) => { if (!t) return ''; const [hh, mm] = t.split(':'); const h12 = ((+hh + 11) % 12) + 1; const ampm = +hh >= 12 ? 'p' : 'a'; return `${h12}${mm !== '00' ? ':' + mm : ''}${ampm}`; };
    const open = hoursList.filter(h => !h.closed);
    const closed = hoursList.filter(h => h.closed);
    // crude pretty-print: group consecutive same-hours days
    if (!open.length) return 'Hours by appointment';
    const wkdays = open.filter(h => !['Saturday','Sunday'].includes(h.day));
    const sat = open.find(h => h.day === 'Saturday');
    const parts = [];
    if (wkdays.length === 5 && wkdays.every(h => h.open === wkdays[0].open && h.close === wkdays[0].close)) {
      parts.push(`Mon–Fri ${fmt(wkdays[0].open)}–${fmt(wkdays[0].close)}`);
    } else {
      wkdays.forEach(h => parts.push(`${h.day.slice(0,3)} ${fmt(h.open)}–${fmt(h.close)}`));
    }
    if (sat) parts.push(`Sat ${fmt(sat.open)}–${fmt(sat.close)}`);
    if (closed.length) parts.push(`Closed ${closed.map(h => h.day.slice(0,3)).join('/')}`);
    return parts.join(' · ');
  })();
  const [expanded, setExpanded] = React.useState(null);
  const svcGridRef = React.useRef(null);
  const toggleSvc = (n) => {
    setExpanded((cur) => {
      const next = cur === n ? null : n;
      if (next) {
        // After React commits the expanded layout, scroll the grid so the
        // open card sits at the top. Use setTimeout (rAF is throttled in
        // some embedded iframes) to wait past the commit.
        setTimeout(() => {
          window.__SVC_SCROLL_FIRED = true;
          const grid = svcGridRef.current;
          if (!grid) return;
          const card = grid.querySelector(`[data-svc="${next}"]`);
          if (!card) return;
          const top = card.offsetTop - grid.offsetTop;
          window.__SVC_SCROLL_TARGET = top;
          grid.scrollTo({ top, behavior: 'auto' });
        }, 80);
      }
      return next;
    });
  };
  return (
    <div className="panel-layer">
      {/* HERO */}
      <section className="stage-panel hero-panel" data-stop="hero" data-active={isActive('hero')}>
        <div className="eyebrow">
          <span className="dot" />
          BAY 03 · LIGHTS ON · FORT MYERS
        </div>
        <h1>{heroCopy.headline}<br/><span className="amber">{heroCopy.headlineAccent}</span></h1>
        <p className="sub">{heroCopy.sub}</p>
        <div className="trust">LOCATED AT {heroCopy.address.toUpperCase()}</div>
        <div className="actions">
          <a href={phoneTel} className="btn btn-primary btn-lg">
            <IconPhone size={18} /> Call {heroCopy.phone}
          </a>
          <a href={mapsUrl}
             target="_blank" rel="noopener"
             className="btn btn-amber btn-lg">
            <IconPin size={18} /> Get Directions
          </a>
          <button className="btn btn-ghost btn-lg" onClick={onBook}>
            Book Service <IconArrow size={18} />
          </button>
        </div>
      </section>

      {/* SERVICES */}
      <section className="stage-panel services-panel glass" data-stop="services" data-active={isActive('services')}>
        <div className="head">
          <div className="eyebrow"><span className="dot" />STOP 02 · TOOL WALL</div>
          <h2>Everything your<br/>car will ever need.</h2>
          <p className="sub">Tap any service for details. Booking takes 60 seconds.</p>
        </div>
        <div className="svc-grid" ref={svcGridRef}>
          {SERVICES.map((s) => {
            const open = expanded === s.n;
            return (
              <article
                className={`svc ${open ? 'is-open' : ''}`}
                key={s.n}
                data-svc={s.n}
              >
                <button
                  type="button"
                  className="svc-head"
                  aria-expanded={open}
                  onClick={() => toggleSvc(s.n)}
                >
                  <span className="icon"><s.i size={22} /></span>
                  <span className="n">{s.n}</span>
                  <h3>{s.t}</h3>
                  <p className="d">{s.d}</p>
                  <span className="chev" aria-hidden="true">{open ? '–' : '+'}</span>
                </button>
                {open && (
                  <div className="svc-body">
                    <p>{s.more}</p>
                    <button
                      type="button"
                      className="svc-book"
                      onClick={(e) => { e.stopPropagation(); onBook(); }}
                    >
                      Book this service <IconArrow size={14} />
                    </button>
                  </div>
                )}
              </article>
            );
          })}
        </div>
      </section>

      {/* PROCESS */}
      <section className="stage-panel process-panel glass" data-stop="process" data-active={isActive('process')}>
        <div className="eyebrow"><span className="dot" />STOP 03 · DIAGNOSTIC STATION</div>
        <h2>How a repair runs here.</h2>
        <p className="sub">Five steps. No surprises in any of them.</p>
        <div className="proc-steps">
          {PROCESS.map((p, i) => (
            <div className={`proc-step ${i === 0 ? 'active' : ''}`} key={p.n}>
              <div className="num">{p.n}</div>
              <h4>{p.t}</h4>
              <p>{p.d}</p>
            </div>
          ))}
        </div>
      </section>

      {/* WHY US */}
      <section className="stage-panel why-panel glass" data-stop="whyus" data-active={isActive('whyus')}>
        <div className="eyebrow"><span className="dot" />STOP 04 · TRUST WALL</div>
        <h2>Why drivers stay.</h2>
        <p className="sub">Six pillars that show up in every job.</p>
        <div className="why-grid">
          {WHYUS.map((w) => (
            <div className="why-item" key={w.t}>
              <div className="ic"><w.i size={16} /></div>
              <div>
                <h4>{w.t}</h4>
                <p>{w.d}</p>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* REVIEWS */}
      <section className="stage-panel reviews-panel glass" data-stop="reviews" data-active={isActive('reviews')}>
        <div className="eyebrow" style={{justifyContent:'center', display:'flex'}}><span className="dot" />STOP 05 · CUSTOMER LOUNGE</div>
        <h2>Real drivers. Real cars.</h2>
        <p className="sub">Six hundred Google reviews and counting. 4.9 stars.</p>
        <div className="reviews-grid">
          {REVIEWS.map((r) => (
            <article className="review" key={r.who}>
              <div className="stars">★★★★★</div>
              <p className="quote">&ldquo;{r.q}&rdquo;</p>
              <div className="who"><b>{r.who}</b> · {r.loc}</div>
            </article>
          ))}
        </div>
      </section>

      {/* CONTACT */}
      <section className="stage-panel contact-panel glass" data-stop="contact" data-active={isActive('contact')}>
        <div className="eyebrow" style={{justifyContent:'center', display:'flex'}}><span className="dot" />STOP 06 · FRONT DESK</div>
        <h2>You're here.<br/><span className="amber">Pull in.</span></h2>
        <span className="phone">{heroCopy.phone}</span>
        <p className="lines">
          <b>INFINITE AUTO GARAGE LLC</b><br/>
          {heroCopy.address}<br/>
          {hoursLine}
        </p>
        <div className="actions">
          <a href={phoneTel} className="btn btn-primary btn-lg">
            <IconPhone size={18} /> Call Now
          </a>
          <a href={mapsUrl}
             target="_blank" rel="noopener"
             className="btn btn-amber btn-lg">
            <IconPin size={18} /> Open in Maps
          </a>
          <button className="btn btn-ghost btn-lg" onClick={onBook}>
            Book Service <IconArrow size={18} />
          </button>
        </div>
      </section>
    </div>
  );
};

window.StagePanels = StagePanels;
