// Main app
const { useState: useStateA, useEffect: useEffectA } = React;
const { brand, services, areas, reviews } = window.CB_DATA;

// ── Deep-dive routing ───────────────────────────────────────────────────────
// The big product sections (Water Heaters, Blue Light, Line Rescue) each get their
// OWN page instead of being stacked on the homepage — so the phone homepage stays
// short and punchy. Vercel's SPA catch-all already serves index.html for these
// clean URLs; here we just read the path and render the matching section.
const DEEP_ROUTES = ['water-heaters', 'blue-light', 'line-rescue', 'videos', 'flood', 'facts', 'vip'];
function getRoute() {
  const q = new URLSearchParams(window.location.search).get('p'); // local-preview fallback (?p=water-heaters)
  const p = (window.location.pathname || '').replace(/^\/+|\/+$/g, '');
  const r = q || p;
  return DEEP_ROUTES.includes(r) ? r : '';
}
function cbGo(route) {
  window.history.pushState({}, '', route ? '/' + route : '/');
  window.dispatchEvent(new Event('cb-route'));
  window.scrollTo(0, 0);
}
function goHome(e) { if (e) e.preventDefault(); cbGo(''); }

// Mobile quick-nav (hamburger) items. type: home | anchor(section id) | route(SPA page) | href(real page).
const MENU_ITEMS = [
  { label: 'Home', type: 'home' },
  { label: 'All Services', type: 'anchor', target: 'services' },
  { label: 'Water Heaters', type: 'route', target: 'water-heaters' },
  { label: 'Blue Light Lining', type: 'route', target: 'blue-light' },
  { label: 'Underground Line Rescue', type: 'route', target: 'line-rescue' },
  { label: 'Job Videos', type: 'route', target: 'videos' },
  { label: 'Reviews', type: 'anchor', target: 'reviews' },
  { label: 'Service Areas', type: 'anchor', target: 'areas' },
  { label: 'Pricing', type: 'href', target: 'pricing' },
  { label: 'Coupons', type: 'anchor', target: 'coupons' },
  { label: 'FAQ', type: 'anchor', target: 'faq' },
  { label: 'Blog', type: 'href', target: 'blog' },
  { label: 'Floodbusterz', type: 'route', target: 'flood' },
];

function Teaser({ icon, kicker, title, blurb, cta, route, href }) {
  // route = in-app SPA page (cbGo); href = a real link (e.g. an existing static page like /blog).
  const target = href || ('/' + route);
  return (
    <section className="teaser" data-screen-label={`teaser-${route || href}`}>
      <div className="container">
        <a className="teaser-card" href={target} onClick={href ? undefined : (e) => { e.preventDefault(); cbGo(route); }}>
          <span className="teaser-icon" aria-hidden="true">{icon}</span>
          <div className="teaser-body">
            <div className="teaser-kicker">{kicker}</div>
            <h3 className="teaser-title">{title}</h3>
            <p className="teaser-blurb">{blurb}</p>
            <span className="teaser-cta">{cta} →</span>
          </div>
        </a>
      </div>
    </section>
  );
}

function DetailLayout({ label, children, onBook }) {
  return (
    <>
      <div className="topbar"><div className="container topbar-inner">
        <div className="topbar-left"><span className="pulse"><span className="pulse-dot" /> 24/7 EMERGENCY DISPATCH</span></div>
        <div><span style={{ opacity: 0.75 }}>CALL DISPATCH</span> &nbsp;<a href={`tel:${brand.phoneRaw}`} style={{ color: 'var(--accent-2)', textDecoration: 'none' }}>{brand.phone}</a></div>
      </div></div>
      <nav className="nav"><div className="container nav-inner">
        <a href="/" className="logo" onClick={goHome}><img src="logo.webp" alt="Clog Busterz Plumbing Services — Central Kentucky" className="logo-img" width="200" height="88" /></a>
        <div className="nav-links">
          <a href="/" onClick={goHome}>← Home</a>
          <a href="pricing">Pricing</a>
          <a href={`tel:${brand.phoneRaw}`} style={{ color: 'var(--accent-2)' }}>{brand.phone}</a>
        </div>
      </div></nav>
      <div className="detail-crumb"><div className="container"><a href="/" onClick={goHome}>Home</a> <span>·</span> {label}</div></div>
      {children}
      <div className="detail-foot"><div className="container">
        <a className="btn" href="/" onClick={goHome}>← Back to home</a>
        <button className="btn btn-primary" onClick={() => onBook && onBook()}>Book same-day service</button>
      </div></div>
      <footer className="footer footer-slim"><div className="container">
        <div className="footer-bottom">
          <span>© {new Date().getFullYear()} CLOG BUSTERZ PLUMBING CO. · LICENSE #{brand.license} · <a href="/" onClick={goHome} style={{ color: 'var(--mute)', textDecoration: 'underline' }}>Home</a> · <a href="pricing" style={{ color: 'var(--mute)', textDecoration: 'underline' }}>Pricing</a> · <a href="sms-terms.html" style={{ color: 'var(--mute)', textDecoration: 'underline' }}>SMS Terms &amp; Privacy</a></span>
          <span style={{ color: 'var(--accent)' }}>● DISPATCH ONLINE</span>
        </div>
      </div></footer>
    </>
  );
}

const QUEST_ITEMS = [
  { id: 'diagnose', label: 'TRIAGE', detail: '3 taps', action: 'START', target: 'diagnose' },
  { id: 'estimate', label: 'PRICE', detail: 'ballpark', action: 'CHECK', target: 'estimate' },
  { id: 'coupon', label: 'COUPON', detail: 'spin or claim', action: 'UNLOCK', target: 'coupons' },
  { id: 'quote', label: 'DISPATCH', detail: 'send request', action: 'BOOK', target: null },
];

