// Blog list, single post, FAQ, coupons, calculator components
const { useState: useStateBL } = React;

function BlogStrip({ onOpen }) {
  return (
    <section className="blog-strip" id="blog" data-screen-label="blog">
      <div className="container">
        <div className="sec-head">
          <div>
            <div className="eyebrow"><span className="dot" /> 07 · FIELD NOTES</div>
            <h2>Plumbing<br/>knowledge,<br/>local context.</h2>
          </div>
          <p>Real advice from real jobs across Lexington, Richmond, and the rest of Central Kentucky. Written by the crew, not by an SEO bot.</p>
        </div>
        <div className="blog-grid">
          {window.CB_BLOG.map((p, i) => (
            <button key={p.slug} className="blog-card" onClick={() => onOpen(p)} data-screen-label={`blog-${p.slug}`}>
              <div className={`blog-thumb thumb-${i % 4}`}>
                <span className="blog-thumb-tag">📷 PHOTO COMING SOON</span>
              </div>
              <div className="blog-meta">
                <span className="blog-cat">{p.cat}</span>
                <span>·</span>
                <span>{p.date}</span>
                <span>·</span>
                <span>{p.read}</span>
              </div>
              <h3 className="blog-title">{p.title}</h3>
              <p className="blog-excerpt">{p.excerpt}</p>
              <div className="blog-read">READ ARTICLE →</div>
            </button>
          ))}
        </div>
        <div className="blog-foot">
          <button className="btn">VIEW ALL ARTICLES →</button>
          <div className="blog-foot-note">New post every two weeks. <a href="#">Subscribe to the dispatch newsletter →</a></div>
        </div>
      </div>
    </section>
  );
}

