/* global window, React */
// Feedback form + Waitlist screens

const { useState, useEffect, useRef, useMemo } = React;
const { Ticker, FloatingSticker } = window.KechHero;
const { CardArt } = window.KechSwipe;

// ---------- Mini sticker pile of liked designs --------------------
function LikedPile({ liked }) {
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'center', gap: 8 }}>
      {liked.map((d, i) => {
        return (
          <div
            key={d.id}
            title={d.caption || d.name}
            style={{
              width: 64, height: 64, borderRadius: 10,
              border: '3px solid var(--kech-black)',
              background: 'var(--kech-white)',
              transform: `rotate(${(i % 2 ? 1 : -1) * (2 + i % 4)}deg)`,
              boxShadow: '3px 3px 0 var(--kech-fuchsia)',
              overflow: 'hidden',
              position: 'relative',
              display: 'grid',
              placeItems: 'center'
            }}>
            
            {d.img ?
            <img
              src={d.img}
              alt={d.caption || d.name}
              draggable={false}
              style={{
                width: '94%',
                height: '94%',
                objectFit: 'contain',
                mixBlendMode: 'multiply',
                filter: 'drop-shadow(0 2px 0 rgba(0,0,0,0.18))'
              }} /> :


            <div style={{ fontFamily: 'Kechfont, system-ui', fontWeight: 800, fontSize: 18, color: 'var(--kech-black)' }}>
                {String(d.no || i + 1).padStart(2, '0')}
              </div>
            }
          </div>);

      })}
    </div>);

}

// ---------- Form section card --------------------------------------
function FormCard({ children, color = 'aqua', tilt = 0 }) {
  const shadowColor = color === 'fuchsia' ? 'var(--kech-fuchsia)' : color === 'aqua' ? 'var(--kech-aqua)' : 'var(--kech-black)';
  return (
    <div style={{
      background: 'var(--kech-white)',
      border: '3px solid var(--kech-black)',
      borderRadius: 18,
      padding: '24px 24px',
      boxShadow: `6px 6px 0 ${shadowColor}, 6px 6px 0 3px var(--kech-black)`,
      transform: `rotate(${tilt}deg)`,
      color: 'var(--kech-black)'
    }}>{children}</div>);

}

// ---------- Tag chip -----------------------------------------------
function Chip({ children, active, onClick }) {
  return (
    <button
      onClick={onClick}
      style={{
        background: active ? 'var(--kech-fuchsia)' : 'var(--kech-white)',
        color: 'var(--kech-black)',
        border: '3px solid var(--kech-black)',
        borderRadius: 999,
        padding: '8px 14px 10px',
        fontFamily: 'var(--font-body)', fontWeight: 700,
        textTransform: 'none', fontSize: 15, lineHeight: 1.1,
        cursor: 'pointer',
        boxShadow: active ? '3px 3px 0 var(--kech-aqua), 3px 3px 0 3px var(--kech-black)' : '3px 3px 0 var(--kech-black)',
        transition: 'all 160ms var(--ease-pop)'
      }}
      onMouseEnter={(e) => {e.currentTarget.style.transform = 'translate(-1px,-1px)';}}
      onMouseLeave={(e) => {e.currentTarget.style.transform = 'translate(0,0)';}}>
      {active ? '✓ ' : ''}{children}</button>);

}

const TAG_OPTIONS = [
'grappig', 'herkenbaar', 'leuk als cadeau', 'uniek', 'lekker brutaal',
'ironisch', 'meme-waardig', 'lekker op het randje'];

const NOPE_TAG_OPTIONS = [
'niet grappig', 'te basic', 'lelijk', 'kinderachtig', 'cringe',
'ik snap het niet', 'overdreven', 'ongepast', 'dit is echt niet iets voor mij'];

const AGE_OPTIONS = ['<18', '18-24', '25-34', '35-44', '45-54', '55+', 'zeg ik liever niet'];
const GENDER_OPTIONS = ['vrouw', 'man', 'non-binair', 'zeg ik liever niet'];


// ---------- Social icon button ------------------------------------
function SocialIcon({ href, label, children }) {
  return (
    <a
      href={href}
      target="_blank"
      rel="noopener noreferrer"
      aria-label={label}
      style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        width: 44, height: 44,
        background: 'var(--kech-white)',
        color: 'var(--kech-black)',
        border: '2.5px solid var(--kech-black)',
        borderRadius: 999,
        boxShadow: '3px 3px 0 var(--kech-black)',
        transition: 'transform 140ms var(--ease-pop), box-shadow 140ms',
        textDecoration: 'none'
      }}
      onMouseEnter={(e) => {e.currentTarget.style.transform = 'translate(-2px,-2px)';e.currentTarget.style.boxShadow = '5px 5px 0 var(--kech-black)';}}
      onMouseLeave={(e) => {e.currentTarget.style.transform = 'translate(0,0)';e.currentTarget.style.boxShadow = '3px 3px 0 var(--kech-black)';}}>
      {children}
    </a>);

}

// ---------- Slider with end-labels --------------------------------
function KechSlider({ value, onChange, min = 1, max = 10, step = 1, leftLabel, rightLabel, formatValue }) {
  const display = formatValue ? formatValue(value) : `${value} / ${max}`;
  return (
    <div>
      <input
        type="range"
        className="kech-range"
        min={min} max={max} step={step} value={value}
        onChange={(e) => onChange(parseInt(e.target.value))}
        style={{ width: '100%' }} />
      
      <div style={{
        display: 'flex', justifyContent: 'space-between', marginTop: 10,
        fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 700,
        letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--kech-black)', opacity: 0.6
      }}>
        <span>{leftLabel}</span>
        <span style={{
          background: 'var(--kech-fuchsia)', color: 'var(--kech-black)',
          padding: '3px 10px', borderRadius: 999, border: '2px solid var(--kech-black)',
          fontFamily: 'Kechfont, system-ui', fontWeight: 800, fontSize: 14, letterSpacing: 0,
          textTransform: 'lowercase', lineHeight: 1
        }}>{display}</span>
        <span>{rightLabel}</span>
      </div>
    </div>);

}