function HomeownerQuest({ onBook }) {
  const [done, setDone] = useStateA(() => {
    try { return JSON.parse(sessionStorage.getItem('cb-quest-progress') || '{}'); }
    catch (e) { return {}; }
  });

  const mark = (id) => {
    setDone(prev => prev[id] ? prev : { ...prev, [id]: true });
  };

  useEffectA(() => {
    const onStep = (e) => e.detail?.id && mark(e.detail.id);
    const onQuote = () => mark('quote');
    window.addEventListener('cb-quest-step', onStep);
    window.addEventListener('cb-open-book', onQuote);
    window.addEventListener('cb-open-quote', onQuote);
    return () => {
      window.removeEventListener('cb-quest-step', onStep);
      window.removeEventListener('cb-open-book', onQuote);
      window.removeEventListener('cb-open-quote', onQuote);
    };
  }, []);

  useEffectA(() => {
    sessionStorage.setItem('cb-quest-progress', JSON.stringify(done));
  }, [done]);

  const completed = QUEST_ITEMS.filter(item => done[item.id]).length;
  const pct = Math.round((completed / QUEST_ITEMS.length) * 100);
  const go = (item) => {
    if (item.id === 'quote') {
      mark('quote');
      onBook();
      return;
    }
    mark(item.id);
    const el = document.getElementById(item.target);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <div className="quest-card" aria-label="Homeowner speed run">
      <div className="quest-top">
        <div>
          <div className="quest-kicker">60-SECOND HOMEOWNER RUN</div>
          <div className="quest-title">{completed === QUEST_ITEMS.length ? 'READY FOR DISPATCH' : 'SAVE THE DAY FASTER'}</div>
        </div>
        <div className="quest-score">{pct}%</div>
      </div>
      <div className="quest-bar"><span style={{ width: `${pct}%` }} /></div>
      <div className="quest-grid">
        {QUEST_ITEMS.map(item => (
          <button key={item.id} className={`quest-step ${done[item.id] ? 'done' : ''}`} onClick={() => go(item)}>
            <span className="quest-check">{done[item.id] ? '✓' : '○'}</span>
            <span>
              <strong>{item.label}</strong>
              <small>{done[item.id] ? 'done' : item.detail}</small>
            </span>
            <em>{done[item.id] ? 'DONE' : item.action}</em>
          </button>
        ))}
      </div>
    </div>
  );
}

const LEAD_MACHINE_LANES = [
  {
    id: 'water-line-leak',
    code: 'WLL',
    title: 'Water line leak',
    signal: 'High bill, wet yard, low pressure',
    service: 'Water Line Leak Detection',
    route: 'Leak locate first, then spot repair or replacement',
    value: 'High-ticket',
    urgency: 'same day',
    tools: ['Acoustic locate', 'Spot repair', 'Full water line'],
    qualifiers: ['Is the meter spinning?', 'Any wet spots in the yard?', 'Does pressure drop at every fixture?'],
  },
  {
    id: 'water-line-replace',
    code: 'WLR',
    title: 'Water line replacement',
    signal: 'Old main, repeated leaks, bad pressure',
    service: 'Water Line Replacement',
    route: 'Find the failure point first, then walk you through repair vs. replace',
    value: 'High-ticket',
    urgency: 'today',
    tools: ['Leak locate', 'Trenchless eligibility', 'New service line'],
    qualifiers: ['Material of existing line?', 'Distance from meter to home?', 'Driveway or hardscape in path?'],
  },
  {
    id: 'sewer-point-repair',
    code: 'SPR',
    title: 'Sewer point repair',
    signal: 'Roots, belly, broken section',
    service: 'Sewer Line Point Repair',
    route: 'Camera first, find the break, fix the smallest section that solves it',
    value: 'High-ticket',
    urgency: 'today',
    tools: ['Camera inspection', 'Locator', 'HammerHead options'],
    qualifiers: ['Backup location?', 'Cleanout access?', 'Has anyone already camera scoped it?'],
  },
  {
    id: 'sewer-replacement',
    code: 'SWR',
    title: 'Sewer replacement',
    signal: 'Collapsed line or repeated backups',
    service: 'Sewer Line Replacement',
    route: 'Second opinion before digging, then compare open trench, PB30, and CIPP',
    value: 'High-ticket',
    urgency: 'this week',
    tools: ['Camera', 'PB30', 'CIPP', 'Excavation'],
    qualifiers: ['Depth of sewer?', 'Trees or driveway nearby?', 'Prior quote amount?'],
  },
  {
    id: 'cipp-pb30',
    code: 'TRN',
    title: 'CIPP or PB30 trenchless',
    signal: 'Save the lawn, driveway, or landscaping',
    service: 'Trenchless Sewer Repair - CIPP / PB30',
    route: 'Show dig-vs-save options and protect the yard when possible',
    value: 'Premium',
    urgency: 'scheduled',
    tools: ['HammerHead Bluelight', 'PB30', 'Camera proof'],
    qualifiers: ['Line diameter?', 'Pipe material?', 'Does the line still have shape?'],
  },
  {
    id: 'hybrid-water-heater',
    code: 'HWH',
    title: 'Hybrid water heater',
    signal: 'Replacement plus rebate conversation',
    service: 'Hybrid Heat Pump Water Heater Consultation',
    route: 'Size the home, check electrical, explain rebates and recovery',
    value: 'Replacement',
    urgency: 'this week',
    tools: ['Sizing', 'Install quote', 'Rebate education'],
    qualifiers: ['Tank size now?', 'Garage or basement install?', 'Electrical panel capacity?'],
  },
  {
    id: 'tankless-sizing',
    code: 'TKL',
    title: 'Tankless sizing',
    signal: 'Never run out of hot water',
    service: 'Tankless Water Heater Sizing',
    route: 'Count fixtures, estimate GPM, then match BTU and units',
    value: 'Replacement',
    urgency: 'scheduled',
    tools: ['Fixture count', 'Gas sizing', 'Endless hot water'],
    qualifiers: ['How many showers?', 'Gas or electric?', 'Any soaking tub?'],
  },
  {
    id: 'septic-leach',
    code: 'SEP',
    title: 'Septic or leach field',
    signal: 'Slow drains, yard odor, wet field',
    service: 'Septic Tank / Leach Field Service',
    route: 'Separate drain clog from tank, distribution, or field issue',
    value: 'High-intent',
    urgency: 'today',
    tools: ['Inspection', 'Line clearing', 'Repair plan'],
    qualifiers: ['Last pump date?', 'Any soggy spots?', 'Whole house slow or one fixture?'],
  },
];