function BlogPostModal({ post, onClose }) {
  if (!post) return null;
  const related = window.CB_BLOG.filter(p => p.slug !== post.slug).slice(0, 2);
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal post-modal" onClick={e => e.stopPropagation()}>
        <div className="post-head">
          <button className="modal-x" onClick={onClose} style={{position:'absolute',top:24,right:24}}>×</button>
          <div className="post-meta">
            <span className="post-cat">{post.cat}</span>
            <span>·</span>
            <span>{post.date}</span>
            <span>·</span>
            <span>{post.read} read</span>
          </div>
          <h1 className="post-title">{post.title}</h1>
          <div className="post-author">By {post.author}</div>
        </div>
        <div className={`post-hero thumb-1`}>
          <span className="blog-thumb-tag">📷 PHOTO COMING SOON</span>
        </div>
        <article className="post-body">
          <p className="post-lede">{post.excerpt}</p>
          {post.sections.map((s, i) => (
            <div key={i}>
              <h2>{s.h}</h2>
              <p>{s.p}</p>
            </div>
          ))}
          <div className="post-cta">
            <div className="post-cta-tag">CALL TO ACTION</div>
            <p>{post.cta}</p>
            <div className="post-cta-actions">
              <a href="tel:8594083382" className="btn btn-primary">CALL 859-408-3382</a>
              <button className="btn btn-ghost" onClick={() => { onClose(); window.dispatchEvent(new CustomEvent('cb-open-book')); }}>BOOK ONLINE →</button>
            </div>
          </div>
          <div className="post-tags">
            {post.tags.map(t => <span key={t} className="post-tag">#{t}</span>)}
          </div>
        </article>
        <div className="post-related">
          <div className="post-related-h">RELATED ARTICLES</div>
          <div className="post-related-grid">
            {related.map(r => (
              <button key={r.slug} className="related-card" onClick={() => { document.querySelector('.modal').scrollTo({top:0}); window.dispatchEvent(new CustomEvent('cb-open-blog', { detail: r })); }}>
                <div className="related-cat">{r.cat}</div>
                <div className="related-title">{r.title}</div>
                <div className="related-arrow">→</div>
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function FAQ() {
  const [open, setOpen] = useStateBL(0);
  return (
    <section className="faq" id="faq" data-screen-label="faq">
      <div className="container">
        <div className="sec-head">
          <div>
            <div className="eyebrow"><span className="dot" /> 08 · FAQ</div>
            <h2>Questions<br/>before you<br/>call us.</h2>
          </div>
          <p>If your question's not here, ring <a href="tel:8594083382" style={{color:'var(--ink)',fontWeight:600}}>859-408-3382</a> — we answer in person, not a robot.</p>
        </div>
        <div className="faq-list">
          {window.CB_FAQ.map((f, i) => (
            <div key={i} className={`faq-item ${open === i ? 'open' : ''}`}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span className="faq-num">{String(i+1).padStart(2,'0')}</span>
                <span className="faq-q-text">{f.q}</span>
                <span className="faq-toggle">{open === i ? '−' : '+'}</span>
              </button>
              {open === i && <div className="faq-a">{f.a}</div>}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Coupons() {
  const [claimed, setClaimed] = useStateBL('');
  const claimCoupon = (code) => {
    navigator.clipboard?.writeText(code);
    setClaimed(code);
    window.dispatchEvent(new CustomEvent('cb-quest-step', { detail: { id: 'coupon' } }));
    window.dispatchEvent(new CustomEvent('cb-open-quote'));
  };

  return (
    <section className="coupons" id="coupons" data-screen-label="coupons">
      <div className="container">
        <div className="sec-head">
          <div>
            <div className="eyebrow" style={{color:'var(--accent-2)'}}><span className="dot" /> 09 · DEALS</div>
            <h2 style={{color:'var(--paper)'}}>Save on<br/>your next<br/>service call.</h2>
          </div>
          <p style={{color:'color-mix(in oklab, var(--paper) 70%, transparent)'}}>Mention the code at booking. New customer offers refresh monthly.</p>
        </div>
        <div className="coupon-grid">
          {window.CB_COUPONS.map((c, i) => (
            <div key={i} className="coupon">
              <div className="coupon-perforation" />
              <div className="coupon-main">
                <div className="coupon-tag">CB · LIMITED OFFER</div>
                <div className="coupon-amount">{c.title}</div>
                <div className="coupon-sub">{c.sub}</div>
                <div className="coupon-terms">{c.terms}</div>
              </div>
              <div className="coupon-stub">
                <div className="coupon-code-label">CODE</div>
                <div className="coupon-code">{c.code}</div>
                <button className="coupon-claim" onClick={() => claimCoupon(c.code)}>
                  {claimed === c.code ? 'COPIED' : 'CLAIM →'}
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Estimator() {
  const [job, setJob] = useStateBL("drain");
  const [bath, setBath] = useStateBL(2);
  const [age, setAge] = useStateBL("medium");
  const markEstimate = () => window.dispatchEvent(new CustomEvent('cb-quest-step', { detail: { id: 'estimate' } }));
  const ranges = {
    drain: { base: 159, perBath: 25, ageMul: { new: 1, medium: 1.1, old: 1.3 } },
    waterheater: { base: 1800, perBath: 200, ageMul: { new: 1, medium: 1.05, old: 1.15 } },
    repipe: { base: 4200, perBath: 950, ageMul: { new: 0.9, medium: 1, old: 1.25 } },
    leak: { base: 289, perBath: 0, ageMul: { new: 1, medium: 1, old: 1.2 } },
    sewer: { base: 389, perBath: 0, ageMul: { new: 1, medium: 1.15, old: 1.4 } },
  };
  const r = ranges[job];
  const lo = Math.round((r.base + r.perBath * bath) * r.ageMul[age] * 0.92);
  const hi = Math.round((r.base + r.perBath * bath) * r.ageMul[age] * 1.18);
  return (
    <section className="estimator" id="estimate" data-screen-label="estimator">
      <div className="container">
        <div className="sec-head">
          <div>
            <div className="eyebrow"><span className="dot" /> 10 · ESTIMATE</div>
            <h2>Ballpark<br/>your job in<br/>30 seconds.</h2>
          </div>
          <p>Real ranges based on jobs we ran across Lexington and Richmond this quarter. For a firm number, we'll come out free.</p>
        </div>
        <div className="estimator-card">
          <div className="est-controls">
            <div className="est-row">
              <label className="est-label">JOB TYPE</label>
              <div className="est-pills">
                {[["drain","Drain Cleaning"],["waterheater","Water Heater"],["repipe","Repipe"],["leak","Leak Repair"],["sewer","Sewer Service"]].map(([k,l]) => (
                  <button key={k} className={`est-pill ${job===k?'on':''}`} onClick={() => { markEstimate(); setJob(k); }}>{l}</button>
                ))}
              </div>
            </div>
            <div className="est-row">
              <label className="est-label">BATHROOMS / SCALE: {bath}</label>
              <input type="range" min="1" max="5" value={bath} onChange={e => { markEstimate(); setBath(+e.target.value); }} className="est-slider" />
            </div>
            <div className="est-row">
              <label className="est-label">HOME AGE</label>
              <div className="est-pills">
                {[["new","Under 20 yrs"],["medium","20–50 yrs"],["old","Over 50 yrs"]].map(([k,l]) => (
                  <button key={k} className={`est-pill ${age===k?'on':''}`} onClick={() => { markEstimate(); setAge(k); }}>{l}</button>
                ))}
              </div>
            </div>
          </div>
          <div className="est-readout">
            <div className="est-readout-label">ESTIMATED RANGE</div>
            <div className="est-amount">${lo.toLocaleString()}<span> – ${hi.toLocaleString()}</span></div>
            <div className="est-note">Based on Lexington/Richmond jobs Q1 2026. Excludes parts upgrade and emergency dispatch fees.</div>
            <button className="btn btn-primary" onClick={() => window.dispatchEvent(new CustomEvent('cb-open-book'))}>GET A FIRM QUOTE →</button>
          </div>
        </div>
      </div>
    </section>
  );
}

function CitySpotlight() {
  const c = window.CB_CITIES[0];
  return (
    <section className="city-spot" id="lexington" data-screen-label="lexington">
      <div className="container">
        <div className="city-grid">
          <div>
            <div className="eyebrow"><span className="dot" /> 11 · CITY SPOTLIGHT</div>
            <h2 className="city-h">Plumber in {c.name}, KY</h2>
            <p className="city-blurb">{c.blurb}</p>
            <div className="city-stats">
              <div><div className="cs-n">{c.population}</div><div className="cs-l">RESIDENTS</div></div>
              <div><div className="cs-n">10+</div><div className="cs-l">YEARS LOCAL</div></div>
              <div><div className="cs-n">SAME-DAY</div><div className="cs-l">SERVICE</div></div>
            </div>
            <div className="city-actions">
              <a href="tel:8594083382" className="btn btn-primary">CALL FOR LEXINGTON SERVICE</a>
              <button className="btn btn-ghost" onClick={() => window.dispatchEvent(new CustomEvent('cb-open-book'))}>BOOK ONLINE →</button>
            </div>
          </div>
          <div className="city-side">
            <div className="city-card">
              <div className="city-card-h">COMMON ISSUES IN {c.name.toUpperCase()}</div>
              <ul className="city-list">
                {c.common.map(x => <li key={x}><span>●</span>{x}</li>)}
              </ul>
            </div>
            <div className="city-card">
              <div className="city-card-h">NEIGHBORHOODS WE SERVE</div>
              <div className="city-tags">
                {c.neighborhoods.map(n => <span key={n} className="city-tag">{n}</span>)}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function VIPBlock() {
  return (
    <section className="vip" data-screen-label="vip">
      <div className="container">
        <div className="vip-grid">
          <div>
            <div className="eyebrow"><span className="dot" /> MEMBERSHIP · COMING SOON</div>
            <h2 className="vip-h">CB GOLD CARD</h2>
            <p className="vip-sub"><strong>Coming soon.</strong> One membership across the whole Busterz family, for the household that's tired of plumbing surprises. Planned at $19/month — get on the early list and you'll be first to know when it opens.</p>
          </div>
          <ul className="vip-list">
            <li><span className="vip-check">✓</span><div><strong>Annual whole-home plumbing inspection</strong><div>21-point whole-home check, free for members.</div></div></li>
            <li><span className="vip-check">✓</span><div><strong>$25 off every repair</strong><div>Member price on every job. Cannot be combined with other offers.</div></div></li>
            <li><span className="vip-check">✓</span><div><strong>Priority dispatch</strong><div>Members go to the front of the queue, even on holidays.</div></div></li>
            <li><span className="vip-check">✓</span><div><strong>No after-hours fees</strong><div>2am call? Same rate as 2pm. Sundays included.</div></div></li>
            <li><span className="vip-check">✓</span><div><strong>Water heater flush included</strong><div>Once a year. Doubles equipment lifespan.</div></div></li>
            <li><span className="vip-check">✓</span><div><strong>Transfers with your home</strong><div>Selling? The next owner inherits the card. Great listing perk.</div></div></li>
          </ul>
        </div>

        {/* BUSTERZ FAMILY PERKS — cross-brand member benefits */}
        <div className="bf-perks">
          <div className="bf-perks-head">
            <span className="bf-perks-tag">★ EXCLUSIVE</span>
            <h3 className="bf-perks-h">BUSTERZ FAMILY PERKS</h3>
            <p className="bf-perks-sub">Your Gold Card will unlock member rates across all three Busterz companies. One family. One card. Three crews on call.</p>
          </div>
          <div className="bf-perks-grid">
            <div className="bf-brand bf-clog">
              <div className="bf-brand-name">CLOG BUSTERZ</div>
              <div className="bf-brand-tag">PLUMBING</div>
              <div className="bf-brand-perk">Everything above — inspection, flush, $25 off every repair, priority dispatch, no after-hours fees.</div>
            </div>
            <div className="bf-brand bf-flood">
              <div className="bf-brand-name">FLOODBUSTERZ</div>
              <div className="bf-brand-tag">WATER DAMAGE &amp; RESTORATION</div>
              <div className="bf-brand-perk">Members skip the mitigation assessment fee and go to the front of the restoration queue. 859-408-9611.</div>
            </div>
            <div className="bf-brand bf-lawn">
              <div className="bf-brand-name">LAWN BUSTERZ</div>
              <div className="bf-brand-tag">LAWN &amp; OUTDOOR</div>
              <div className="bf-brand-perk">Busterz Family rate on mowing, aeration &amp; cleanups — plus a free first service when you sign up as a Gold member.</div>
            </div>
          </div>
        </div>

        <div className="vip-cta">
          <button className="btn btn-primary big-btn" onClick={() => window.dispatchEvent(new CustomEvent('cb-open-book', { detail: { problem: 'membership-interest', presetService: 'CB Gold Card — early interest list', notes: 'Customer wants to be notified when the CB Gold Card membership launches. Not a booking — add to early-interest list.' }}))}>
            <span className="btn-line">GET ON THE EARLY LIST</span>
            <span className="btn-line big">MEMBERSHIP · COMING SOON</span>
          </button>
          <a href="tel:8594083382" className="btn btn-ghost">QUESTIONS? CALL 859-408-3382</a>
        </div>
      </div>
    </section>
  );
}

function MobileCallBar() {
  const openBook = () => window.dispatchEvent(new CustomEvent('cb-open-book'));
  const openBrain = () => window.dispatchEvent(new CustomEvent('cb-open-brain'));
  const openSecond = () => window.dispatchEvent(new CustomEvent('cb-open-second-opinion-cta'));
  return (
    <nav className="mobile-rail" aria-label="Quick actions">
      <a href="tel:8594083382" className="mrail-btn">
        <span className="mrail-emoji" aria-hidden="true">📞</span>
        <span className="mrail-lbl">Call</span>
      </a>
      <button type="button" className="mrail-btn" onClick={openBook}>
        <span className="mrail-emoji" aria-hidden="true">📅</span>
        <span className="mrail-lbl">Book</span>
      </button>
      <button type="button" className="mrail-btn mrail-brain" onClick={openBrain}>
        <span className="mrail-emoji" aria-hidden="true">🪠🧠</span>
        <span className="mrail-lbl">Brain</span>
      </button>
      {/* HIDDEN 7/11 — 2nd Opinion posts to /api/second-opinion (not live on prod, 404). Restore when shipped. */}
    </nav>
  );
}

// ⬆️ Back-to-top — fades in after the user scrolls down, smooth-scrolls to the top.
// Visibility is driven by inline style (beats any stylesheet cascade) so it can't get stuck hidden.
function ToTop() {
  const [show, setShow] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setShow(window.scrollY > 700);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const toTop = () => {
    try { window.scrollTo({ top: 0, behavior: 'smooth' }); } catch (e) { window.scrollTo(0, 0); }
  };
  return (
    <button className="to-top" aria-label="Back to top" title="Back to top" onClick={toTop}
      style={{ opacity: show ? 1 : 0, transform: show ? 'none' : 'translateY(12px)', pointerEvents: show ? 'auto' : 'none' }}>
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><polyline points="18 15 12 9 6 15" /></svg>
    </button>
  );
}

Object.assign(window, { BlogStrip, BlogPostModal, FAQ, Coupons, Estimator, CitySpotlight, VIPBlock, MobileCallBar, ToTop });
