// Google Verified strip + Quick Quote modal + Pipe Lottery
const { useState: useStateG, useEffect: useEffectG, useRef: useRefG } = React;

// ============== GOOGLE VERIFIED BADGE STRIP ==============
function GoogleGuaranteed({ onQuote }) {
  return (
    <section className="gg-strip" id="trust">
      <div className="container">
        <div className="gg-grid">
          <div className="gg-badge">
            <div className="gg-shield">
              <svg viewBox="0 0 40 40" width="56" height="56">
                <defs>
                  <linearGradient id="ggg" x1="0" y1="0" x2="1" y2="1">
                    <stop offset="0" stopColor="#4285F4"/>
                    <stop offset="0.5" stopColor="#34A853"/>
                    <stop offset="1" stopColor="#FBBC05"/>
                  </linearGradient>
                </defs>
                <path d="M20 2 L36 8 L36 22 Q36 32 20 38 Q4 32 4 22 L4 8 Z" fill="url(#ggg)"/>
                <path d="M14 20 L18 24 L26 16" stroke="#fff" strokeWidth="3.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>
            <div>
              <div className="gg-h">GOOGLE</div>
              <div className="gg-h2">VERIFIED</div>
              <div className="gg-sub">License-verified · Insured · Local Services profile</div>
            </div>
          </div>

          <div className="gg-stat">
            <div className="gg-stat-stars">
              <span>★★★★★</span>
              <span className="gg-stat-num">4.8</span>
            </div>
            <div className="gg-stat-l">798 GOOGLE REVIEWS</div>
            <div className="gg-stat-tiny">Verification checks shown on Google Local Services</div>
          </div>

          <div className="gg-stat">
            <div className="gg-stat-num accent">10+</div>
            <div className="gg-stat-l">YEARS IN BUSINESS</div>
            <div className="gg-stat-tiny">Family-owned since 2016</div>
          </div>

          <div className="gg-stat">
            <div className="gg-stat-num accent">24/7</div>
            <div className="gg-stat-l">DISPATCH OPEN</div>
            <div className="gg-stat-tiny">Real humans · No phone tree · No callback queue</div>
          </div>

          <div className="gg-cta-wrap">
            <button className="gg-cta" onClick={onQuote}>
              <span className="gg-cta-bolt">⚡</span>
              <span>
                <span className="gg-cta-l1">GET A QUOTE</span>
                <span className="gg-cta-l2">IN 60 SECONDS</span>
              </span>
            </button>
            <div className="gg-cta-tiny">No spam · No upsells · Real plumber callback</div>
          </div>
        </div>
      </div>
    </section>
  );
}
window.GoogleGuaranteed = GoogleGuaranteed;