function LeadMachine({ onBook, onQuote }) {
  const [activeId, setActiveId] = useStateA(LEAD_MACHINE_LANES[0].id);
  const active = LEAD_MACHINE_LANES.find(lane => lane.id === activeId) || LEAD_MACHINE_LANES[0];

  const startLane = (lane = active) => {
    onBook({
      problem: lane.id,
      presetService: lane.service,
      serviceCode: lane.code,
      notes: [
        `Lead Machine: ${lane.title}.`,
        `Customer signal: ${lane.signal}.`,
        `Recommended route: ${lane.route}.`,
        `Toolbox: ${lane.tools.join(', ')}.`,
        `Ask next: ${lane.qualifiers.join(' | ')}.`,
      ].join('\n')
    });
  };

  return (
    <section className="lead-machine" id="lead-machine" data-screen-label="lead-machine">
      <div className="container">
        <div className="lm-head">
          <div>
            <div className="eyebrow"><span className="dot" /> NOT SURE WHAT YOU NEED?</div>
            <h2>Tell us what's happening — we'll point you to the right fix.</h2>
          </div>
          <p>Tap what you're seeing and we'll match it to the right service — with the questions our techs need answered up front, so your visit is faster. You deal with us directly, never a lead site that sells your info to five contractors.</p>
        </div>

        <div className="lm-grid">
          <div className="lm-lanes" aria-label="High-value plumbing lead lanes">
            {LEAD_MACHINE_LANES.map((lane, i) => (
              <button
                key={lane.id}
                className={`lm-lane ${lane.id === active.id ? 'is-active' : ''}`}
                onClick={() => setActiveId(lane.id)}
                type="button"
              >
                <span className="lm-lane-num">{String(i + 1).padStart(2, '0')}</span>
                <span className="lm-lane-body">
                  <strong>{lane.title}</strong>
                  <small>{lane.signal}</small>
                </span>
                <em>{lane.urgency}</em>
              </button>
            ))}
          </div>

          <div className="lm-dispatch">
            <div className="lm-dispatch-top">
              <div>
                <span className="lm-ticket">RECOMMENDED</span>
                <h3>{active.service}</h3>
              </div>
              <span className="lm-code">{active.code}</span>
            </div>
            <div className="lm-route">{active.route}</div>
            <div className="lm-meta-grid">
              <div>
                <span>First step</span>
                <strong>{active.tools[0] || 'Diagnose'}</strong>
              </div>
              <div>
                <span>Speed</span>
                <strong>{active.urgency}</strong>
              </div>
              <div>
                <span>Estimate</span>
                <strong>Upfront &amp; free</strong>
              </div>
            </div>
            <div className="lm-toolbox">
              {active.tools.map(tool => <span key={tool}>{tool}</span>)}
            </div>
            <div className="lm-questions">
              <span>A few quick things we'll ask</span>
              {active.qualifiers.map(q => <p key={q}>{q}</p>)}
            </div>
            <div className="lm-actions">
              <button className="btn btn-primary" onClick={() => startLane()} type="button">BOOK THIS VISIT</button>
              <button className="btn" onClick={onQuote} type="button">60-SEC QUOTE</button>
              <a className="phone-pill" href={`tel:${brand.phoneRaw}`}>{brand.phone}</a>
            </div>
          </div>
        </div>

        <div className="lm-proof">
          <div><strong>1</strong><span>local crew — not a call center</span></div>
          <div><strong>0</strong><span>shared leads or bidding wars</span></div>
          <div><strong>{brand.googleRating}★</strong><span>from {brand.googleReviewCount} public Google reviews</span></div>
          <div><strong>24/7</strong><span>someone answers, day or night</span></div>
        </div>
      </div>
    </section>
  );
}

