/* funnel.jsx — qualification quiz + routing + booking / disqualified screens */

const REVENUE_OPTS = [
  { id: '0-5',  label: '$0 – $5k',   note: 'per month' },
  { id: '5-10', label: '$5k – $10k', note: 'per month' },
  { id: '10-15',label: '$10k – $15k',note: 'per month' },
  { id: '15+',  label: '$15k+',      note: 'per month' },
];

function isQualified(google, revenue) {
  return google === 'yes' && revenue !== '0-5';
}

/* progress bar */
function Progress({ step, total, accent }) {
  return (
    <div style={{ display: 'flex', gap: 6, marginBottom: 30 }}>
      {Array.from({ length: total }).map((_, i) => (
        <div key={i} style={{ flex: 1, height: 4, borderRadius: 4, background: i <= step ? accent : 'var(--line)', transition: 'background .3s' }} />
      ))}
    </div>
  );
}

/* a big selectable option button */
function OptionBtn({ active, accent, onClick, children, sub }) {
  const [h, setH] = useState(false);
  return (
    <button onClick={onClick} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{
        width: '100%', textAlign: 'left', cursor: 'pointer',
        padding: '20px 22px', borderRadius: 10, marginBottom: 12,
        background: active ? 'var(--blue-soft)' : (h ? 'var(--bg-2)' : '#fff'),
        border: `1.5px solid ${active ? accent : (h ? 'var(--blue)' : 'var(--line)')}`,
        color: 'var(--ink)', transition: 'all .15s', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 14,
        boxShadow: active ? 'none' : '0 2px 8px -6px rgba(20,52,127,.5)',
      }}>
      <span>
        <span style={{ fontSize: 18, fontWeight: 800 }}>{children}</span>
        {sub && <span style={{ display: 'block', fontSize: 13, color: 'var(--ink-3)', fontWeight: 600, marginTop: 2 }}>{sub}</span>}
      </span>
      <span style={{ width: 22, height: 22, borderRadius: 22, flexShrink: 0, border: `2px solid ${active ? accent : 'var(--line)'}`, background: active ? accent : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {active && <svg width="11" height="9" viewBox="0 0 11 9" fill="none"><path d="M1 4.5 4 7.5 10 1.5" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>}
      </span>
    </button>
  );
}

/* ====================== FUNNEL ====================== */
function Funnel({ accent, brand, bookingId, onClose, onQualified, videoId }) {
  const [step, setStep] = useState(0); // 0 q1, 1 q2, 2 contact, 3 result
  const [google, setGoogle] = useState(null);
  const [revenue, setRevenue] = useState(null);
  const [form, setForm] = useState({ name: '', phone: '' });
  const [errors, setErrors] = useState({});
  const [outcome, setOutcome] = useState(null); // 'qualified' | 'disqualified'
  const [reason, setReason] = useState(null);

  useEffect(() => { window.LPTrack.logLocal('quiz_start'); }, []);
  useEffect(() => { window.scrollTo(0, 0); }, [step]);

  function pickGoogle(v) {
    setGoogle(v); window.LPTrack.logLocal('quiz_q1', { google: v });
    setTimeout(() => setStep(1), 180);
  }
  function pickRevenue(v) {
    setRevenue(v); window.LPTrack.logLocal('quiz_q2', { revenue: v });
    setTimeout(() => setStep(2), 180);
  }

  function validate() {
    const e = {};
    if (!form.name.trim()) e.name = 1;
    if (form.phone.replace(/\D/g, '').length < 10) e.phone = 1;
    setErrors(e); return Object.keys(e).length === 0;
  }

  async function submitContact() {
    if (!validate()) return;
    const qualified = isQualified(google, revenue);
    const why = google !== 'yes' ? 'no_google_profile' : (revenue === '0-5' ? 'revenue_below_5k' : null);

    const firstName = form.name.trim().split(/\s+/)[0] || '';
    const lastName = form.name.trim().split(/\s+/).slice(1).join(' ');
    const lead = {
      firstName, lastName, name: form.name.trim(),
      phone: form.phone, google, revenue,
      status: qualified ? 'qualified' : 'disqualified', reason: why,
    };
    window.LPTrack.saveLead(lead);
    window.LPTrack.logLocal('optin', { google, revenue, qualified });

    const ud = { phone: form.phone, firstName: form.name.trim().split(/\s+/)[0], lastName: form.name.trim().split(/\s+/).slice(1).join(' ') };

    if (qualified) {
      window.LPTrack.logLocal('qualified');
      window.LPTrack.logLocal('booking_shown');
      // standard Lead event — the conversion we want Meta to optimize toward (fire-and-forget)
      window.LPTrack.track('Lead', {
        content_name: 'Qualified Audit Request', content_category: 'auto_repair',
        currency: 'USD', value: 50, revenue_band: revenue,
      }, ud);
      window.LPTrack.LS.set('lp_current', { name: form.name.trim(), firstName, phone: form.phone, reason: null, videoId: videoId || '', bookingId });
      window.location.href = 'booking.html';
    } else {
      window.LPTrack.logLocal('disqualified', { reason: why });
      // custom event so it stays OUT of the optimization signal — these are nurture leads
      window.LPTrack.track('UnqualifiedLead', {
        content_name: 'Unqualified Lead', reason: why, revenue_band: revenue, has_google: google,
      }, ud);
      window.LPTrack.LS.set('lp_current', { name: form.name.trim(), firstName, phone: form.phone, reason: why });
      window.location.href = 'nurture.html';
    }
  }

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 100, background: 'rgba(8,18,33,.55)', backdropFilter: 'blur(3px)', display: 'flex', justifyContent: 'center', padding: 'clamp(10px,4vh,56px) 14px', overflowY: 'auto' }}>
      <div onClick={e => e.stopPropagation()} style={{ position: 'relative', width: '100%', maxWidth: 540, margin: 'auto', background: '#fff', borderRadius: 18, boxShadow: '0 40px 100px -30px rgba(8,18,33,.65)', padding: '40px 26px 34px' }}>
        <button onClick={onClose} aria-label="Close" style={{ position: 'absolute', top: 12, right: 14, background: 'none', border: 'none', color: 'var(--ink-3)', cursor: 'pointer', fontSize: 28, lineHeight: 1, padding: 6, zIndex: 3 }}>×</button>
        {step < 3 && <Progress step={step} total={3} accent={accent} />}

        {step === 0 && (
          <div>
            <h2 className="display" style={{ fontSize: 'clamp(26px,5vw,38px)' }}>Do you own a <span style={{ color: accent }}>verified</span> Google Business Profile?</h2>
            <p style={{ color: 'var(--ink-3)', marginTop: 12, marginBottom: 28, fontSize: 15 }}>A claimed, verified listing for your shop on Google Maps / Search.</p>
            <OptionBtn active={google === 'yes'} accent={accent} onClick={() => pickGoogle('yes')} sub="Claimed &amp; verified — I manage it">Yes, I have one</OptionBtn>
            <OptionBtn active={google === 'no'} accent={accent} onClick={() => pickGoogle('no')} sub="Not yet, or I’m not sure">No / Not verified</OptionBtn>
          </div>
        )}

        {step === 1 && (
          <div>
            <button onClick={() => setStep(0)} style={backBtn}>← Back</button>
            <h2 className="display" style={{ fontSize: 'clamp(26px,5vw,38px)' }}>What’s your current <span style={{ color: accent }}>monthly revenue?</span></h2>
            <p style={{ color: 'var(--ink-3)', marginTop: 12, marginBottom: 28, fontSize: 15 }}>This helps us tailor the right growth plan for your shop.</p>
            {REVENUE_OPTS.map(o => (
              <OptionBtn key={o.id} active={revenue === o.id} accent={accent} onClick={() => pickRevenue(o.id)} sub={o.note}>{o.label}</OptionBtn>
            ))}
          </div>
        )}

        {step === 2 && (
          <div>
            <button onClick={() => setStep(1)} style={backBtn}>← Back</button>
            <h2 className="display" style={{ fontSize: 'clamp(26px,5vw,38px)' }}>One last step — <span style={{ color: accent }}>where do we send the details?</span></h2>
            <p style={{ color: 'var(--ink-3)', marginTop: 12, marginBottom: 28, fontSize: 15 }}>Quick &amp; secure — we’ll text you to confirm your spot.</p>
            <Field label="Full name" v={form.name} err={errors.name} onChange={v => setForm({ ...form, name: v })} />
            <Field label="Mobile number" type="tel" v={form.phone} err={errors.phone} onChange={v => setForm({ ...form, phone: v })} />
            <button className="btn btn-primary btn-lg" style={{ width: '100%', marginTop: 18 }} onClick={submitContact}>
              Continue →
            </button>
            <p style={{ textAlign: 'center', fontSize: 12, color: 'var(--ink-4)', marginTop: 14 }}>🔒 Your information is secure and never shared.</p>
          </div>
        )}

        {step === 3 && outcome === 'qualified' && (
          <Qualified accent={accent} bookingId={bookingId} form={form} videoId={videoId} />
        )}
        {step === 3 && outcome === 'disqualified' && (
          <Disqualified accent={accent} reason={reason} form={form} />
        )}
      </div>
    </div>
  );
}