// ============== QUICK QUOTE MODAL (LSA-style) ==============
function QuickQuote({ open, onClose }) {
  const [step, setStep] = useStateG('form'); // form | success
  const [form, setForm] = useStateG({ name: '', phone: '', email: '', service: '', urgency: '', smsConsent: false, emailConsent: false });

  useEffectG(() => {
    if (!open) { setStep('form'); setForm({ name: '', phone: '', email: '', service: '', urgency: '', smsConsent: false, emailConsent: false }); }
  }, [open]);

  if (!open) return null;
  const validEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim());
  const valid = form.name.trim() && form.phone.replace(/\D/g, '').length >= 10 && validEmail && form.service;
  const urgencyForBoard = ({ now: 'emergency', today: 'today', week: 'this week', quote: 'flexible' })[form.urgency] || 'flexible';

  const submit = async () => {
    if (!valid) return;
    // ── 1. DISPATCH INTAKE — and actually CHECK the result (a swallowed failure here
    //      showed the customer "success" while the lead evaporated; booking.jsx pattern).
    let primaryOk = false;
    if (window.CB_DISPATCH) {
      try {
        const res = await window.CB_DISPATCH.sendLead({
          source: 'quick-quote',
          name: form.name,
          phone: form.phone,
          email: form.email.trim(),
          service: form.service,
          urgency: urgencyForBoard,
          smsConsent: form.smsConsent ? 'yes' : 'no',
          emailConsent: form.emailConsent ? 'yes' : 'no',
        });
        primaryOk = !!(res && res.ok);
      } catch (e) { primaryOk = false; }
    }
    // ── 2. BACKUP — if dispatch didn't clearly succeed, capture via Formspree so the
    //      lead is NEVER lost (emails the office, same failover as the booking modal).
    let backupOk = false;
    if (!primaryOk) {
      try {
        const fr = await fetch('https://formspree.io/f/mbdekjeo', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            _subject: `⚠️ CB Quick Quote BACKUP · ${form.service || 'General'} · ${form.urgency || ''}`,
            _cc: 'ronniem@clogbusterzplumbing.com,devin@clogbusterzplumbing.com',
            name: form.name,
            phone: form.phone,
            email: form.email.trim(),
            service: form.service,
            urgency: urgencyForBoard,
            smsConsent: form.smsConsent ? 'yes' : 'no',
            emailConsent: form.emailConsent ? 'yes' : 'no',
            consentText: window.CB_DISPATCH ? window.CB_DISPATCH.CONSENT_TEXT : '',
            alert: 'PRIMARY DISPATCH SEND FAILED — please follow up with this customer manually.',
            source: 'Quick Quote - Google Verified strip (backup path)',
          })
        });
        backupOk = !!(fr && fr.ok);
      } catch (e) { console.warn('Quick Quote backup error', e); }
    }
    // ── 3. Both failed → be honest, keep them on the form to retry or call.
    if (!primaryOk && !backupOk) {
      alert("We couldn't reach dispatch just now — please call 859-408-3382 so we don't miss you, or try again in a moment. Your details are still here.");
      return;
    }
    setStep('success');
  };

  return (
    <div className="qq-modal" onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div className="qq-card">
        {step === 'form' && (
          <>
            <div className="qq-head">
              <div className="qq-head-truck">
                <div className="qq-head-truck-bg"></div>
                <div className="qq-head-truck-tag">📷 PHOTO COMING SOON</div>
                <div className="qq-head-badge">
                  <svg viewBox="0 0 40 40" width="32" height="32">
                    <path d="M20 3 L35 8 L35 22 Q35 30 20 37 Q5 30 5 22 L5 8 Z" fill="#34A853"/>
                    <path d="M14 20 L18 24 L26 16" stroke="#fff" strokeWidth="3.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                  <span>GOOGLE<br/>VERIFIED</span>
                </div>
              </div>
              <button className="qq-x" onClick={onClose}>×</button>
            </div>
            <div className="qq-body">
              <div className="qq-eyebrow">CLOG BUSTERZ PLUMBING · LIC #M7707</div>
              <h3 className="qq-h">Get a real quote.<br/>From a real plumber.</h3>
              <p className="qq-sub">Fill this out and we'll call you back fast. No bots. No mass emails. Just a Clog Busterz human.</p>

              <div className="qq-fields">
                <label className="qq-field">
                  <span>Your name</span>
                  <input value={form.name} onChange={e => setForm({...form, name: e.target.value})} placeholder="Jane Smith" />
                </label>
                <label className="qq-field">
                  <span>Phone</span>
                  <input type="tel" value={form.phone} onChange={e => setForm({...form, phone: e.target.value})} placeholder="(859) 555-1234" />
                </label>
                <label className="qq-field">
                  <span>Email</span>
                  <input type="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} placeholder="you@example.com" />
                </label>
                <label className="qq-field">
                  <span>What do you need?</span>
                  <select value={form.service} onChange={e => setForm({...form, service: e.target.value})}>
                    <option value="">Pick a service —</option>
                    <option>Drain cleaning</option>
                    <option>Emergency / flooding</option>
                    <option>Water heater</option>
                    <option>Sewer / Blue Light CIPP</option>
                    <option>Trenchless / PB30</option>
                    <option>Leak detection</option>
                    <option>Repipe</option>
                    <option>Toilet repair</option>
                    <option>Gas line</option>
                    <option>Something else</option>
                  </select>
                </label>
                <div className="qq-urgency">
                  <span className="qq-urgency-l">How urgent?</span>
                  <div className="qq-urgency-row">
                    {[
                      { id: 'now', l: '🚨 RIGHT NOW', d: 'Active flood/no water' },
                      { id: 'today', l: '⚡ TODAY', d: 'Same-day service' },
                      { id: 'week', l: '📅 THIS WEEK', d: 'Schedule it' },
                      { id: 'quote', l: '💰 JUST QUOTING', d: 'Comparing options' },
                    ].map(u => (
                      <button key={u.id} className={`qq-u ${form.urgency === u.id ? 'on' : ''}`} onClick={() => setForm({...form, urgency: u.id})} type="button">
                        <span className="qq-u-l">{u.l}</span>
                        <span className="qq-u-d">{u.d}</span>
                      </button>
                    ))}
                  </div>
                </div>
              </div>
              {window.ConsentBox && (
                <window.ConsentBox
                  smsChecked={!!form.smsConsent}
                  emailChecked={!!form.emailConsent}
                  onSmsChange={v => setForm({...form, smsConsent: v})}
                  onEmailChange={v => setForm({...form, emailConsent: v})}
                />
              )}

              <button className={`qq-submit ${valid ? 'on' : ''}`} onClick={submit} disabled={!valid}>
                <span>SEND IT →</span>
                <span className="qq-submit-tiny">A plumber will call you back</span>
              </button>
              <div className="qq-trust">
                <span>🔒 We don't sell or share info</span>
                <span>•</span>
                <span>Reply STOP to opt out anytime</span>
              </div>
            </div>
          </>
        )}

        {step === 'success' && (
          <div className="qq-success">
            <button className="qq-x qq-x-light" onClick={onClose}>×</button>
            <div className="qq-success-check">
              <svg viewBox="0 0 80 80" width="80" height="80">
                <circle cx="40" cy="40" r="36" fill="none" stroke="#34A853" strokeWidth="4" className="qq-check-ring"/>
                <path d="M24 42 L36 54 L58 30" fill="none" stroke="#34A853" strokeWidth="6" strokeLinecap="round" strokeLinejoin="round" className="qq-check-tick"/>
              </svg>
            </div>
            <div className="qq-success-eyebrow">REQUEST RECEIVED</div>
            <h3 className="qq-success-h">{form.name.split(' ')[0] || 'Friend'}, we've got your request.</h3>
            <div className="qq-success-receipt">
              <div className="qq-success-row"><span>SERVICE</span><span className="v">{form.service}</span></div>
              <div className="qq-success-row"><span>URGENCY</span><span className="v accent">{form.urgency || 'STANDARD'}</span></div>
              <div className="qq-success-row"><span>CALLBACK</span><span className="v ok">A REAL PLUMBER</span></div>
              <div className="qq-success-row"><span>STATUS</span><span className="v">RECEIVED ✓</span></div>
            </div>
            <p className="qq-success-p">A real Clog Busterz plumber is reviewing this and will call <strong>{form.phone}</strong> back. If you can't wait, hit the line:</p>
            <a href="tel:8594083382" className="qq-success-call">📞 859-408-3382</a>
          </div>
        )}
      </div>
    </div>
  );
}
window.QuickQuote = QuickQuote;