function App() {
  const tweaksDef = /*EDITMODE-BEGIN*/{
    "accent": "#2473c4",
    "accent2": "#4ab3ff",
    "headline": "BUSTIN' CLOGS",
    "headlineLine2": "SAVIN' DAYS",
    "tagline": "Central Kentucky's most reliable plumbing crew. Licensed, insured, and answering the phone — Sunday at 2am or Tuesday at noon.",
    "showEmergencyBar": true,
    "darkHero": true
  }/*EDITMODE-END*/;

  const [tweaks, setTweak] = window.useTweaks ? window.useTweaks(tweaksDef) : [tweaksDef, () => {}];
  const [bookOpen, setBookOpen] = useStateA(false);
  const [bookPrefill, setBookPrefill] = useStateA(null);
  const [postOpen, setPostOpen] = useStateA(null);
  const [quoteOpen, setQuoteOpen] = useStateA(false);
  const [floodOpen, setFloodOpen] = useStateA(false);
  const [route, setRoute] = useStateA(getRoute());
  const [menuOpen, setMenuOpen] = useStateA(false);

  useEffectA(() => {
    const onRoute = () => setRoute(getRoute());
    window.addEventListener('popstate', onRoute);
    window.addEventListener('cb-route', onRoute);
    return () => { window.removeEventListener('popstate', onRoute); window.removeEventListener('cb-route', onRoute); };
  }, []);

  // Live Google rating/count: live-reviews.js mutates window.CB_DATA.brand in place and
  // fires 'cb:reviews' when the app's Places-fed endpoint answers. Re-render to show it.
  // Fail-soft by design — if it never fires, the hardcoded data.js numbers stay.
  const [, bumpReviews] = useStateA(0);
  useEffectA(() => {
    const onReviews = () => bumpReviews((n) => n + 1);
    window.addEventListener('cb:reviews', onReviews);
    return () => window.removeEventListener('cb:reviews', onReviews);
  }, []);

  useEffectA(() => {
    const handler = (e) => {
      setBookPrefill(e.detail || null);
      setBookOpen(true);
    };
    const blogHandler = (e) => setPostOpen(e.detail);
    const quoteHandler = () => setQuoteOpen(true);
    const floodHandler = () => setFloodOpen(true);
    // Mobile rail "2nd Opinion" — fail-soft: use the photo modal if fun.jsx mounted it,
    // otherwise fall back to the booking form prefilled for a second opinion.
    const secondHandler = () => {
      if (window.SecondOpinionModal) { window.dispatchEvent(new Event('cb-open-second-opinion')); return; }
      setBookPrefill({
        problem: 'second-opinion',
        presetService: 'Second Opinion Before You Dig',
        serviceCode: '2ND',
        notes: 'Mobile rail: Second Opinion Before You Dig. Customer may have a sewer/water line replacement quote — camera/locate first, then compare spot repair, PB30, CIPP, and excavation.'
      });
      setBookOpen(true);
    };
    window.addEventListener('cb-open-book', handler);
    window.addEventListener('cb-open-blog', blogHandler);
    window.addEventListener('cb-open-quote', quoteHandler);
    window.addEventListener('cb-open-flood', floodHandler);
    window.addEventListener('cb-open-second-opinion-cta', secondHandler);
    return () => {
      window.removeEventListener('cb-open-book', handler);
      window.removeEventListener('cb-open-blog', blogHandler);
      window.removeEventListener('cb-open-quote', quoteHandler);
      window.removeEventListener('cb-open-flood', floodHandler);
      window.removeEventListener('cb-open-second-opinion-cta', secondHandler);
    };
  }, []);

  // Floodbusterz water-damage cross-sell is now CONTEXTUAL, not a timed popup. The old version
  // fired on exit-intent (30s) or 70% scroll (45s) for EVERY visitor — a water-damage offer shown
  // to people with no leak at all ("when a leak isn't a leak"). Now the offer appears only at the
  // END of a booking, and only when the booking is an actual water-escape job (see booking.jsx
  // `isWaterDamage`), which dispatches `cb-open-flood`; the floodHandler above opens the modal.

  // apply tweak vars
  useEffectA(() => {
    document.documentElement.style.setProperty('--accent', tweaks.accent);
    document.documentElement.style.setProperty('--accent-2', tweaks.accent2);
  }, [tweaks.accent, tweaks.accent2]);

  const openBook = (pre) => { setBookPrefill(pre); setBookOpen(true); };
  // Handle a tap on a mobile quick-nav item, then close the menu.
  const goMenu = (item) => {
    setMenuOpen(false);
    if (item.type === 'route') { cbGo(item.target); return; }
    if (item.type === 'href') { window.location.href = item.target; return; }
    if (item.type === 'home') { cbGo(''); return; }
    if (item.type === 'anchor') {
      const scroll = () => document.getElementById(item.target) && document.getElementById(item.target).scrollIntoView({ behavior: 'smooth', block: 'start' });
      if (getRoute()) { cbGo(''); setTimeout(scroll, 70); } else { setTimeout(scroll, 30); }
    }
  };
  const openLineDiagnosis = () => openBook({
    problem: 'line-rescue',
    presetService: 'Yard-Saver Line Diagnosis',
    serviceCode: 'LINE',
    notes: 'Homepage CTA: Yard-Saver Line Diagnosis. Customer wants camera/leak locate, repair-vs-replace options, and trenchless eligibility before digging.'
  });
  // 🥊 Second Opinion — open the photo-enabled reader (camera/upload a competitor's quote, the leak, or
  // the equipment plate → the same engine Plunger Pete uses gives an honest verdict). The old flow just
  // opened the booking form; the buddy asked for Pete-style photo upload, so this now opens that modal.
  // Fail-soft: if fun.jsx hasn't mounted the modal for any reason, fall back to the booking form.
  const openSecondOpinion = () => {
    if (window.SecondOpinionModal) { window.dispatchEvent(new Event('cb-open-second-opinion')); return; }
    openBook({
      problem: 'second-opinion',
      presetService: 'Second Opinion Before You Dig',
      serviceCode: '2ND',
      notes: 'Homepage CTA: Second Opinion Before You Dig. Customer may have a sewer or water line replacement quote. Camera/locate first, then compare spot repair, PB30, CIPP, and excavation.'
    });
  };

  // Deep-dive page (its own URL) — render just that section inside a slim layout, reusing
  // the booking modal so "Book" still works. The homepage's giant inline blocks become teasers.
  if (route) {
    const DEEP = {
      'water-heaters': { label: 'Water Heaters', node: window.WaterHeaters ? <window.WaterHeaters onBook={openBook} onQuote={() => setQuoteOpen(true)} /> : null },
      'blue-light': { label: 'Blue Light Pipe Lining', node: window.BlueLight ? <window.BlueLight /> : null },
      'line-rescue': { label: 'Underground Line Rescue', node: window.LineRescue ? <window.LineRescue onBook={openBook} /> : null },
      'videos': { label: 'Job Videos', node: window.VideoSection ? <window.VideoSection /> : null },
      'flood': { label: 'Floodbusterz — Water Damage', node: window.Floodbusterz ? <window.Floodbusterz /> : null },
      'facts': { label: 'Facts & FAQ', node: <AISection /> },
      'vip': { label: 'Membership — Coming Soon', node: window.VIPBlock ? <window.VIPBlock /> : null },
    };
    const d = DEEP[route];
    return (
      <>
        {window.ScrollReveal && <window.ScrollReveal />}
        <DetailLayout label={d.label} onBook={openBook}>
          {d.node}
        </DetailLayout>
        <BookingModal open={bookOpen} onClose={() => setBookOpen(false)} prefill={bookPrefill} />
        {window.QuickQuote && <window.QuickQuote open={quoteOpen} onClose={() => setQuoteOpen(false)} />}
        {window.PipePete && <window.PipePete />}
      </>
    );
  }

  return (
    <>
      {window.ScrollReveal && <window.ScrollReveal />}

      {/* TOP BAR */}
      <div className="topbar">
        <div className="container topbar-inner">
          <div className="topbar-left">
            <span className="pulse"><span className="pulse-dot" /> 24/7 EMERGENCY DISPATCH</span>
            <span style={{display: 'none'}} className="hide-sm">LICENSE #{brand.license}</span>
            <span style={{opacity: 0.75}} className="hide-sm">SERVING CENTRAL KY SINCE {brand.since}</span>
          </div>
          <div>
            <span style={{opacity: 0.75}}>CALL DISPATCH</span> &nbsp;<a href={`tel:${brand.phoneRaw}`} style={{color: 'var(--accent-2)', textDecoration: 'none'}}>{brand.phone}</a>
          </div>
        </div>
      </div>

      {/* NAV */}
      <nav className="nav">
        <div className="container nav-inner">
          <a href="#" className="logo">
            <img src="logo.webp" alt="Clog Busterz Plumbing Services — Madison & Fayette County KY" className="logo-img" width="200" height="88" />
          </a>
          <button className="nav-burger" onClick={() => setMenuOpen(true)} aria-label="Open menu" aria-expanded={menuOpen}>
            <span /><span /><span />
          </button>
          {/* Desktop nav: 8 essentials only. Everything else lives in the mobile menu,
              footer, and the homepage sections themselves — 16 links made the bar overflow
              and shove the phone number off-screen. */}
          <div className="nav-links">
            <a href="#services">Services</a>
            <a href="pricing">Pricing</a>
            <a href="/water-heaters" onClick={(e) => { e.preventDefault(); cbGo('water-heaters'); }}>Water Heaters</a>
            <a href="/blue-light" onClick={(e) => { e.preventDefault(); cbGo('blue-light'); }}>Blue Light</a>
            <a href="/flood" onClick={(e) => { e.preventDefault(); cbGo('flood'); }}>Floodbusterz</a>
            <a href="#brain">Brain AI</a>
            <a href="blog">Blog</a>
            <a href="#coupons">Coupons</a>
          </div>
          <div className="nav-cta">
            <button className="btn btn-ghost" onClick={() => setQuoteOpen(true)}>QUICK QUOTE</button>
            <a href={`tel:${brand.phoneRaw}`} className="phone-pill">
              <span className="ic">●</span>{brand.phone}
            </a>
          </div>
        </div>
      </nav>

      {/* HERO */}
      <section className="hero" style={{padding: '80px 0 0'}} data-screen-label="hero">
        {window.HeroCinema && <window.HeroCinema />}
        <div className="container">
          <div className="hero-eye">
            <span className="live"><span className="live-dot" />24/7 · DISPATCH OPEN</span>
            <span>MADISON & FAYETTE COUNTY · LIC #{brand.license}</span>
            <span>SAME-DAY · 24/7 EMERGENCY · UPFRONT PRICING</span>
          </div>
          <div className="hero-grid">
            <div>
              <h1>
                {tweaks.headline}<br/>
                <span className="accent">{tweaks.headlineLine2}.</span>
              </h1>
              <p className="hero-sub">24/7 plumber for drains, water heaters, water lines, sewer repairs, septic, and trenchless options in Lexington, Richmond, and Central Kentucky.</p>
              <div className="hero-proof-line">
                Camera first. Leak locate first. Repair-vs-replace options before anyone talks big money.
              </div>
              <div className="hero-cta">
                <a href={`tel:${brand.phoneRaw}`} className="phone-pill">
                  <span>●</span>{brand.phone}
                </a>
                <button className="btn" style={{borderColor: 'var(--accent-2)', color: 'var(--accent-2)'}} onClick={openLineDiagnosis}>
                  GET A LINE DIAGNOSIS
                </button>
                <button className="btn" style={{borderColor: 'var(--paper)', color: 'var(--paper)'}} onClick={() => openBook()}>
                  BOOK SAME-DAY SERVICE
                </button>
                {/* HIDDEN 7/11 — "Free Second Opinion" photo flow posts to /api/second-opinion,
                    which is NOT live on prod yet (404). Restore this button once that route ships. */}
              </div>
            </div>
            <div className="hero-side">
              <div className="receipt-headline">
                <span>★ GOOGLE REVIEWS</span>
                <span style={{color: 'var(--ok)'}}>● VERIFIED</span>
              </div>
              <a href={brand.googleReviewsUrl} target="_blank" rel="noopener noreferrer" className="hero-rating-card">
                <div className="hero-rating-top">
                  <span className="hero-rating-num">{brand.googleRating}</span>
                  <div>
                    <StarRow n={5} />
                    <div className="hero-rating-count">{brand.googleReviewCount} public Google reviews</div>
                  </div>
                </div>
              </a>
              <div className="receipt">
                <div className="receipt-row"><span>LICENSED</span><span className="v">KY #{brand.license}</span></div>
                <div className="receipt-row"><span>FAMILY-OWNED</span><span className="v">SINCE 2016</span></div>
                <div className="receipt-row"><span>SERVICE AREA</span><span className="v">{brand.region.toUpperCase()}</span></div>
                <div className="receipt-row"><span>EMERGENCY</span><span className="v accent">24 / 7</span></div>
              </div>
              <a href={brand.googleReviewsUrl} target="_blank" rel="noopener noreferrer" className="hero-review-link">Read all {brand.googleReviewCount} Google reviews →</a>
              <HomeownerQuest onBook={() => openBook()} />
            </div>
          </div>

          <div className="hero-img hero-dispatch-board" aria-label="How Clog Busterz prioritizes service">
            <div className="hero-board-top">
              <span>HOW WE DISPATCH</span>
              <span className="hero-board-live"><span className="live-dot" /> 24/7 · REAL HUMANS</span>
            </div>
            <div className="hero-route-grid">
              <div className="hero-route-card hot">
                <span className="route-code">P1</span>
                <strong>EMERGENCIES</strong>
                <small>Burst pipes · floods · sewage — 24/7</small>
              </div>
              <div className="hero-route-card">
                <span className="route-code">P2</span>
                <strong>NO HOT WATER</strong>
                <small>Water heater repair or replace</small>
              </div>
              <div className="hero-route-card">
                <span className="route-code">P3</span>
                <strong>DRAIN &amp; SEWER</strong>
                <small>Camera-first diagnosis</small>
              </div>
            </div>
            <div className="hero-board-bottom">
              <div>
                <span className="truck-dot" />
                <strong>LICENSED · INSURED</strong>
                <small>Central KY · family-owned since 2016</small>
              </div>
              <button className="hero-board-cta" onClick={() => openBook()}>REQUEST A VISIT →</button>
            </div>
          </div>
        </div>
        <div style={{marginTop: 64}}>
          <StatStrip />
        </div>
      </section>

      {/* MARQUEE */}
      <Marquee items={[
        "DRAIN CLEANING", "SEWER SCOPE", "WATER HEATER", "EMERGENCY 24/7",
        "REPIPE", "LEAK DETECTION", "GAS LINE", "TANKLESS",
        "LICENSED · INSURED", "FAMILY OWNED",
      ]} />

      {/* GOOGLE GUARANTEED */}
      {window.GoogleGuaranteed && <window.GoogleGuaranteed onQuote={() => setQuoteOpen(true)} />}

      {/* LOCAL LEAD MACHINE */}
      <LeadMachine onBook={openBook} onQuote={() => setQuoteOpen(true)} />

      {/* UNDERGROUND LINE RESCUE — teaser → its own page */}
      <Teaser route="line-rescue" icon="🚰" kicker="Sewer & water lines · trenchless"
        title="Underground Line Rescue"
        blurb="Buried sewer or water line acting up? We camera it first, locate the problem, then lay out repair-vs-replace options — spot repair, PB30, or no-dig CIPP — before anyone touches your yard."
        cta="See line rescue options" />

      {/* SERVICES */}
      <section className="services" id="services" data-screen-label="services">
        <div className="container">
          <div className="sec-head">
            <div>
              <div className="eyebrow"><span className="dot" /> 02 · SERVICES</div>
              <h2>Sixteen<br/>specialties.<br/>One crew.</h2>
            </div>
            <p>From a slow drain to a full repipe — and everything that drips, runs, or floods in between. Every job gets upfront pricing and a workmanship warranty.</p>
          </div>
          <div className="services-grid">
            {services.map(s => (
              <ServiceCard
                key={s.id}
                svc={s}
                onClick={(svc) => openBook({ problem: svc.id, presetService: svc.name })}
              />
            ))}
          </div>
          <BadgeRow />
        </div>
      </section>

      {/* DIAGNOSE */}
      <section className="diagnose-section" id="diagnose" data-screen-label="diagnose">
        <div className="container">
          <div className="sec-head" style={{color: 'var(--paper)'}}>
            <div>
              <div className="eyebrow"><span className="dot" /> 03 · TRIAGE</div>
              <h2 style={{color: 'var(--paper)'}}>Don't know<br/>what's wrong?</h2>
            </div>
            <p style={{color: 'color-mix(in oklab, var(--paper) 70%, transparent)'}}>
              Skip the phone tree. Tell us what's happening, where it's happening, and how fast you need a crew. We'll route you in three taps.
            </p>
          </div>
          <Diagnose />
        </div>
      </section>

      {/* AREAS */}
      <section className="areas" id="areas" data-screen-label="areas">
        <div className="container">
          <div className="sec-head">
            <div>
              <div className="eyebrow"><span className="dot" /> 04 · COVERAGE</div>
              <h2>Madison &<br/>Fayette<br/>County.</h2>
            </div>
            <p>Headquartered in Richmond (Madison County) with a Lexington location (Fayette County) — plus 21 more Central Kentucky cities. In our coverage zone, you're a same-day call.</p>
          </div>
          <div className="areas-grid">
            {areas.map((a, i) => (
              <div key={a} className="area-cell">
                <span className="area-num">{String(i+1).padStart(2,'0')}</span>
                <span>{a}</span>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* WHY */}
      <section className="why" id="why" data-screen-label="why">
        <div className="container">
          <div className="sec-head">
            <div>
              <div className="eyebrow" style={{color: 'var(--accent-2)'}}><span className="dot" /> 05 · WHY US</div>
              <h2 style={{color: 'var(--paper)'}}>Four reasons<br/>we get the call.</h2>
            </div>
            <p style={{color: 'color-mix(in oklab, var(--paper) 70%, transparent)'}}>
              We're not the cheapest. We're the ones who answer at 2am, show up when we say, and stand behind the work for years.
            </p>
          </div>
          <div className="why-grid">
            <div className="why-cell">
              <div className="why-num">01</div>
              <h3 className="why-h">Customer-care focused</h3>
              <p className="why-p">Real humans on the phone. Real techs at the door. No upsell theater, no surprise invoices, no “while we're here” shakedowns.</p>
            </div>
            <div className="why-cell">
              <div className="why-num">02</div>
              <h3 className="why-h">Family owned, three generations</h3>
              <p className="why-p">Three generations of plumbers means three generations of know-how on every truck — and a name on the side that we actually care about.</p>
            </div>
            <div className="why-cell">
              <div className="why-num">03</div>
              <h3 className="why-h">Licensed, insured, certified</h3>
              <p className="why-p">License #{brand.license}. Fully bonded. Our techs are factory-certified on Bradford White, A.O. Smith, Rheem, and Rinnai gear.</p>
            </div>
            <div className="why-cell">
              <div className="why-num">04</div>
              <h3 className="why-h">Quality craftsmanship, warrantied</h3>
              <p className="why-p">High-quality parts, code-clean installs, written warranties on labor and equipment. If it breaks under warranty, we're back the next day.</p>
            </div>
          </div>
        </div>
      </section>

      {/* VIDEOS — teaser → its own page */}
      <Teaser route="videos" icon="🎬" kicker="Real jobs · on camera"
        title="See the Crew in Action"
        blurb="Real Clog Busterz jobs across Central Kentucky — Blue Light pipe lining, same-day water heater swaps, drain camera finds. Watch how we work before we ever knock on your door."
        cta="Watch job videos" />

      {/* REVIEWS */}
      <section className="reviews" id="reviews" data-screen-label="reviews">
        <div className="container">
          <div className="sec-head">
            <div>
              <div className="eyebrow"><span className="dot" /> 06 · TESTIMONY</div>
              <h2>What the<br/>neighbors say.</h2>
            </div>
            <div className="reviews-proof">
              <p>{brand.googleRating} average across {brand.googleReviewCount} public Google reviews. Real customer excerpts, linked back to the Google profile.</p>
              <a href={brand.googleReviewsUrl} target="_blank" rel="noopener noreferrer">Read all Google reviews</a>
            </div>
          </div>
          <div className="reviews-grid">
            {reviews.map((r, i) => (
              <div key={i} className="review">
                <div className="review-head">
                  <StarRow n={r.stars} />
                  <span style={{fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.16em', color: 'var(--mute)'}}>R-{String(i+1).padStart(3,'0')}</span>
                </div>
                <div className="review-text">"{r.text}"</div>
                <div className="review-foot">
                  <span className="rname">— {r.name}</span>
                  <span>{r.source || `${r.area}, KY`}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* EMERGENCY BAR */}
      {tweaks.showEmergencyBar && (
        <div className="emergency-bar" data-screen-label="emergency">
          <div className="container emergency-inner">
            <div>
              <div className="emergency-h">
                <span className="blink">●</span> BURST PIPE? FLOODED BASEMENT?
              </div>
              <div className="emergency-sub">24/7 EMERGENCY DISPATCH · FAST LOCAL RESPONSE · {brand.region.toUpperCase()}</div>
            </div>
            <a href={`tel:${brand.phoneRaw}`} className="emergency-cta">
              CALL {brand.phone} →
            </a>
          </div>
        </div>
      )}

      {/* CITY SPOTLIGHT */}
      <CitySpotlight />

      {/* WATER HEATERS — teaser → its own page */}
      <Teaser route="water-heaters" icon="🔥" kicker="Tank · tankless · same-day"
        title="Water Heaters, Done Right"
        blurb="No hot water, or ready to upgrade? Same-day installs on Rheem & A.O. Smith, tank or tankless, factory-certified techs — and $100 off any install. See sizes, options, and pricing."
        cta="See water heater options" />

      {/* BLUE LIGHT PIPE LINING — teaser → its own page */}
      <Teaser route="blue-light" icon="💡" kicker="Trenchless · no-dig repair"
        title="Blue Light Pipe Lining"
        blurb="Fix a broken pipe without tearing up the yard. HammerHead Blue Light LED-cured CIPP rebuilds the pipe from the inside — cleaner, faster, and warrantied. See how it works."
        cta="See how Blue Light works" />

      {/* FLOODBUSTERZ — SISTER COMPANY — teaser → its own page */}
      <Teaser route="flood" icon="🌊" kicker="Sister company · restoration"
        title="Water Damage? Meet Floodbusterz"
        blurb="Burst pipe or flood already did the damage? Floodbusterz is our sister company — water extraction, structural drying, and insurance-claim help. Separate crews, same family, one call handles both."
        cta="See Floodbusterz" />

      {/* ESTIMATOR */}
      <Estimator />

      {/* BLOG — teaser → the existing /blog page */}
      <Teaser href="blog" icon="📝" kicker="Guides · costs · straight talk"
        title="The Clog Busterz Blog"
        blurb="Plain-English guides on what plumbing really costs, when to repair vs replace, and how to avoid getting oversold — written by the crew, not a marketing agency."
        cta="Read the blog" />

      {/* COUPONS */}
      <Coupons />

      {/* PIPE LOTTERY */}
      {window.PipeLottery && <window.PipeLottery />}

      {/* VIP — teaser → its own /vip page (membership is coming soon, not live) */}
      <Teaser route="vip" icon="🏅" kicker="Coming soon"
        title="CB Gold Card Membership"
        blurb="One membership across the whole Busterz family — annual inspections, member pricing, priority dispatch, no after-hours fees. Launching soon; get on the early list to be first to know."
        cta="See what's coming" />

      {/* FAQ */}
      <FAQ />

      {/* PLUMBER'S BRAIN AI */}
      {window.PlumberBrain && <window.PlumberBrain />}
      {window.SecondOpinionModal && <window.SecondOpinionModal />}

      {/* AI-READY FACTS — moved to its own /facts page (crawler/utility content), linked from the footer */}

      {/* FOOTER */}
      <footer className="footer">
        <div className="container">
          <div className="footer-top">
            <div>
              <div className="footer-brand">CLOG<br/><span className="accent">BUSTERZ.</span></div>
              <p className="footer-tag">{brand.tagline}. Licensed plumbing services across {brand.region}, since {brand.since}.</p>
            </div>
            <div>
              <div className="footer-h">SERVICES</div>
              <ul className="footer-list">
                <li><a href="#services">Drain Cleaning</a></li>
                <li><a href="#services">Emergency Plumbing</a></li>
                <li><a href="#services">Water Heaters</a></li>
                <li><a href="#services">Sewer Services</a></li>
                <li><a href="#services">Repiping</a></li>
                <li><a href="#services">Commercial</a></li>
                <li><a href="pricing" style={{color: 'var(--accent-2)'}}>See Our Prices →</a></li>
              </ul>
            </div>
            <div>
              <div className="footer-h">COMPANY</div>
              <ul className="footer-list">
                <li><a href="#why">About</a></li>
                <li><a href="pricing">Upfront Pricing</a></li>
                <li><a href="#areas">Service Areas</a></li>
                <li><a href="#reviews">Reviews</a></li>
                <li><a href="blog">Blog</a></li>
                <li><a href="/videos" onClick={(e) => { e.preventDefault(); cbGo('videos'); }}>Job Videos</a></li>
                <li><a href="/vip" onClick={(e) => { e.preventDefault(); cbGo('vip'); }}>Membership (soon)</a></li>
                <li><a href="/facts" onClick={(e) => { e.preventDefault(); cbGo('facts'); }}>Facts &amp; FAQ</a></li>
                <li><a href="#" onClick={(e) => { e.preventDefault(); openBook(); }}>Book Online</a></li>
              </ul>
            </div>
            <div>
              <div className="footer-h">DISPATCH</div>
              <ul className="footer-list">
                <li><a href={`tel:${brand.phoneRaw}`} style={{color: 'var(--accent-2)', fontFamily: 'var(--serif)', fontSize: 22}}>{brand.phone}</a></li>
                <li style={{marginTop: 8, color: 'var(--mute)', fontFamily: 'var(--mono)', fontSize: 12, letterSpacing: '0.04em'}}>📍 {brand.address}</li>
                <li style={{marginTop: 4, color: 'var(--mute)', fontFamily: 'var(--mono)', fontSize: 12, letterSpacing: '0.04em'}}>📍 {brand.addressLex}</li>
                <li style={{marginTop: 16, color: 'var(--mute)', fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.16em'}}>LICENSE #{brand.license}</li>
              </ul>
            </div>
          </div>
          <div className="footer-bottom">
            <span>© {new Date().getFullYear()} CLOG BUSTERZ PLUMBING CO. · ALL RIGHTS RESERVED · <a href="sms-terms.html" style={{color: 'var(--mute)', textDecoration: 'underline'}}>SMS Terms &amp; Privacy</a> · <a href="plumbers-brain/usage/" style={{color: 'var(--mute)', textDecoration: 'underline'}}>Plumber's Brain Use Notice</a></span>
            <span style={{color: 'var(--accent)'}}>● DISPATCH ONLINE</span>
          </div>
        </div>
      </footer>

      <BookingModal open={bookOpen} onClose={() => setBookOpen(false)} prefill={bookPrefill} />
      <BlogPostModal post={postOpen} onClose={() => setPostOpen(null)} />
      {window.QuickQuote && <window.QuickQuote open={quoteOpen} onClose={() => setQuoteOpen(false)} />}
      {window.FloodHoverModal && <window.FloodHoverModal open={floodOpen} onClose={() => setFloodOpen(false)} />}
      {window.QuotePill && <window.QuotePill onClick={() => setQuoteOpen(true)} />}
      <MobileCallBar />
      {window.ToTop && <window.ToTop />}

      {/* MOBILE QUICK-NAV (hamburger menu) */}
      {menuOpen && (
        <div className="mnav-overlay" onClick={() => setMenuOpen(false)}>
          <div className="mnav-panel" onClick={(e) => e.stopPropagation()}>
            <div className="mnav-head">
              <img src="logo.webp" alt="Clog Busterz" className="mnav-logo" />
              <button className="mnav-close" onClick={() => setMenuOpen(false)} aria-label="Close menu">Close ✕</button>
            </div>
            <div className="mnav-list">
              {MENU_ITEMS.map((item) => (
                <a key={item.label}
                   href={item.type === 'route' ? '/' + item.target : item.type === 'href' ? item.target : item.type === 'anchor' ? '/#' + item.target : '/'}
                   onClick={(e) => { e.preventDefault(); goMenu(item); }}>
                  <span>{item.label}</span>
                  {item.type === 'route' && <span className="mnav-arrow">›</span>}
                </a>
              ))}
            </div>
            <div className="mnav-cta">
              <button className="mnav-book" onClick={() => { setMenuOpen(false); openBook(); }}>📅 BOOK ONLINE</button>
              <a className="mnav-call" href={`tel:${brand.phoneRaw}`} onClick={() => setMenuOpen(false)}>📞 CALL {brand.phone}</a>
            </div>
          </div>
        </div>
      )}
      {window.PipePete && <window.PipePete />}
      {window.PlungerRain && <window.PlungerRain />}

      {window.TweaksPanel && (
        <window.TweaksPanel title="Tweaks">
          <window.TweakSection title="Theme">
            <window.TweakColor label="Accent (orange)" value={tweaks.accent} onChange={v => setTweak('accent', v)} />
            <window.TweakColor label="Accent 2 (yellow)" value={tweaks.accent2} onChange={v => setTweak('accent2', v)} />
          </window.TweakSection>
          <window.TweakSection title="Hero copy">
            <window.TweakText label="Headline line 1" value={tweaks.headline} onChange={v => setTweak('headline', v)} />
            <window.TweakText label="Headline line 2" value={tweaks.headlineLine2} onChange={v => setTweak('headlineLine2', v)} />
            <window.TweakText label="Tagline" value={tweaks.tagline} onChange={v => setTweak('tagline', v)} multiline />
          </window.TweakSection>
          <window.TweakSection title="Sections">
            <window.TweakToggle label="Emergency bar" value={tweaks.showEmergencyBar} onChange={v => setTweak('showEmergencyBar', v)} />
          </window.TweakSection>
        </window.TweaksPanel>
      )}
    </>
  );
}

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