const backBtn = { background: 'none', border: 'none', color: 'var(--ink-3)', cursor: 'pointer', fontSize: 14, fontWeight: 700, marginBottom: 18, padding: 0 };

function Field({ label, v, onChange, err, type = 'text', optional }) {
  return (
    <label style={{ display: 'block', marginBottom: 12 }}>
      <span style={{ display: 'block', fontSize: 12.5, fontWeight: 700, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 7 }}>
        {label}{optional && <span style={{ color: 'var(--ink-4)', fontWeight: 600 }}> (optional)</span>}
      </span>
      <input type={type} value={v} onChange={e => onChange(e.target.value)}
        style={{
          width: '100%', padding: '14px 16px', borderRadius: 9, fontSize: 16, fontFamily: 'var(--body)',
          background: '#fff', color: 'var(--ink)', border: `1.5px solid ${err ? '#D63636' : 'var(--line)'}`, outline: 'none',
        }}
        onFocus={e => e.target.style.borderColor = 'var(--blue)'}
        onBlur={e => e.target.style.borderColor = err ? '#D63636' : 'var(--line)'} />
      {err && <span style={{ fontSize: 12, color: '#D63636', marginTop: 5, display: 'block' }}>Please enter a valid {label.toLowerCase()}.</span>}
    </label>
  );
}