// ============== FLUSH LOTTERY — $5 / $15 / $25 / $30 GRAND TURD ==============
const LOTTERY_PRIZES = [
  { id: 'p5',  label: '$5 OFF',  d: 'Any service — no minimum',  code: 'FLUSH5',  weight: 45, color: '#9fd4ff' },
  { id: 'p15', label: '$15 OFF', d: 'Any service over $100',     code: 'FLUSH15', weight: 30, color: '#4ab3ff' },
  { id: 'p35', label: '$25 OFF', d: 'Any service over $150',     code: 'FLUSH25', weight: 15, color: '#ffd23d' },
  { id: 'p50', label: '$30 OFF', d: 'THE GRAND TURD · any service over $250', code: 'GRANDTURD30', weight: 10, color: '#c77dff' },
];
// Seven turds float in the bowl — each color is a different payout.
// Brown $5s, blue $15s, golden $25, and ONE purple-crowned GRAND TURD worth $30.
const CHIPS = [
  { cid: 'c1', prize: 'p5' },
  { cid: 'c2', prize: 'p15' },
  { cid: 'c3', prize: 'p5' },
  { cid: 'c4', prize: 'p35' },
  { cid: 'c5', prize: 'p5' },
  { cid: 'c6', prize: 'p15' },
  { cid: 'c7', prize: 'p50' },
];