// ===================================================================
// FEEDBACK FORM
// ===================================================================
function FeedbackForm({ liked, disliked = [], onSubmit }) {
  const [step, setStep] = useState(1);
  const [tags, setTags] = useState([]);
  const [openText, setOpenText] = useState('');
  const [nopeTags, setNopeTags] = useState([]);
  const [nopeText, setNopeText] = useState('');
  const [purchaseIntent, setPurchaseIntent] = useState(5);
  const [selfVsGift, setSelfVsGift] = useState(5);
  const [where, setWhere] = useState([]);
  const [price, setPrice] = useState(15);
  const [age, setAge] = useState('');
  const [gender, setGender] = useState('');
  const [otherText, setOtherText] = useState('');

  const toggle = (set, get) => (v) => set(get.includes(v) ? get.filter((x) => x !== v) : [...get, v]);

  // Scroll to top on step change (mobile-friendly: long forms otherwise leave user
  // at bottom of previous step, missing the next step's header)
  useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'instant' });
  }, [step]);

  const hasNope = disliked && disliked.length > 0;
  const persistStep = (s) => {
    if (!window.KechDB) return;
    if (s === 1) {
      window.KechDB.recordFeedback('1', { liked_tags: tags, liked_text: openText });
    } else if (s === 1.5) {
      window.KechDB.recordFeedback('1.5', { nope_tags: nopeTags, nope_text: nopeText });
    } else if (s === 2) {
      window.KechDB.recordFeedback('2', {
        sliders: { purchaseIntent, selfVsGift, where, price },
        demographics: { age, gender },
        liked_text: otherText
      });
    }
  };
  const next = () => {
    setStep((s) => {
      persistStep(s);
      if (s === 1) return hasNope ? 1.5 : 2;
      if (s === 1.5) return 2;
      return Math.min(s + 1, 3);
    });
  };
  const back = () => {
    setStep((s) => {
      if (s === 1.5) return 1;
      if (s === 2) return hasNope ? 1.5 : 1;
      return Math.max(s - 1, 1);
    });
  };

  const submit = () => {
    if (window.KechDB) {
      window.KechDB.recordFeedback('2', {
        sliders: { purchaseIntent, selfVsGift, where, price },
        demographics: { age, gender },
        liked_text: otherText
      });
    }
    onSubmit({
      tags, openText, nopeTags, nopeText,
      purchaseIntent, selfVsGift,
      where, price, age, gender, otherText
    });
  };

  return (
    <section className="page" style={{ position: 'relative', background: 'var(--kech-fuchsia)' }}>
      {/* Decorative dots bg */}
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: 'radial-gradient(circle at 0 0, rgba(25,20,20,0.18) 8px, transparent 9px)',
        backgroundSize: '60px 60px',
        opacity: 0.5, pointerEvents: 'none'
      }} />
      <FloatingSticker top="6%" left="4%" rot={-8} bg="var(--kech-aqua)" delay={0.2}>roast time</FloatingSticker>
      <FloatingSticker top="16%" right="6%" rot={5} bg="var(--kech-black)" color="var(--kech-aqua)" delay={0.5}>± 90 sec</FloatingSticker>

      <div style={{ position: 'relative', zIndex: 2, maxWidth: 720, margin: '0 auto', padding: '64px 24px 96px' }}>
        {/* Header */}
        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <h2 style={{
            fontFamily: 'Kechfont, system-ui', fontWeight: 800,
            fontSize: 'clamp(48px, 8vw, 96px)', lineHeight: 0.85, letterSpacing: '-0.02em',
            color: 'var(--kech-black)', textTransform: 'lowercase', margin: 0
          }}>baby tell me why?</h2>
          <p style={{ marginTop: 12, color: 'var(--kech-black)', fontWeight: 600, fontSize: 17, opacity: 0.85 }}>
            je swipede {liked.length} ja's. nu de eerlijke mening.
          </p>

          {/* Stepper removed per feedback */}
        </div>

        {/* Step 1: liked pile + reasons (combined) */}
        {step === 1 &&
        <FormCard color="aqua">
            <div style={{
            fontFamily: 'Kechfont, system-ui', fontWeight: 800, fontSize: 28,
            textTransform: 'lowercase', lineHeight: 0.9, marginBottom: 6
          }}>jouw shortlist</div>
            <p style={{ fontSize: 14, color: 'var(--kech-black)', opacity: 0.7, margin: '0 0 16px' }}>
              dit zijn de ballen die jij liked.
            </p>
            <LikedPile liked={liked} />

            <hr className="dotted-rule" style={{ margin: '24px 0' }} />

            <div style={{ fontFamily: 'Kechfont, system-ui', fontWeight: 800, fontSize: 30, textTransform: 'lowercase', lineHeight: 0.9, marginBottom: 6 }}>wat vond je er leuk aan</div>
            <p style={{ fontSize: 14, color: 'var(--kech-black)', opacity: 0.7, marginTop: 0, marginBottom: 20 }}>meerdere aanklikken mag</p>

            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 24 }}>
              {TAG_OPTIONS.map((t) =>
            <Chip key={t} active={tags.includes(t)} onClick={() => toggle(setTags, tags)(t)}>{t}</Chip>
            )}
            </div>

            <label style={{ display: 'block', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 18, textTransform: 'none', marginBottom: 8, lineHeight: 1.2 }}>
              of in eigen woorden:
            </label>
            <textarea
            className="kech-textarea"
            value={openText}
            onChange={(e) => setOpenText(e.target.value)}
            placeholder="deel je mening, wees ook lekker kritisch" />
          

            <div style={{ marginTop: 22, display: 'flex', justifyContent: 'flex-end', gap: 12, flexWrap: 'wrap' }}>
              <button className="kbtn" onClick={next}>door →</button>
            </div>
          </FormCard>
        }

        {/* Step 1.5: disliked pile + nope reasons */}
        {step === 1.5 &&
        <FormCard color="fuchsia">
            <div style={{
            fontFamily: 'Kechfont, system-ui', fontWeight: 800, fontSize: 28,
            textTransform: 'lowercase', lineHeight: 0.9, marginBottom: 6
          }}>de afgewezen</div>
            <p style={{ fontSize: 14, color: 'var(--kech-black)', opacity: 0.7, margin: '0 0 16px' }}>
              deze swipede je weg. wat klopte er niet?
            </p>
            <LikedPile liked={disliked} />

            <hr className="dotted-rule" style={{ margin: '24px 0' }} />

            <div style={{ fontFamily: 'Kechfont, system-ui', fontWeight: 800, fontSize: 30, textTransform: 'lowercase', lineHeight: 0.9, marginBottom: 6 }}>waarom vond je deze niks?</div>
            <p style={{ fontSize: 14, color: 'var(--kech-black)', opacity: 0.7, marginTop: 0, marginBottom: 20 }}>meerdere aanklikken mag</p>

            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 24 }}>
              {NOPE_TAG_OPTIONS.map((t) =>
            <Chip key={t} active={nopeTags.includes(t)} onClick={() => toggle(setNopeTags, nopeTags)(t)}>{t}</Chip>
            )}
            </div>

            <label style={{ display: 'block', fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 18, textTransform: 'none', marginBottom: 8, lineHeight: 1.2 }}>
              of in eigen woorden:
            </label>
            <textarea
            className="kech-textarea"
            value={nopeText}
            onChange={(e) => setNopeText(e.target.value)}
            placeholder="zeg het maar, kritisch mag juist!" />
          

            <div style={{ marginTop: 22, display: 'flex', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
              <button className="kbtn kbtn--ghost kbtn--small" onClick={back}>← terug</button>
              <button className="kbtn" onClick={next}>door →</button>
            </div>
          </FormCard>
        }

        {/* Step 2: Sliders */}
        {step === 2 &&
        <FormCard color="aqua">
            <div style={{ fontFamily: 'Kechfont, system-ui', fontWeight: 800, fontSize: 30, textTransform: 'lowercase', lineHeight: 0.9, marginBottom: 22 }}>gretigheidsmeter</div>

            <div style={{ marginBottom: 8 }}>
              <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 18, textTransform: 'none', marginBottom: 10, lineHeight: 1.2 }}>even serieus, hoe waarschijnlijk zou je deze echt kopen</div>
              <KechSlider
              value={purchaseIntent} onChange={setPurchaseIntent}
              leftLabel="echt niet" rightLabel="100% ja" />
            </div>

            <hr className="dotted-rule" />

            <div style={{ marginBottom: 8 }}>
              <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 18, textTransform: 'none', marginBottom: 10, lineHeight: 1.2 }}>voor jezelf of voor een ander als cadeau?</div>
              <KechSlider
              value={selfVsGift} onChange={setSelfVsGift}
              leftLabel="voor mezelf" rightLabel="voor een ander" />
            </div>

            <hr className="dotted-rule" />

            <div style={{ marginBottom: 8 }}>
              <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 18, textTransform: 'none', marginBottom: 6, lineHeight: 1.2 }}>wat voor prijs zou je per stuk verwachten?</div>
              <p style={{ margin: '0 0 14px', fontSize: 13, lineHeight: 1.35, color: 'var(--kech-black)', opacity: 0.65, fontWeight: 500 }}>grotere kerstballen van glas, handgeverfd, in cadeauverpakking verkocht, excl. verzendkosten</p>
              <KechSlider
              value={price} onChange={setPrice}
              min={0} max={30} step={1}
              leftLabel="€0" rightLabel="€30+"
              formatValue={(v) => v >= 30 ? '€30+' : `€${v}`} />
            </div>

            <hr className="dotted-rule" />

            <div style={{ marginBottom: 18 }}>
              <div style={{ fontFamily: 'Kechfont, system-ui', fontWeight: 800, fontSize: 28, textTransform: 'lowercase', lineHeight: 0.9, marginBottom: 6 }}>over jou</div>
              <p style={{ fontSize: 14, color: 'var(--kech-black)', opacity: 0.7, marginTop: 0, marginBottom: 14 }}>helpt mij om de juiste mensen te bereiken</p>

              <div style={{ marginBottom: 14 }}>
                <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 16, marginBottom: 8 }}>leeftijd</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {AGE_OPTIONS.map((o) =>
                <Chip key={o} active={age === o} onClick={() => setAge(age === o ? '' : o)}>{o}</Chip>
                )}
                </div>
              </div>

              <div>
                <div style={{ fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 16, marginBottom: 8 }}>geslacht</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {GENDER_OPTIONS.map((o) =>
                <Chip key={o} active={gender === o} onClick={() => setGender(gender === o ? '' : o)}>{o}</Chip>
                )}
                </div>
              </div>
            </div>

            <hr className="dotted-rule" />

            <div style={{ marginBottom: 8 }}>
              <div style={{ fontFamily: 'Kechfont, system-ui', fontWeight: 800, fontSize: 28, textTransform: 'lowercase', lineHeight: 0.9, marginBottom: 6 }}>nog iets?</div>
              <p style={{ fontSize: 14, color: 'var(--kech-black)', opacity: 0.7, marginTop: 0, marginBottom: 14 }}>ideeën, feedback, uitgebreide dankwoorden - alles kan</p>
              <textarea
              className="kech-textarea"
              value={otherText}
              onChange={(e) => setOtherText(e.target.value)}
              placeholder="hier mag je echt los."
              style={{ minHeight: 120 }} />
            </div>

            <div style={{ marginTop: 22, display: 'flex', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
              <button className="kbtn kbtn--ghost kbtn--small" onClick={back}>← terug</button>
              <button className="kbtn" onClick={submit} style={{ fontSize: 24 }}>klaar! Send it</button>
            </div>
          </FormCard>
        }

        {/* Step 3 was merged into step 2 */}
        {false &&
        <FormCard color="aqua">
            <div style={{ fontFamily: 'Kechfont, system-ui', fontWeight: 800, fontSize: 30, textTransform: 'lowercase', lineHeight: 0.9, marginBottom: 6 }}>
              alles eruit
            </div>
            <p style={{ fontSize: 14, color: 'var(--kech-black)', opacity: 0.7, marginTop: 0, marginBottom: 16 }}>
              wat we hebben gemist, ideeën, beter idee, een betere naam — alles welkom.
            </p>
            <textarea
            className="kech-textarea"
            value={otherText}
            onChange={(e) => setOtherText(e.target.value)}
            placeholder="hier mag je echt los."
            style={{ minHeight: 140 }} />
          
            <div style={{ marginTop: 22, display: 'flex', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
              <button className="kbtn kbtn--ghost kbtn--small" onClick={back}>← terug</button>
              <button className="kbtn" onClick={submit} style={{ fontSize: 24 }}>klaar — stuur in 🚀</button>
            </div>
          </FormCard>
        }
      </div>
    </section>);

}

// ===================================================================
// WAITLIST
// ===================================================================
const TURNSTILE_SITE_KEY = '0x4AAAAAADIXk7uu9-S-uxLd';

// Email-typo suggestion (Levenshtein-based) ----------------------------------
const COMMON_DOMAINS = [
  'gmail.com', 'googlemail.com',
  'hotmail.com', 'hotmail.nl', 'hotmail.be', 'hotmail.fr', 'hotmail.de',
  'outlook.com', 'outlook.nl', 'outlook.be',
  'live.nl', 'live.com', 'live.be',
  'yahoo.com', 'yahoo.nl',
  'icloud.com', 'me.com', 'mac.com',
  'protonmail.com', 'proton.me', 'pm.me',
  'kpnmail.nl', 'ziggo.nl', 'kpn.nl', 'planet.nl', 'home.nl', 'xs4all.nl', 'casema.nl', 'upcmail.nl',
  'student.uu.nl', 'student.uva.nl',
];
const COMMON_TLDS = ['com', 'net', 'org', 'nl', 'be', 'de', 'fr', 'uk', 'co', 'io', 'app', 'dev', 'me', 'info', 'eu', 'us', 'edu'];

function lev(a, b) {
  const m = a.length, n = b.length;
  if (Math.abs(m - n) > 2) return 99;
  const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
  for (let i = 0; i <= m; i++) dp[i][0] = i;
  for (let j = 0; j <= n; j++) dp[0][j] = j;
  for (let i = 1; i <= m; i++) {
    for (let j = 1; j <= n; j++) {
      dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
    }
  }
  return dp[m][n];
}

function suggestEmail(email) {
  if (!email || !email.includes('@')) return null;
  const [local, domain] = email.trim().toLowerCase().split('@');
  if (!local || !domain) return null;
  if (COMMON_DOMAINS.includes(domain)) return null;
  // Whole-domain typo (gmial.com → gmail.com, gmail.vom → gmail.com)
  let best = null, bestD = 99;
  for (const d of COMMON_DOMAINS) {
    const dist = lev(d, domain);
    if (dist < bestD && dist > 0 && dist <= 2) { bestD = dist; best = d; }
  }
  if (best) return `${local}@${best}`;
  // TLD-only typo (something.cmo → something.com)
  const dotIdx = domain.lastIndexOf('.');
  if (dotIdx < 0) return null;
  const tld = domain.slice(dotIdx + 1);
  const base = domain.slice(0, dotIdx);
  if (COMMON_TLDS.includes(tld)) return null;
  let bestT = null, bestTD = 99;
  for (const t of COMMON_TLDS) {
    const dist = lev(t, tld);
    if (dist < bestTD && dist > 0 && dist <= 1) { bestTD = dist; bestT = t; }
  }
  if (bestT) return `${local}@${base}.${bestT}`;
  return null;
}

// ===================================================================
// EMAIL PROMPT (na 1e collectie) — low-friction conversion tussen swipes
// ===================================================================
function EmailPrompt({ onSubmit, onSkip }) {
  const [email, setEmail] = useState('');
  const [honeypot, setHoneypot] = useState('');
  const [phase, setPhase] = useState('idle'); // idle | loading | error
  const [turnstileToken, setTurnstileToken] = useState('');
  const [emailSuggestion, setEmailSuggestion] = useState(null);
  const formMountedAt = useRef(Date.now());
  const turnstileRef = useRef(null);

  useEffect(() => { setEmailSuggestion(suggestEmail(email)); }, [email]);

  useEffect(() => {
    let widgetId = null; let cancelled = false;
    const tryRender = () => {
      if (cancelled) return;
      if (!window.turnstile || !turnstileRef.current) { setTimeout(tryRender, 200); return; }
      widgetId = window.turnstile.render(turnstileRef.current, {
        sitekey: TURNSTILE_SITE_KEY,
        callback: (t) => setTurnstileToken(t),
        'error-callback': () => setTurnstileToken(''),
        'expired-callback': () => setTurnstileToken(''),
        theme: 'light', size: 'flexible',
      });
    };
    tryRender();
    return () => {
      cancelled = true;
      if (widgetId !== null && window.turnstile) { try { window.turnstile.remove(widgetId); } catch (e) {} }
    };
  }, []);

  const submit = async (e) => {
    e.preventDefault();
    if (!email || phase === 'loading') return;
    if (emailSuggestion) {
      const useSuggestion = window.confirm(`even checken — bedoel je "${emailSuggestion}"?`);
      if (useSuggestion) { setEmail(emailSuggestion); setEmailSuggestion(null); return; }
    }
    setPhase('loading');
    if (window.KechDB) {
      const result = await window.KechDB.recordWaitlist({
        email, honeypot,
        formAgeMs: Date.now() - formMountedAt.current,
        turnstileToken,
      });
      if (result && result.error) {
        setPhase('error');
        return;
      }
      window.KechDB.updateSessionProgress({ completedStep: 'waitlist' });
    }
    onSubmit(email);
  };

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'rgba(25,20,20,0.55)',
      backdropFilter: 'blur(2px)',
      WebkitBackdropFilter: 'blur(2px)',
      display: 'grid', placeItems: 'center', padding: '20px',
      animation: 'kech-fade-in 220ms ease-out',
      overflowY: 'auto'
    }}>
      <div className="pop" style={{
        position: 'relative',
        background: 'var(--kech-white)',
        border: '4px solid var(--kech-black)',
        borderRadius: 22,
        padding: '26px 24px 28px',
        maxWidth: 440, width: '100%',
        boxShadow: '7px 7px 0 var(--kech-fuchsia), 7px 7px 0 4px var(--kech-black)',
        textAlign: 'center',
        margin: 'auto'
      }}>
        {/* Decorative "almost done" sticker */}
        <div style={{
          position: 'absolute', top: -16, right: -10,
          background: 'var(--kech-aqua)', color: 'var(--kech-black)',
          border: '3px solid var(--kech-black)', borderRadius: 999,
          padding: '6px 12px 8px', fontFamily: 'Kechfont, system-ui',
          fontWeight: 800, fontSize: 14, textTransform: 'lowercase',
          transform: 'rotate(8deg)', boxShadow: '3px 3px 0 var(--kech-black)',
          whiteSpace: 'nowrap'
        }}>laatste stap</div>
        <div style={{
          fontFamily: 'Kechfont, system-ui', fontWeight: 800,
          fontSize: 'clamp(36px, 7vw, 56px)', lineHeight: 0.9, letterSpacing: '-0.02em',
          color: 'var(--kech-black)', textTransform: 'lowercase',
          textShadow: '0 3px 0 rgba(255,255,255,0.4)', margin: '0 0 6px'
        }}>grote speler</div>
        <p style={{ margin: '0 0 18px', fontSize: 15, lineHeight: 1.45, fontWeight: 600, color: 'var(--kech-black)', opacity: 0.85 }}>
          gun je email en ben er als eerste bij
        </p>

        {phase === 'error' ? (
          <div style={{ padding: '12px 16px', background: 'var(--kech-fuchsia)', color: 'var(--kech-black)', border: '3px solid var(--kech-black)', borderRadius: 14, marginBottom: 16, fontSize: 14, fontWeight: 600 }}>
            iets ging mis. probeer 't later op de waitlist-pagina aan het einde.
          </div>
        ) : null}

        <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {/* honeypot */}
          <input
            type="text" name="website" tabIndex={-1} autoComplete="off"
            value={honeypot} onChange={(e) => setHoneypot(e.target.value)}
            aria-hidden="true"
            style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0, pointerEvents: 'none' }} />

          <input
            type="email" required value={email} onChange={(e) => setEmail(e.target.value)}
            placeholder="jouw@email.nl"
            className="kech-input"
            style={{ width: '100%' }}
            autoFocus />

          {emailSuggestion && (
            <div style={{
              fontSize: 13, fontWeight: 600, color: 'var(--kech-black)',
              background: 'var(--kech-aqua)', padding: '6px 14px 8px',
              borderRadius: 999, border: '2px solid var(--kech-black)',
              alignSelf: 'center'
            }}>
              bedoel je{' '}
              <button type="button" onClick={() => { setEmail(emailSuggestion); setEmailSuggestion(null); }}
                style={{ background: 'transparent', border: 'none', padding: 0, fontWeight: 800, color: 'var(--kech-fuchsia)', cursor: 'pointer', textDecoration: 'underline', fontFamily: 'inherit', fontSize: 'inherit' }}>
                {emailSuggestion}
              </button>?
            </div>
          )}

          <div ref={turnstileRef} style={{ display: 'flex', justifyContent: 'center', minHeight: 65 }} />

          <button type="submit" className="kbtn"
            disabled={phase === 'loading' || !email || !turnstileToken}
            style={{ width: '100%', fontSize: 17 }}>
            {phase === 'loading' ? '...' : !turnstileToken ? 'even verifiëren…' : 'hou me op de hoogte →'}
          </button>

          <button type="button" onClick={onSkip}
            className="kbtn kbtn--ghost kbtn--small"
            style={{ width: '100%', background: 'transparent', borderColor: 'var(--kech-black)', color: 'var(--kech-black)', fontSize: 14 }}>
            ik ben een kleine speler, ga verder zonder email
          </button>
        </form>
      </div>
    </div>
  );
}