/* ---- QUALIFIED → booking ---- */
function Qualified({ accent, bookingId, form, videoId }) {
  const wrapRef = useRef(null);
  const fired = useRef(false);

  useEffect(() => {
    // load LeadConnector embed resizer
    if (!document.querySelector('script[data-msgsndr]')) {
      const s = document.createElement('script');
      s.src = 'https://link.msgsndr.com/js/form_embed.js';
      s.async = true; s.setAttribute('data-msgsndr', '1');
      document.body.appendChild(s);
    }
    // listen for booking-complete messages from the widget
    function onMsg(ev) {
      const d = ev.data;
      const str = typeof d === 'string' ? d : JSON.stringify(d || '');
      if (/book|appointment|schedul|slot.*confirm|booked/i.test(str) && !fired.current) {
        confirmBooking();
      }
    }
    window.addEventListener('message', onMsg);
    return () => window.removeEventListener('message', onMsg);
  }, []);

  async function confirmBooking() {
    if (fired.current) return; fired.current = true;
    window.LPTrack.saveLead({ status: 'booked' });
    window.LPTrack.logLocal('booking_complete');
    await window.LPTrack.track('Schedule', {
      content_name: 'Strategy Call Booked', currency: 'USD', value: 250,
    }, { phone: form.phone, firstName: (form.name || '').trim().split(/\s+/)[0] });
  }

  return (
    <div ref={wrapRef}>
      <div style={{ textAlign: 'center', marginBottom: 18 }}>
        <div style={{ width: 56, height: 56, borderRadius: 100, background: 'rgba(31,191,107,.14)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14 }}>
          <svg width="28" height="22" viewBox="0 0 30 24" fill="none"><path d="M2 13 11 21 28 3" stroke="#1FBF6B" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </div>
        <h2 className="display" style={{ fontSize: 'clamp(24px,5vw,36px)' }}>You’re a <span style={{ color: accent }}>perfect fit</span>, {(form.name || '').trim().split(/\s+/)[0] || 'there'}.</h2>
        <p style={{ color: 'var(--ink-2)', marginTop: 10, fontSize: 16 }}>
          Two quick steps and you’re booked 👇
        </p>
      </div>

      {/* STEP 1 — watch the video */}
      {videoId ? (
        <div style={{ marginBottom: 26 }}>
          <div style={{ background: accent, color: '#fff', textAlign: 'center', padding: '12px 16px', borderRadius: '12px 12px 0 0', fontWeight: 800, fontSize: 'clamp(15px,3.4vw,19px)', letterSpacing: '.005em' }}>
            ⬇️&nbsp; Step 1: Watch this quick video &nbsp;⬇️
          </div>
          <div style={{ position: 'relative', aspectRatio: '16/9', background: '#0C1B30', border: '1px solid var(--line)', borderTop: 'none', borderRadius: '0 0 12px 12px', overflow: 'hidden' }}>
            <iframe
              src={`https://player.vimeo.com/video/${videoId}?autoplay=1&title=0&byline=0&portrait=0&dnt=1`}
              style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', border: 0 }}
              allow="autoplay; fullscreen; picture-in-picture" allowFullScreen title="Watch"></iframe>
          </div>
        </div>
      ) : null}

      {/* STEP 2 — book a call */}
      <div style={{ textAlign: 'center', marginBottom: 14 }}>
        <span style={{ fontSize: 'clamp(17px,3.6vw,21px)', fontWeight: 800, color: 'var(--ink)' }}>
          👇 <span style={{ textDecoration: 'underline', textUnderlineOffset: 3, textDecorationColor: accent, textDecorationThickness: 3 }}>Step 2:</span> Book your free call below 👇
        </span>
      </div>
      <div style={{ border: '1px solid var(--line)', borderRadius: 14, overflow: 'hidden', background: '#fff', minHeight: 780 }}>
        <iframe
          src={`https://api.leadconnectorhq.com/widget/booking/${bookingId}`}
          style={{ display: 'block', width: '100%', height: 760, minHeight: 760, border: 'none' }}
          scrolling="no" id={`${bookingId}_embed`} title="Book your call"></iframe>
      </div>
      <div style={{ marginTop: 26 }}>
        <div style={{ textAlign: 'center', fontWeight: 800, fontSize: 17, color: 'var(--ink)', marginBottom: 14 }}>
          Real results from real shop owners 👇
        </div>
        <div style={{ display: 'flex', gap: 12, overflowX: 'auto', paddingBottom: 6, scrollSnapType: 'x mandatory' }}>
          {['1194472718', '1071544418', '1070893175'].map(id => (
            <div key={id} style={{ flex: '0 0 188px', aspectRatio: '9/16', borderRadius: 14, overflow: 'hidden', background: '#0C1B30', border: '1px solid var(--line)', scrollSnapAlign: 'center' }}>
              <iframe src={`https://player.vimeo.com/video/${id}?title=0&byline=0&portrait=0&dnt=1`}
                style={{ width: '100%', height: '100%', border: 0 }}
                allow="fullscreen; picture-in-picture" allowFullScreen title="Testimonial"></iframe>
            </div>
          ))}
        </div>
      </div>
      <button onClick={confirmBooking} className="btn btn-ghost" style={{ width: '100%', marginTop: 18, fontSize: 14 }}>
        I’ve booked my call ✓
      </button>
    </div>
  );
}

/* ---- DISQUALIFIED → we'll reach out ---- */
function Disqualified({ accent, reason, form }) {
  const firstName = (form.name || '').trim().split(/\s+/)[0] || 'so much';
  const copy = reason === 'no_google_profile'
    ? {
        h: 'Let’s get your Google profile live first.',
        p: `Thanks ${firstName} — before we can drive calls, your shop needs a verified Google Business Profile. Good news: that’s step one of what we do, and our team will personally reach out to help you get it set up the right way.`,
      }
    : {
        h: 'We’d love to help you grow into this.',
        p: `Thanks ${firstName} — based on where your shop is right now, our paid program isn’t the right fit just yet. But we don’t want to leave you hanging. Our team will reach out with a free game plan and resources to help you build momentum.`,
      };
  return (
    <div style={{ textAlign: 'center', paddingTop: 10 }}>
      <div style={{ width: 64, height: 64, borderRadius: 100, background: 'var(--blue-soft)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 20 }}>
        <svg width="30" height="30" viewBox="0 0 24 24" fill="none"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.8 19.8 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.9.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92Z" stroke={accent} strokeWidth="2" strokeLinejoin="round"/></svg>
      </div>
      <h2 className="display" style={{ fontSize: 'clamp(24px,4.6vw,36px)', maxWidth: 460, margin: '0 auto' }}>{copy.h}</h2>
      <p style={{ color: 'var(--ink-2)', marginTop: 16, fontSize: 17, maxWidth: 480, margin: '16px auto 0', textWrap: 'pretty' }}>{copy.p}</p>
      <div style={{ marginTop: 30, padding: 22, border: '1px solid var(--line)', borderRadius: 12, background: 'var(--bg-2)', maxWidth: 440, marginInline: 'auto' }}>
        <div style={{ fontSize: 13, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--ink-3)' }}>What happens next</div>
        <p style={{ fontSize: 15, color: 'var(--ink-2)', marginTop: 10 }}>
          We’ve got your details. A member of our team will reach out to <strong style={{ color: 'var(--ink)' }}>{form.phone}</strong> within 1 business day.
        </p>
      </div>
      <p style={{ marginTop: 26, fontSize: 13, color: 'var(--ink-4)' }}>You can close this window — we’ll be in touch.</p>
    </div>
  );
}

Object.assign(window, { Funnel, isQualified });