function PipeLottery() {
  const [phase, setPhase] = useStateG('idle'); // idle | spinning | won
  const [prize, setPrize] = useStateG(null);
  const [played, setPlayed] = useStateG(false);
  const [flushed, setFlushed] = useStateG([]);
  const [keepCid, setKeepCid] = useStateG(null);

  useEffectG(() => {
    if (localStorage.getItem('cb-lottery-played') === '1') setPlayed(true);
  }, []);

  // 🚽 GIANT TOILET — all 6 coupons float in the bowl; the flush washes the losers away
  const CHIP_POS = [
    { left: '12%', top: '22%' },
    { left: '52%', top: '14%' },
    { left: '30%', top: '42%' },
    { left: '72%', top: '30%' },
    { left: '8%',  top: '56%' },
    { left: '42%', top: '62%' },
    { left: '64%', top: '54%' },
  ];

  const pickWeighted = () => {
    const total = LOTTERY_PRIZES.reduce((a, p) => a + p.weight, 0);
    let r = Math.random() * total;
    for (const p of LOTTERY_PRIZES) {
      r -= p.weight;
      if (r <= 0) return p;
    }
    return LOTTERY_PRIZES[0];
  };

  const spin = () => {
    if (phase !== 'idle' || played) return;
    window.dispatchEvent(new CustomEvent('cb-quest-step', { detail: { id: 'coupon' } }));
    setPhase('spinning');
    const won = pickWeighted();
    // one chip carrying the winning value survives — the other five get flushed
    const survivors = CHIPS.filter(c => c.prize === won.id);
    const keep = survivors[Math.floor(Math.random() * survivors.length)];
    setKeepCid(keep.cid);
    const losers = CHIPS.filter(c => c.cid !== keep.cid).map(c => c.cid)
      .sort(() => Math.random() - 0.5);
    losers.forEach((cid, i) => {
      setTimeout(() => setFlushed(f => [...f, cid]), 700 + i * 550);
    });
    setTimeout(() => {
      setPrize(won);
      setPhase('won');
      localStorage.setItem('cb-lottery-played', '1');
      setPlayed(true);
    }, 700 + losers.length * 550 + 900);
  };

  const reset = () => {
    localStorage.removeItem('cb-lottery-played');
    setPlayed(false);
    setPhase('idle');
    setPrize(null);
    setFlushed([]);
    setKeepCid(null);
  };
  const debugReplay = new URLSearchParams(window.location.search).has('lotteryDebug');

  return (
    <section className="lot" id="lottery">
      <div className="lot-bg-dots" />
      <div className="container">
        <div className="lot-card">
          <div className="lot-bulbs">
            {Array.from({length: 16}).map((_, i) => <span key={i} className="lot-bulb" style={{animationDelay: (i*0.08) + 's'}} />)}
          </div>
          <div className="lot-head">
            <div className="lot-eyebrow">⚡ ONE SPIN PER VISITOR · NO PURCHASE NECESSARY</div>
            <h2 className="lot-h">PIPE<br/><span className="lot-h-stroke">LOTTERY.</span></h2>
            <p className="lot-sub">Seven turds in the bowl, every color a different payout — from $5 to a golden $25, and <em>one purple-crowned GRAND TURD worth $30</em>. Pull the handle: six get flushed, whatever stays is yours. Cannot be combined with any other offers.</p>
          </div>

          <div className="lot-machine">
            <div className="gt-scene">
              <div className="gt-toilet">
                <div className="gt-tank">
                  <div className="gt-tank-lid"></div>
                  <div className="gt-tank-label">CLOG BUSTERZ · FLUSH-O-MATIC 3000</div>
                  <button
                    className={`gt-handle ${phase !== 'idle' || played ? 'disabled' : ''} ${phase === 'spinning' ? 'pulled' : ''}`}
                    onClick={spin}
                    disabled={phase !== 'idle' || played}
                    aria-label="Flush"
                  >
                    <span className="gt-handle-bar"></span>
                    <span className="gt-handle-l">FLUSH</span>
                  </button>
                </div>
                <div className={`gt-bowl ${phase === 'spinning' ? 'flushing' : ''}`}>
                  <div className="gt-water">
                    <div className="gt-swirl"></div>
                    <span className="gt-poop gp1" aria-hidden="true">💩</span>
                    <span className="gt-poop gp2" aria-hidden="true">💩</span>
                    <span className="gt-poop gp3" aria-hidden="true">💩</span>
                    {CHIPS.map((c, i) => {
                      const p = LOTTERY_PRIZES.find(x => x.id === c.prize);
                      return (
                        <span
                          key={c.cid}
                          className={`gt-turd t-${p.id} ${flushed.includes(c.cid) ? 'gone' : ''} ${phase === 'won' && keepCid === c.cid ? 'stay' : ''}`}
                          style={{ left: CHIP_POS[i].left, top: CHIP_POS[i].top }}
                        >
                          <span className="gt-turd-emoji" aria-hidden="true">💩</span>
                          <span className="gt-turd-amt" style={{ background: p.color }}>{p.label.replace(' OFF','')}</span>
                        </span>
                      );
                    })}
                    <div className="gt-drain"></div>
                  </div>
                </div>
                <div className="gt-pedestal"></div>
                <div className="gt-base"></div>
              </div>
            </div>
            <div className="lot-readout">
              {phase === 'idle' && !played && <span>TANK FULL · PULL THE HANDLE ↑</span>}
              {phase === 'idle' && played && <span className="lot-played">YOU ALREADY FLUSHED · WE GOT YOU</span>}
              {phase === 'spinning' && <span className="lot-spinning">FLUSHING THE LOSERS… 🌀</span>}
              {phase === 'won' && prize && (
                <span className="lot-won">
                  {prize.id === 'p50'
                    ? '👑💩 THE GRAND TURD SURVIVED · $30 OFF IS YOURS'
                    : `💩 ${prize.label} STAYED IN THE BOWL · IT'S YOURS`}
                </span>
              )}
            </div>
            {phase === 'won' && (
              <div className="gt-confetti" aria-hidden="true">
                {[...Array(12)].map((_, i) => (
                  <span key={i} style={{ left: (4 + i * 8) + '%', animationDelay: (i % 5) * 0.18 + 's' }}>💩</span>
                ))}
              </div>
            )}
          </div>

          {phase === 'won' && prize && (
            <div className="lot-prize">
              <div className="lot-prize-tape">★ ★ ★  WINNER  ★ ★ ★</div>
              <div className="lot-prize-card" style={{borderColor: prize.color}}>
                <div className="lot-prize-l">CLOG BUSTERZ COUPON · LIC #M7707</div>
                <div className="lot-prize-big" style={{color: prize.color}}>{prize.label}</div>
                <div className="lot-prize-d">{prize.d}</div>
                <div className="lot-prize-code">
                  <span>CODE</span>
                  <strong>{prize.code}</strong>
                  <button className="lot-copy" onClick={() => { navigator.clipboard?.writeText(prize.code); }}>COPY</button>
                </div>
                <div className="lot-prize-foot">Mention code at booking. Cannot be combined with any other offers. Expires in 30 days. One per household.</div>
              </div>
              <div className="lot-actions">
                <a href="tel:8594083382" className="lot-action lot-action-primary">CALL TO REDEEM →</a>
                <button className="lot-action lot-action-ghost" onClick={() => window.dispatchEvent(new CustomEvent('cb-open-quote'))}>BOOK ONLINE</button>
              </div>
            </div>
          )}
          {played && phase === 'idle' && debugReplay && (
            <div className="lot-replay">
              <button onClick={reset} className="lot-replay-btn">↻ Reset (testing only)</button>
            </div>
          )}

          <div className="lot-odds">
            <div className="lot-odds-h">WHAT YOU CAN WIN</div>
            <div className="lot-odds-grid">
              {LOTTERY_PRIZES.map(p => (
                <div key={p.id} className="lot-odds-row">
                  <span className="lot-odds-dot" style={{background: p.color}} />
                  <span className="lot-odds-l">{p.label}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
window.PipeLottery = PipeLottery;

// ============== STICKY "GET QUOTE" PILL ==============
function QuotePill({ onClick }) {
  const [shown, setShown] = useStateG(false);
  useEffectG(() => {
    const onScroll = () => setShown(window.scrollY > 600);
    window.addEventListener('scroll', onScroll);
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  if (!shown) return null;
  return (
    <button className="quote-pill" onClick={onClick}>
      <span className="quote-pill-bolt">⚡</span>
      <span className="quote-pill-text">QUOTE IN 60 SEC</span>
    </button>
  );
}
window.QuotePill = QuotePill;