function Waitlist({ initialCount = 1247, onReset, skipForm = false }) {
  const [email, setEmail] = useState('');
  const [honeypot, setHoneypot] = useState('');
  const [phase, setPhase] = useState(skipForm ? 'success' : 'idle'); // idle | loading | success
  const [count, setCount] = useState(initialCount);
  const [copied, setCopied] = useState(false);
  const [showToast, setShowToast] = useState(false);
  const [turnstileToken, setTurnstileToken] = useState('');
  const [emailSuggestion, setEmailSuggestion] = useState(null);
  const formMountedAt = useRef(Date.now()); // for bot-timing check
  const turnstileRef = useRef(null);

  // Detect typos (.vom → .com, gmial → gmail) on every keystroke
  useEffect(() => {
    setEmailSuggestion(suggestEmail(email));
  }, [email]);

  // Live waitlist count from Supabase (success-page counter)
  useEffect(() => {
    let cancelled = false;
    if (window.KechDB && window.KechDB.getWaitlistCount) {
      window.KechDB.getWaitlistCount().then((n) => {
        if (!cancelled && typeof n === 'number') setCount(n);
      });
    }
    return () => { cancelled = true; };
  }, []);

  // Render Turnstile widget once script + DOM are ready
  useEffect(() => {
    if (phase === 'success') return;
    let widgetId = null;
    let cancelled = false;
    const tryRender = () => {
      if (cancelled) return;
      if (!window.turnstile || !turnstileRef.current) {
        setTimeout(tryRender, 200);
        return;
      }
      widgetId = window.turnstile.render(turnstileRef.current, {
        sitekey: TURNSTILE_SITE_KEY,
        callback: (token) => setTurnstileToken(token),
        'error-callback': () => setTurnstileToken(''),
        'expired-callback': () => setTurnstileToken(''),
        theme: 'light',
      });
    };
    tryRender();
    return () => {
      cancelled = true;
      if (widgetId !== null && window.turnstile) {
        try { window.turnstile.remove(widgetId); } catch (e) {}
      }
    };
  }, [phase]);

  const submit = (e) => {
    e.preventDefault();
    if (!email || phase === 'success') return;
    // Block submit als er een typo-suggestie is — vraag bevestiging
    if (emailSuggestion) {
      const useSuggestion = window.confirm(
        `even checken — bedoel je "${emailSuggestion}"?\n\n` +
        `OK = gebruik de gecorrigeerde versie\n` +
        `Annuleren = jouw versie ("${email}") is goed`
      );
      if (useSuggestion) {
        setEmail(emailSuggestion);
        setEmailSuggestion(null);
        return; // user moet opnieuw submit-knop klikken (bevestigt nieuwe waarde)
      }
    }
    setPhase('loading');
    setShowToast(true);
    setTimeout(() => setShowToast(false), 3000);
    if (window.KechDB) {
      window.KechDB.recordWaitlist({
        email,
        honeypot,
        formAgeMs: Date.now() - formMountedAt.current,
        turnstileToken,
      });
      window.KechDB.updateSessionProgress({ completedStep: 'waitlist' });
    }
    setTimeout(() => {
      setPhase('success');
      setCount((c) => c + 1);
    }, 700);
  };

  const shareUrl = typeof window !== 'undefined' ? window.location.href : 'kechballen.nl';
  const whatsappLink = `https://wa.me/?text=${encodeURIComponent(`yo, swipe even mee bij kechballen — kerst krijgt een upgrade. ${shareUrl}`)}`;

  if (phase === 'success') {
    return (
      <section className="page" style={{ position: 'relative', background: 'var(--kech-aqua)', overflow: 'hidden' }}>
        {/* Confetti dots */}
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage:
          'radial-gradient(circle, var(--kech-fuchsia) 6px, transparent 7px),' +
          'radial-gradient(circle, var(--kech-black) 4px, transparent 5px)',
          backgroundSize: '120px 120px, 80px 80px',
          backgroundPosition: '0 0, 40px 40px',
          opacity: 0.4
        }} />
        <Ticker variant="black" speed={54} items={['Sneeuw drip drop', '🔥 first dibs', 'thanks dushi', 'tot ziens bij de drop', 'louter grote spelers']} />

        <div style={{ position: 'relative', zIndex: 2, maxWidth: 720, margin: '0 auto', padding: '64px 24px 80px', textAlign: 'center' }}>
          <div className="pop" style={{
            display: 'inline-block',
            background: 'var(--kech-black)', color: 'var(--kech-aqua)',
            border: '4px solid var(--kech-black)', borderRadius: 18,
            padding: '12px 24px 14px',
            fontFamily: 'Kechfont, system-ui', fontWeight: 800, fontSize: 22,
            textTransform: 'lowercase', lineHeight: 1, transform: 'rotate(-3deg)',
            boxShadow: '5px 5px 0 var(--kech-fuchsia)',
            marginBottom: 22
          }}>kechies 4ever</div>

          <h2 className="rise" style={{
            fontFamily: 'Kechfont, system-ui', fontWeight: 800,
            fontSize: 'clamp(56px, 10vw, 140px)', lineHeight: 0.82, letterSpacing: '-0.025em',
            color: 'var(--kech-black)', textTransform: 'lowercase', margin: 0,
            textShadow: '0 4px 0 rgba(255,255,255,0.6)'
          }}>Je bent<br />erbij</h2>

          <p className="rise" style={{ animationDelay: '120ms', marginTop: 22, fontSize: 18, fontWeight: 600, color: 'var(--kech-black)', maxWidth: 480, marginInline: 'auto' }}>
            ik mail je zodra we het echt gaan produceren, help me door dit te verspreiden!
          </p>

          {/* Counter */}
          <div className="rise" style={{
            animationDelay: '240ms',
            display: 'inline-flex', alignItems: 'center', gap: 10,
            marginTop: 28, padding: '12px 22px',
            background: 'var(--kech-white)', border: '3px solid var(--kech-black)',
            borderRadius: 999, boxShadow: '4px 4px 0 var(--kech-fuchsia)',
            fontFamily: 'Kechfont, system-ui', fontWeight: 800, fontSize: 22,
            textTransform: 'lowercase', color: 'var(--kech-black)', lineHeight: 1
          }}>
            <span style={{ width: 10, height: 10, borderRadius: 999, background: 'var(--kech-fuchsia)' }} />
            je bent nr <span style={{ color: 'var(--kech-fuchsia)' }}>#{count}</span> op de lijst
          </div>

          {/* Share */}
          <div style={{ marginTop: 36, display: 'flex', gap: 14, justifyContent: 'center', flexWrap: 'wrap' }}>
            <a href={whatsappLink} target="_blank" rel="noopener noreferrer" className="kbtn">
              whatsapp je harem →
            </a>
            <button
              className="kbtn kbtn--aqua"
              style={{ background: 'var(--kech-black)', color: 'var(--kech-aqua)', boxShadow: '5px 5px 0 var(--kech-fuchsia), 5px 5px 0 3px var(--kech-black)' }}
              onClick={() => {
                navigator.clipboard?.writeText(shareUrl);
                setCopied(true);
                setTimeout(() => setCopied(false), 1800);
              }}>
              {copied ? '✓ gekopieerd' : 'kopieer link'}
            </button>
          </div>

          {/* Socials */}
          <div style={{ marginTop: 40, display: 'flex', gap: 14, justifyContent: 'center', alignItems: 'center' }}>
            <SocialIcon href="https://www.instagram.com/kechballen/" label="instagram">
              <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <rect x="3" y="3" width="18" height="18" rx="5" />
                <circle cx="12" cy="12" r="4" />
                <circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none" />
              </svg>
            </SocialIcon>
            <SocialIcon href="https://www.tiktok.com/@kechballen_official" label="tiktok">
              <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor" aria-hidden="true">
                <path d="M14 3v10.2a2.8 2.8 0 1 1-2.8-2.8h.8V7.5h-.8a5.7 5.7 0 1 0 5.7 5.7V8.6a6.5 6.5 0 0 0 3.6 1.1V6.8a3.6 3.6 0 0 1-3.6-3.6V3H14z" />
              </svg>
            </SocialIcon>
            <SocialIcon href="https://www.facebook.com/profile.php?id=61576428306652" label="facebook">
              <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor" aria-hidden="true">
                <path d="M13.5 21v-7.5h2.5l.4-3h-2.9V8.6c0-.9.3-1.5 1.5-1.5h1.5V4.4c-.3 0-1.2-.1-2.2-.1-2.2 0-3.7 1.3-3.7 3.8v2.4H8v3h2.6V21h2.9z" />
              </svg>
            </SocialIcon>
          </div>

          {onReset &&
          <div style={{ marginTop: 36 }}>
              <button onClick={onReset} className="kbtn kbtn--ghost kbtn--small" style={{ color: 'var(--kech-black)', borderColor: 'var(--kech-black)' }}>
                opnieuw swipen ↺
              </button>
            </div>
          }
        </div>
      </section>);

  }

  return (
    <section className="page" style={{
      position: 'relative',
      background:
      'radial-gradient(60% 70% at 20% 20%, #FBA8D2 0%, rgba(251,168,210,0) 60%),' +
      'radial-gradient(55% 65% at 38% 40%, #F037A5 0%, rgba(240,55,165,0) 55%),' +
      'radial-gradient(60% 70% at 78% 78%, #C9F7EE 0%, rgba(201,247,238,0) 60%),' +
      'radial-gradient(45% 55% at 65% 55%, #9BF0E1 0%, rgba(155,240,225,0) 65%),' +
      'linear-gradient(135deg, #FBA8D2 0%, #F037A5 35%, #6FC9BB 70%, #C9F7EE 100%)',
      overflow: 'hidden'
    }}>
      <div className="halftone" style={{ opacity: 0.35, mixBlendMode: 'multiply' }} />
      <Ticker variant="black" speed={54} items={['first dibs', 'lijst groeit', 'wejow', 'je moeder wilt ook', 'thanks dushi', 'de grap wordt echt']} />

      <FloatingSticker top="14%" left="6%" rot={-6} bg="var(--kech-aqua)" delay={0.2}>laatste stap</FloatingSticker>
      <FloatingSticker bottom="14%" right="6%" rot={6} bg="var(--kech-fuchsia)" delay={0.5}>geen spam</FloatingSticker>

      {/* Toast */}
      {showToast &&
      <div className="pop" style={{
        position: 'fixed', top: 32, left: '50%', transform: 'translateX(-50%) rotate(-2deg)',
        zIndex: 100,
        background: 'var(--kech-black)', color: 'var(--kech-aqua)',
        border: '4px solid var(--kech-black)', borderRadius: 14,
        padding: '14px 24px 16px',
        fontFamily: 'Kechfont, system-ui', fontWeight: 800, fontSize: 22,
        textTransform: 'lowercase', lineHeight: 1,
        boxShadow: '6px 6px 0 var(--kech-fuchsia)'
      }}>
          je bent m'n favo kech 💖
        </div>
      }

      <div style={{ position: 'relative', zIndex: 2, maxWidth: 680, margin: '0 auto', padding: '72px 24px 100px', textAlign: 'center' }}>
        <h2 style={{
          fontFamily: 'Kechfont, system-ui', fontWeight: 800,
          fontSize: 'clamp(40px, 7vw, 84px)', lineHeight: 0.88, letterSpacing: '-0.02em',
          color: 'var(--kech-fuchsia-ink, #B8267B)', textTransform: 'lowercase',
          margin: '0 0 0',
          textShadow: '0 3px 0 rgba(255,255,255,0.5)'
        }}>thanks<br /><span style={{ color: 'var(--kech-black)' }}>wees er als eerste bij</span></h2>

        <p style={{ marginTop: 18, fontSize: 17, color: 'var(--kech-black)', maxWidth: 480, marginInline: 'auto', fontWeight: 600, opacity: 0.85 }}>
          top hoes zijn erbij vanaf day 1. wil jij het niet missen? gun me je emailadres en ik laat het je weten zodra deze grap echt wordt (soon!)
        </p>

        <form onSubmit={submit} style={{ marginTop: 32, display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center' }}>
          {/* Honeypot — hidden from humans, bots fill it = rejected by RLS */}
          <input
            type="text" name="website" tabIndex={-1} autoComplete="off"
            value={honeypot} onChange={(e) => setHoneypot(e.target.value)}
            aria-hidden="true"
            style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0, pointerEvents: 'none' }} />
          <input
            type="email" required value={email} onChange={(e) => setEmail(e.target.value)}
            placeholder="jouw@email.nl"
            className="kech-input"
            style={{ flex: '1 1 280px', maxWidth: 380 }} />

          <button type="submit" className="kbtn" disabled={phase === 'loading' || !turnstileToken} style={{ fontFamily: "Inter", fontSize: "14px" }}>
            {phase === 'loading' ? '...' : !turnstileToken ? 'even verifiëren…' : 'ik ben een grote speler en ik gun →'}
          </button>
        </form>

        {/* Email typo suggestion (live tijdens typen) */}
        {emailSuggestion && phase !== 'success' && (
          <div style={{
            marginTop: 10, fontSize: 14, fontWeight: 600, color: 'var(--kech-black)',
            background: 'var(--kech-aqua)', display: 'inline-block',
            padding: '6px 14px 8px', borderRadius: 999,
            border: '2px solid var(--kech-black)',
            boxShadow: '3px 3px 0 var(--kech-fuchsia)'
          }}>
            bedoel je{' '}
            <button
              type="button"
              onClick={() => { setEmail(emailSuggestion); setEmailSuggestion(null); }}
              style={{
                background: 'transparent', border: 'none', padding: 0,
                fontWeight: 800, color: 'var(--kech-fuchsia)', cursor: 'pointer',
                textDecoration: 'underline', fontFamily: 'inherit', fontSize: 'inherit'
              }}
            >{emailSuggestion}</button>?
          </div>
        )}

        {/* Cloudflare Turnstile widget */}
        <div ref={turnstileRef} style={{ marginTop: 16, display: 'flex', justifyContent: 'center' }}></div>

        <p style={{ marginTop: 18, fontSize: 12, color: 'var(--kech-black)', opacity: 0.6, fontFamily: 'var(--font-mono)', textTransform: 'uppercase', letterSpacing: '0.18em' }}>NIET VOOR KLEINE SPELERS. NUL SPAM. SEE YOU SOON.

        </p>

        {/* Social icons */}
        <div style={{ marginTop: 36, display: 'flex', gap: 14, justifyContent: 'center', alignItems: 'center' }}>
          <SocialIcon href="https://www.instagram.com/kechballen/" label="instagram">
            <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <rect x="3" y="3" width="18" height="18" rx="5" />
              <circle cx="12" cy="12" r="4" />
              <circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none" />
            </svg>
          </SocialIcon>
          <SocialIcon href="https://www.tiktok.com/@kechballen_official" label="tiktok">
            <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor" aria-hidden="true">
              <path d="M14 3v10.2a2.8 2.8 0 1 1-2.8-2.8h.8V7.5h-.8a5.7 5.7 0 1 0 5.7 5.7V8.6a6.5 6.5 0 0 0 3.6 1.1V6.8a3.6 3.6 0 0 1-3.6-3.6V3H14z" />
            </svg>
          </SocialIcon>
          <SocialIcon href="https://www.facebook.com/profile.php?id=61576428306652" label="facebook">
            <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor" aria-hidden="true">
              <path d="M13.5 21v-7.5h2.5l.4-3h-2.9V8.6c0-.9.3-1.5 1.5-1.5h1.5V4.4c-.3 0-1.2-.1-2.2-.1-2.2 0-3.7 1.3-3.7 3.8v2.4H8v3h2.6V21h2.9z" />
            </svg>
          </SocialIcon>
        </div>

        {/* Back to home */}
        {onReset &&
        <div style={{ marginTop: 32 }}>
            <button onClick={onReset} className="kbtn kbtn--ghost kbtn--small" style={{ color: 'var(--kech-black)', borderColor: 'var(--kech-black)' }}>
              ← terug naar de start
            </button>
          </div>
        }
      </div>
    </section>);

}

window.KechForms = { FeedbackForm, Waitlist, EmailPrompt };