/* Conversion audit variant for the Copilot landing.
   Keeps the original v2-mascot.jsx untouched while testing the approved
   office-hours restructuring: pain-first hero, early-access CTA, proof,
   situation-based audience, conservative trust, and staged preorder flow. */

// Live Paddle: Interview Co-Pilot early access ($15 one-time)
const PADDLE_CLIENT_TOKEN = 'live_719ff94a561fc390c1a5ed09de2';
const PADDLE_PRICE_ID = 'pri_01ks09s06q07fqyrbhybawjnh8';
const PADDLE_SCRIPT_SRC = 'https://cdn.paddle.com/paddle/v2/paddle.js';
// Optional: hosted pay page on an approved domain (see copilot-pay.html)
const PADDLE_CHECKOUT_URL = '';

const V2_CONVERSION_QUALIFICATION_OPTIONS = ["Weekly", "Monthly", "A few times per quarter", "Rarely"];
const V2_CONVERSION_ONBOARDING_CALL_URL = "[ONBOARDING_CALL_URL]";
const V2_CONVERSION_PREORDER_INITIAL = 17;
const V2_CONVERSION_PREORDER_TOTAL = 30;
const V2_CONVERSION_PRIMARY_CTA = "Get early access";
const V2_CHECKOUT_PLAN = "Pre-order";

// Must not be named `znTrack` — Babel hoists top-level vars onto window and
// would overwrite analytics.js's window.znTrack, causing infinite recursion.
const callZnTrack = (eventName, properties) => {
  if (typeof window !== 'undefined' && typeof window.znTrack === 'function') {
    window.znTrack(eventName, properties || {});
  }
};

const META_PAYMENT_PARAMS = {
  value: 15,
  currency: 'USD',
  content_name: 'Zernote Interview Co-Pilot founding access',
};

const GOOGLE_PAYMENT_CONVERSION_SEND_TO = 'AW-18177397973/cmQKCJi8wLgcENWp1NtD';
const GOOGLE_PAYMENT_CONVERSION_KEY = 'zn_google_payment_conversion_tracked';

const getMetaEventOptions = () => {
  if (typeof window === 'undefined') return undefined;
  const testEventCode = window.__META_TEST_EVENT_CODE || new URLSearchParams(window.location.search).get('test_event_code');
  return testEventCode ? { test_event_code: testEventCode } : undefined;
};

const trackMetaEvent = (eventName, params = {}, method = 'track') => {
  if (typeof window !== 'undefined' && typeof window.fbq === 'function') {
    const options = getMetaEventOptions();
    if (options) {
      window.fbq(method, eventName, params, options);
      if (typeof window.__trackMetaTestFallback === 'function') {
        window.__trackMetaTestFallback(eventName, params);
      }
    } else {
      window.fbq(method, eventName, params);
    }
  }
};

const trackGoogleAdsEvent = (eventName, params = {}) => {
  if (typeof window !== 'undefined' && typeof window.gtag === 'function') {
    window.gtag('event', eventName, params);
  }
};

const trackGooglePaymentConversion = (eventData) => {
  if (typeof window === 'undefined') return;
  try {
    if (window.sessionStorage.getItem(GOOGLE_PAYMENT_CONVERSION_KEY)) return;
  } catch (e) {
    // sessionStorage can be unavailable in strict browser privacy modes.
  }

  const checkoutData = eventData && eventData.data ? eventData.data : {};
  const value = Number(checkoutData.totals && checkoutData.totals.total);
  const currency = checkoutData.currency_code || META_PAYMENT_PARAMS.currency;
  const params = {
    send_to: GOOGLE_PAYMENT_CONVERSION_SEND_TO,
    value: Number.isFinite(value) ? value : META_PAYMENT_PARAMS.value,
    currency,
    transaction_id: checkoutData.transaction_id || '',
  };

  trackGoogleAdsEvent('conversion', params);

  try {
    window.sessionStorage.setItem(GOOGLE_PAYMENT_CONVERSION_KEY, '1');
  } catch (e) {
    // Ignore storage failures; tracking should not block the checkout flow.
  }
};

const loadPaddleScript = (() => {
  let promise = null;
  return () => {
    if (typeof window === 'undefined') {
      return Promise.reject(new Error('window is not available'));
    }
    if (window.Paddle) {
      return Promise.resolve(window.Paddle);
    }
    if (promise) {
      return promise;
    }
    promise = new Promise((resolve, reject) => {
      const existing = document.querySelector(`script[src="${PADDLE_SCRIPT_SRC}"]`);
      if (existing) {
        existing.addEventListener('load', () => resolve(window.Paddle), { once: true });
        existing.addEventListener('error', () => reject(new Error('Failed to load Paddle.js')), { once: true });
        return;
      }
      const script = document.createElement('script');
      script.src = PADDLE_SCRIPT_SRC;
      script.async = true;
      script.onload = () => resolve(window.Paddle);
      script.onerror = () => reject(new Error('Failed to load Paddle.js'));
      document.head.appendChild(script);
    });
    return promise;
  };
})();

const V2ConversionTopBar = ({ onCtaClick }) => (
  <header className="zn-nav-bar is-dark">
    <div className="zn-nav-bar__inner">
      <a className="zn-nav-bar__brand" href="#">
        <img src="ds/logos/wordmark-dark.svg" alt="zernote" height="14" style={{ height: 14 }} />
      </a>
      <nav className="zn-nav-bar__nav">
        <a href="#features">What it does</a>
        <a href="#how">Trust</a>
        <a href="#pricing">Founding access</a>
      </nav>
      <div className="zn-nav-bar__right">
        <button onClick={onCtaClick} className="zn-btn zn-btn--primary zn-btn--sm">
          {V2_CONVERSION_PRIMARY_CTA} <Icon name="arrow" size={14} />
        </button>
      </div>
    </div>
  </header>
);

const V2ConversionFooter = () => (
  <footer className="zn-foot">
    <div className="zn-foot__inner">
      <div className="zn-foot__brand">
        <img src="ds/logos/full-logo-dark.svg" alt="zernote" style={{ height: 28 }} />
        <p className="zn-foot__tag">Tools for user researchers, by Zernote Inc.</p>
      </div>
      <div className="zn-foot__cols">
        <div>
          <h5>Product</h5>
          <a href="#features">What it does</a>
          <a href="#how">Trust and boundaries</a>
          <a href="#pricing">Founding access</a>
        </div>
        <div>
          <h5>Coming soon</h5>
          <a href="#fit">Who it is for</a>
          <a href="#features">Live follow-ups</a>
          <a href="#pricing">Q3 2026 launch</a>
        </div>
        <div>
          <h5>Company</h5>
          <a href="mailto:hello@zernote.com">Contact</a>
        </div>
      </div>
    </div>
    <div className="zn-foot__bottom">
      <span>© 2026 Zernote Inc.</span>
      <span>zernote.com</span>
    </div>
  </footer>
);

const V2ConversionStyles = () => (
  <style>{`
    .v2 .v2-proof-strip {
      margin-top: 40px;
      padding: 42px;
      border: 1px solid rgba(22,131,255,.24);
      border-radius: var(--radius-lg);
      background:
        radial-gradient(circle at 16% 12%, rgba(0,109,250,.28), transparent 34%),
        radial-gradient(circle at 86% 4%, rgba(22,131,255,.18), transparent 30%),
        linear-gradient(135deg, #071426, var(--z-navy-800));
      box-shadow: 0 24px 80px rgba(0,109,250,.16), 0 18px 70px rgba(11,16,32,.22);
    }
    .v2 .v2-proof-strip .zn-eyebrow {
      display: inline-flex;
      background: rgba(0,109,250,.16);
      border-color: rgba(22,131,255,.32);
      color: rgba(213,232,255,.88);
    }
    .v2 .v2-proof-main {
      margin-top: 22px;
      max-width: 760px;
    }
    .v2 .v2-proof-main__quote {
      margin: 0;
      font: 600 40px/52px var(--font-ui);
      letter-spacing: -0.025em;
      color: var(--fg-on-dark);
      text-wrap: balance;
    }
    .v2 .v2-proof-person {
      display: flex;
      align-items: center;
      gap: 14px;
      margin-top: 26px;
      font: 500 17px/26px var(--font-ui);
      color: var(--fg-on-dark);
    }
    .v2 .v2-proof-person__avatar {
      width: 44px;
      height: 44px;
      border-radius: 999px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      background: rgba(0,109,250,.2);
      border: 1px solid rgba(22,131,255,.28);
      color: var(--fg-on-dark);
      font: 700 15px/20px var(--font-ui);
      flex-shrink: 0;
    }
    .v2 .v2-proof-person__meta {
      color: var(--fg-on-dark-muted);
    }
    .v2 .v2-proof-divider {
      height: 1px;
      margin: 44px 0 34px;
      background: linear-gradient(90deg, rgba(22,131,255,.34), rgba(255,255,255,.08));
    }
    .v2 .v2-proof-strip__quotes {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20px;
      margin-top: 0;
    }
    .v2 .v2-proof-strip__quotes blockquote {
      margin: 0;
      padding: 26px 28px;
      border-radius: 16px;
      background: rgba(0,109,250,.08);
      border: 1px solid rgba(22,131,255,.18);
      font: 600 21px/32px var(--font-ui);
      color: var(--fg-on-dark);
      text-wrap: pretty;
      min-height: 144px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: flex-start;
    }
    .v2 .v2-proof-card__source {
      display: block;
      margin-top: 20px;
      font: 500 15px/22px var(--font-ui);
      color: var(--fg-on-dark-muted);
    }
    .v2 .v2-product-intro {
      margin-top: 56px;
      max-width: 760px;
    }
    .v2 .v2-overlay-wrap {
      margin-top: 32px;
    }
    .v2 .v2-overlay-wrap::before {
      content: "Here’s what you actually see: guidance beside the live call.";
    }
    .v2 .v2-fit {
      max-width: 820px;
    }
    .v2 .v2-trust-layout {
      display: grid;
      grid-template-columns: minmax(0, .85fr) minmax(0, 1.15fr);
      gap: 56px;
      align-items: start;
    }
    .v2 .v2-trust-mascot {
      width: 252px;
      height: 252px;
      margin-top: 64px;
      margin-left: 76px;
      margin-right: auto;
      border-radius: 999px;
      display: grid;
      place-items: center;
      background:
        radial-gradient(circle at 52% 46%, rgba(255,255,255,.92), rgba(255,255,255,.72) 43%, rgba(255,255,255,0) 44%),
        var(--surface-card);
      border: 1px solid var(--stroke-card);
      box-shadow: 0 20px 60px rgba(11,16,32,.08);
      overflow: hidden;
    }
    .v2 .v2-trust-mascot img {
      width: 176px;
      height: auto;
      display: block;
      transform: scaleX(-1) rotate(4deg) translate(2px, 5px);
    }
    .v2 .v2-trust-rows {
      border-top: 1px solid var(--stroke-card);
    }
    .v2 .v2-trust-row {
      display: grid;
      grid-template-columns: 48px minmax(0, 1fr);
      gap: 18px;
      padding: 26px 0;
      border-bottom: 1px solid var(--stroke-card);
    }
    .v2 .v2-trust-row__icon {
      width: 40px;
      height: 40px;
      border-radius: 10px;
      background: var(--surface-pill);
      border: 1px solid var(--stroke-pill);
      display: inline-flex;
      align-items: center;
      justify-content: center;
      color: var(--z-blue-600);
    }
    .v2 .v2-trust-row h3 {
      margin: 0 0 8px;
      font: 700 21px/28px var(--font-ui);
      letter-spacing: -0.015em;
      color: var(--fg-1);
    }
    .v2 .v2-trust-row p {
      margin: 0;
      font: 400 17px/28px var(--font-ui);
      color: var(--fg-2);
      text-wrap: pretty;
    }
    .v2 .v2-price-card {
      padding: 34px;
      border: 1px solid rgba(22,131,255,.24);
      background:
        radial-gradient(circle at 18% 0%, rgba(0,109,250,.24), transparent 34%),
        radial-gradient(circle at 94% 18%, rgba(22,131,255,.16), transparent 30%),
        linear-gradient(135deg, #071426, var(--z-navy-800));
      color: var(--fg-on-dark);
      box-shadow: 0 24px 80px rgba(0,109,250,.16), 0 18px 70px rgba(11,16,32,.2);
    }
    .v2 .v2-price-card .zn-price__name,
    .v2 .v2-price-card .zn-price__num {
      color: var(--fg-on-dark);
    }
    .v2 .v2-price-card .zn-price__amount {
      gap: 10px;
      flex-wrap: wrap;
    }
    .v2 .v2-price-card .zn-price__amount del {
      font: 600 16px/24px var(--font-ui);
      color: var(--fg-on-dark-muted);
    }
    .v2 .v2-price-card .zn-price__per {
      color: rgba(213,232,255,.78);
    }
    .v2 .v2-price-card .zn-price__feats {
      gap: 14px;
    }
    .v2 .v2-price-card .zn-price__feats li {
      font: 400 15px/23px var(--font-ui);
      color: rgba(213,232,255,.78);
    }
    .v2 .v2-price-card .zn-price__feats strong {
      font-weight: 800;
      color: var(--fg-on-dark);
    }
    .v2 .v2-price-card .v2-preorder-progress__meta {
      color: rgba(213,232,255,.72);
    }
    .v2 .v2-price-card .v2-preorder-progress__meta span:first-child {
      color: var(--fg-on-dark);
    }
    .v2 .v2-price-card .v2-preorder-progress__meta span:last-child {
      color: var(--fg-on-dark-muted);
    }
    .v2 .v2-price-card .v2-preorder-progress__track {
      border-color: rgba(22,131,255,.28);
      background: rgba(0,109,250,.14);
    }
    .v2 .v2-price-card .v2-preorder-progress__track span {
      background: linear-gradient(90deg, var(--z-blue-600), var(--z-blue-500));
      box-shadow: 0 0 22px rgba(22,131,255,.44);
    }
    .v2 .v2-price-card .zn-price__cta {
      box-shadow: 0 14px 36px rgba(0,109,250,.3);
    }
    @media (max-width: 768px) {
      .v2 .v2-proof-strip {
        margin-top: 28px;
        padding: 22px;
      }
      .v2 .v2-proof-main__quote {
        font-size: 30px;
        line-height: 38px;
      }
      .v2 .v2-proof-person {
        align-items: flex-start;
        font-size: 15px;
        line-height: 23px;
      }
      .v2 .v2-proof-divider {
        margin: 30px 0 22px;
      }
      .v2 .v2-proof-strip__quotes {
        grid-template-columns: 1fr;
      }
      .v2 .v2-proof-strip__quotes blockquote {
        min-height: 0;
        font-size: 18px;
        line-height: 28px;
      }
      .v2 .v2-trust-layout {
        grid-template-columns: 1fr;
        gap: 28px;
      }
      .v2 .v2-trust-mascot {
        width: 168px;
        height: 168px;
        margin-top: 32px;
        margin-left: 0;
        margin-right: 0;
      }
      .v2 .v2-trust-mascot img {
        width: 118px;
      }
      .v2 .v2-trust-row {
        grid-template-columns: 40px minmax(0, 1fr);
        gap: 14px;
        padding: 22px 0;
      }
    }
  `}</style>
);

const V2Conversion = () => {
  const t = useTweak();
  const [modalStep, setModalStep] = React.useState(null);
  const [email, setEmail] = React.useState('');
  const [qualification, setQualification] = React.useState('');
  const [payLoading, setPayLoading] = React.useState(false);
  const [payError, setPayError] = React.useState('');
  const [preorderCount, setPreorderCount] = React.useState(V2_CONVERSION_PREORDER_INITIAL);
  const paddleReadyRef = React.useRef(false);
  const paymentCompletedRef = React.useRef(false);
  const emailSubmittedRef = React.useRef(false);
  const checkoutOpenedRef = React.useRef(false);

  const mascotMap = {
    questioning: "ds/logos/mascot-questioning.png",
    tongue: "ds/logos/mascot-tongue.png",
    love: "ds/logos/mascot-love.png",
  };
  const heroMascotSrc = mascotMap[t.heroMascot] || mascotMap.questioning;

  const markPreorderComplete = () => {
    setPreorderCount((count) => Math.min(V2_CONVERSION_PREORDER_TOTAL, count + 1));
  };

  React.useEffect(() => {
    if (typeof window === 'undefined') return;
    const params = new URLSearchParams(window.location.search);
    if (params.get('paid') === '1') {
      markPreorderComplete();
      setModalStep('success');
    }
  }, []);

  const openLeadModal = (e) => {
    if (e) e.preventDefault();
    setPayError('');
    trackMetaEvent('LeadStart', {
      content_name: 'Zernote Interview Co-Pilot early access modal',
    }, 'trackCustom');
    callZnTrack('email_gate_open', {});
    setModalStep('email');
  };

  const closeLeadModal = () => {
    if (
      modalStep &&
      !emailSubmittedRef.current &&
      (modalStep === 'email' || modalStep === 'qualification')
    ) {
      callZnTrack('email_gate_closed', {});
    }
    setModalStep(null);
  };

  const submitLandingForm = async (fields) => {
    try {
      await fetch('/try/api/forms', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          landing: 'copilot-conversion',
          ...fields,
        })
      });
    } catch (e) {
      console.error('Lead form submission failed:', e);
    }
  };

  const submitEmail = async (e) => {
    e.preventDefault();
    if (!email || !email.includes('@')) return;

    console.log('saveEmail:', email);
    await submitLandingForm({
      email,
      where: 'Early access email step',
    });

    trackMetaEvent('Lead', {
      content_name: 'Zernote Interview Co-Pilot email lead',
    });

    if (typeof window.znSetUserId === 'function') window.znSetUserId();
    emailSubmittedRef.current = true;
    callZnTrack('email_submitted', {});

    setModalStep('qualification');
  };

  const submitQualification = async () => {
    console.log('qualification:', qualification);
    await submitLandingForm({
      email,
      qualification,
      where: 'Qualification step',
    });

    trackMetaEvent('QualificationComplete', {
      content_name: 'Zernote Interview Co-Pilot qualification',
      answer: qualification,
    }, 'trackCustom');

    callZnTrack('pre_checkout_view', { plan: V2_CHECKOUT_PLAN });
    setModalStep('checkout');
  };

  const ensurePaddle = async () => {
    const Paddle = await loadPaddleScript();
    if (!Paddle) {
      throw new Error('Paddle.js is unavailable');
    }
    if (!paddleReadyRef.current) {
      Paddle.Initialize({
        token: PADDLE_CLIENT_TOKEN,
        eventCallback: (data) => {
          console.log(data);
          if (data.name === 'checkout.completed') {
            paymentCompletedRef.current = true;
            markPreorderComplete();
            trackMetaEvent('Purchase', META_PAYMENT_PARAMS);
            trackGooglePaymentConversion(data);
            const checkoutData = data.data || {};
            const amount = Number(checkoutData.totals && checkoutData.totals.total);
            callZnTrack('purchase_completed', {
              plan: V2_CHECKOUT_PLAN,
              amount: Number.isFinite(amount) ? amount : META_PAYMENT_PARAMS.value,
              currency: checkoutData.currency_code || META_PAYMENT_PARAMS.currency,
              paddle_txn: checkoutData.transaction_id || '',
            });
            setModalStep('success');
          }
          if (data.name === 'checkout.closed' && !paymentCompletedRef.current) {
            if (checkoutOpenedRef.current) {
              callZnTrack('checkout_abandoned', {});
            }
            setModalStep('checkout');
          }
        },
      });
      paddleReadyRef.current = true;
    }
    return Paddle;
  };

  const openPaddle = async () => {
    setPayError('');
    paymentCompletedRef.current = false;

    if (PADDLE_CHECKOUT_URL) {
      const url = new URL(PADDLE_CHECKOUT_URL);
      if (email) url.searchParams.set('email', email);
      url.searchParams.set('return', window.location.href);
      const pWin = window.open(url.toString(), '_blank');

      const checkClose = setInterval(() => {
        if (pWin && pWin.closed) {
          clearInterval(checkClose);
          setModalStep('checkout');
        }
      }, 500);
      return;
    }

    setPayLoading(true);
    try {
      const Paddle = await ensurePaddle();
      const checkout = {
        items: [{ priceId: PADDLE_PRICE_ID, quantity: 1 }],
        customer: email ? { email } : undefined,
        customData: {
          product: 'copilot_preorder',
          landing: 'copilot-conversion',
          email,
          qualification,
        },
        settings: {
          successUrl: window.location.href.split('#')[0] + '?paid=1',
        },
      };
      trackMetaEvent('InitiateCheckout', META_PAYMENT_PARAMS);
      callZnTrack('checkout_started', {
        plan: V2_CHECKOUT_PLAN,
        amount: META_PAYMENT_PARAMS.value,
        currency: META_PAYMENT_PARAMS.currency,
      });
      checkoutOpenedRef.current = true;
      Paddle.Checkout.open(checkout);
    } catch (e) {
      console.error('Paddle checkout failed:', e);
      setPayError('Could not open checkout. Please try again or email us at hello@zernote.com.');
    } finally {
      setPayLoading(false);
    }
  };

  return (
    <div className="zn-landing v2">
      <V2ConversionStyles />
      <V2ConversionTopBar onCtaClick={openLeadModal} />

      <Section tone="light" padTop={56} padBottom={72}>
        <div className="v2-hero">
          <div>
            <span className="zn-eyebrow">
              <Icon name="sparkle" size={12} />
              For live customer and UX interviews
            </span>
            <h1 className="v2-hero__title">
              Running interviews alone? Zernote catches missed follow-ups while you listen.
            </h1>
            <p className="v2-hero__sub">
              Zernote tracks your guide, spots thin answers, and suggests probes during the live call, before the follow-up window closes.
            </p>

            <div className="v2-hero__cta">
              <button type="button" onClick={openLeadModal} className="zn-btn zn-btn--primary zn-btn--lg">
                {V2_CONVERSION_PRIMARY_CTA} <Icon name="arrow" size={14} />
              </button>
            </div>
            <p className="v2-hero__signature">
              Founding access is $15 after qualification. Full refund if we don’t ship on time.
            </p>
          </div>

          <div className="v2-mascot-stage">
            <img src={heroMascotSrc} alt="Zernote mascot" />

            <div className="v2-bubble v2-bubble--a">
              <Icon name="check" size={14} color="#0E7C3A" />
              <span>Marina just answered Q1. Crossed it off.</span>
            </div>
            <div className="v2-bubble v2-bubble--b">
              <Icon name="sparkle" size={14} />
              <span>Probe: <strong>how did she decide who to trust?</strong></span>
            </div>
            <div className="v2-bubble v2-bubble--c">
              <Icon name="chart" size={14} color="#8A38F5" />
              <span>Emotion block is at 45%.</span>
            </div>
          </div>
        </div>

        <div className="v2-proof-strip" aria-label="What researchers told us">
          <span className="zn-eyebrow zn-eyebrow--soft">What researchers told us</span>
          <div className="v2-proof-main">
            <blockquote className="v2-proof-main__quote">“It would replace the second person we don’t have anyway.”</blockquote>
            <div className="v2-proof-person">
              <span className="v2-proof-person__avatar" aria-hidden="true">SR</span>
              <span>Senior UX Researcher <span className="v2-proof-person__meta">· fintech, pre-sale call</span></span>
            </div>
          </div>
          <div className="v2-proof-divider" aria-hidden="true" />
          <div className="v2-proof-strip__quotes">
            <blockquote>
              <span>“You can get carried away with the discussion and forget to ask a critical question.”</span>
              <span className="v2-proof-card__source">Product designer doing discovery</span>
            </blockquote>
            <blockquote>
              <span>“It’s hard to listen and keep an overview of what you’ve asked at the same time.”</span>
              <span className="v2-proof-card__source">Solo UX researcher, studio</span>
            </blockquote>
          </div>
        </div>

        <div className="v2-product-intro">
          <h2 className="zn-section-title">The moment Zernote helps is during the call, not after it.</h2>
          <p className="zn-section-sub">
            Post-call notes are too late for the question you forgot to ask. Zernote sits beside your call, tracks what has been covered, and surfaces the next useful probe while the conversation is still alive.
          </p>
        </div>
        <div className="v2-overlay-wrap">
          <OverlayDemo height={580} />
        </div>
      </Section>

      <Section id="fit" tone="muted" padTop={84} padBottom={72}>
        <div className="v2-fit">
          <div className="zn-sec__head">
            <h2 className="zn-section-title">Built for people running interviews without a second person.</h2>
            <p className="zn-section-sub">
              If you are responsible for the conversation and the guide at the same time, this is for you: UX researchers, junior researchers, solo consultants, small studios, PMs, founders, and product designers doing discovery.
            </p>
          </div>
        </div>
      </Section>

      <Section id="features" tone="light" padTop={104} padBottom={96}>
        <div className="zn-sec__head">
          <h2 className="zn-section-title">Three jobs. <em>That’s it.</em></h2>
        </div>

        <div className="zn-feat-grid">
          <MascotFeature
            mascot="ds/logos/mascot-questioning.png"
            num="01 · Track"
            title="I show what’s covered and what’s left."
            body="I keep the interview map updated as people answer, so you always see what’s covered and what’s still open." />

          <MascotFeature
            mascot="ds/logos/mascot-love.png"
            num="02 · Suggest"
            title="I suggest what to ask next."
            body="When an answer feels thin, I suggest the next follow-up. You can ask it, tweak it, or skip it." />

          <MascotFeature
            mascot="ds/logos/mascot-tongue.png"
            num="03 · Mark"
            title="I mark moments worth revisiting."
            body="I flag missed topics, strong quotes, and follow-up moments while you stay focused on the call." />
        </div>
      </Section>

      <Section id="how" tone="muted" padTop={76} padBottom={88}>
        <div className="v2-trust-layout">
          <div className="zn-sec__head">
            <h2 className="zn-section-title">Responsible AI for live research calls.</h2>
            <p className="zn-section-sub">
              Use Zernote in sessions where participants know tools may assist. It stays beside the call and supports your interview flow.
            </p>
            <div className="v2-trust-mascot" aria-hidden="true">
              <img src="ds/logos/mascot-tongue.png" alt="" />
            </div>
          </div>
          <div className="v2-trust-rows">
            <TrustRow icon="headset" title="Works with any call platform." body="Use it on Zoom, Google Meet, Microsoft Teams, Telegram calls, or any other interview setup. Zernote sits alongside the conversation, so you do not have to change how you already run calls." />
            <TrustRow icon="pause" title="Clear data terms before live use." body="Early-access users will receive clear data handling terms before using Zernote in live client interviews." />
            <TrustRow icon="target" title="Researchers remain in control." body="AI can’t replace a skilled researcher. You decide whether to ask, edit, or ignore every suggested follow-up." />
          </div>
        </div>
      </Section>

      <Section id="pricing" tone="light" padTop={88} padBottom={120}>
        <div className="zn-sec__head is-centered">
          <span className="zn-eyebrow">Founding access, launch in Q3 2026</span>
          <h2 className="zn-section-title">Reserve founding access.</h2>
        </div>
        <div className="zn-price-row v2-price-row">
          <V2ConversionPricingCard onPreorder={openLeadModal} preorderCount={preorderCount} />
        </div>
      </Section>

      <V2ConversionFooter />
      <V2ConversionPreorderModal
        step={modalStep}
        email={email}
        setEmail={setEmail}
        qualification={qualification}
        setQualification={setQualification}
        payLoading={payLoading}
        payError={payError}
        onClose={closeLeadModal}
        onEmailContinue={submitEmail}
        onQualificationContinue={submitQualification}
        onCheckout={openPaddle}
        preorderCount={preorderCount}
      />
    </div>
  );
};

const V2ConversionPricingCard = ({ onPreorder, preorderCount }) =>
  <div className="zn-price v2-price-card">
    <h3 className="zn-price__name">Founding access</h3>
    <div className="zn-price__amount">
      <span className="zn-price__num">$15</span>
      <del>$30</del>
      <span className="zn-price__per">one time</span>
    </div>
    <ul className="zn-price__feats">
      <li><Icon name="check" size={14} color="#0E7C3A" /><span><strong>Lifetime founding price,</strong> half the planned launch price.</span></li>
      <li><Icon name="check" size={14} color="#0E7C3A" /><span><strong>First access</strong> when the live interview copilot opens in Q3 2026.</span></li>
      <li><Icon name="check" size={14} color="#0E7C3A" /><span><strong>Direct input</strong> into the first pilot workflow.</span></li>
      <li><Icon name="check" size={14} color="#0E7C3A" /><span><strong>Full refund</strong> if we don’t ship on time.</span></li>
    </ul>
    <V2ConversionPreorderProgress count={preorderCount} />
    <button type="button" onClick={onPreorder} className="zn-btn zn-btn--primary zn-btn--lg zn-price__cta">{V2_CONVERSION_PRIMARY_CTA}</button>
  </div>;

const V2ConversionPreorderProgress = ({ count }) => {
  const safeCount = Math.max(0, Math.min(V2_CONVERSION_PREORDER_TOTAL, count));
  const remaining = Math.max(0, V2_CONVERSION_PREORDER_TOTAL - safeCount);
  const progress = `${Math.round((safeCount / V2_CONVERSION_PREORDER_TOTAL) * 100)}%`;

  return (
    <div className="v2-preorder-progress" aria-label={`${safeCount} of ${V2_CONVERSION_PREORDER_TOTAL} founding spots reserved`}>
      <div className="v2-preorder-progress__meta">
        <span>{remaining} founding spots left.</span>
        <span>{safeCount}/{V2_CONVERSION_PREORDER_TOTAL} reserved</span>
      </div>
      <div className="v2-preorder-progress__track">
        <span style={{ width: progress }} />
      </div>
    </div>
  );
};

const V2ConversionPreorderModal = ({
  step,
  email,
  setEmail,
  qualification,
  setQualification,
  payLoading,
  payError,
  onClose,
  onEmailContinue,
  onQualificationContinue,
  onCheckout,
  preorderCount
}) => {
  const dialogRef = React.useRef(null);

  React.useEffect(() => {
    if (step && dialogRef.current) {
      dialogRef.current.focus();
    }
  }, [step]);

  if (!step) return null;

  const closeOnBackdropClick = (e) => {
    if (e.target === e.currentTarget) {
      onClose();
    }
  };

  const closeOnEscape = (e) => {
    if (e.key === 'Escape') {
      onClose();
    }
  };

  return (
    <div
      ref={dialogRef}
      className="v2-modal"
      role="dialog"
      aria-modal="true"
      tabIndex="-1"
      onClick={closeOnBackdropClick}
      onKeyDown={closeOnEscape}
    >
      <div className="v2-modal__card">
        <button type="button" className="v2-modal__close" onClick={onClose} aria-label="Close">×</button>
        {step === "email" && (
          <form onSubmit={onEmailContinue} className="v2-modal__form">
            <h3 className="v2-modal__title">Get early access</h3>
            <p className="v2-modal__copy">
              Join early access for people running interviews without a second researcher. We’ll send the live copilot demo and invite the best-fit users into the first pilot.
            </p>
            <label className="v2-field">
              <span>Email</span>
              <input
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                type="email"
                required
              />
            </label>
            <button type="submit" className="zn-btn zn-btn--primary zn-btn--lg v2-modal__button">Continue to early access</button>
            <p className="v2-modal__consent">
              We’ll email you about Zernote early access. Unsubscribe anytime. Privacy terms will be shared before live interview use.
            </p>
          </form>
        )}

        {step === "qualification" && (
          <form onSubmit={(e) => { e.preventDefault(); onQualificationContinue(); }}>
            <h3 className="v2-modal__title">How often do you run interviews without a second person?</h3>
            <div className="v2-options">
              {V2_CONVERSION_QUALIFICATION_OPTIONS.map((option) => (
                <label key={option} className={`v2-option ${qualification === option ? "is-selected" : ""}`}>
                  <input
                    type="radio"
                    name="qualification"
                    value={option}
                    checked={qualification === option}
                    onChange={() => setQualification(option)}
                    required
                  />
                  <span>{option}</span>
                </label>
              ))}
            </div>
            <button type="submit" className="zn-btn zn-btn--primary zn-btn--lg v2-modal__button">See founding access</button>
          </form>
        )}

        {step === "checkout" && (
          <div>
            <h3 className="v2-modal__title">Reserve founding access for $15.</h3>
            <p className="v2-modal__copy">
              Your answer helps us prioritize the first pilot cohort. If you want to back the product, preorder now and lock the founding price. If we do not ship on time, you get a full refund.
            </p>
            <p className="v2-modal__section-label">What you get</p>
            <ul className="v2-modal__feats">
              <li><Icon name="check" size={14} color="#0E7C3A" /><span><strong>Lifetime founding price,</strong> half the planned launch price.</span></li>
              <li><Icon name="check" size={14} color="#0E7C3A" /><span><strong>First access</strong> when the live interview copilot opens in Q3 2026.</span></li>
              <li><Icon name="check" size={14} color="#0E7C3A" /><span><strong>Direct input</strong> into the first pilot workflow.</span></li>
              <li><Icon name="check" size={14} color="#0E7C3A" /><span><strong>Full refund</strong> if we don’t ship on time.</span></li>
            </ul>
            <V2ConversionPreorderProgress count={preorderCount} />
            <div className="v2-modal-price"><span>$15</span><del>$30</del><span className="v2-modal-price__note">one time</span></div>
            {payError ? <p className="v2-modal__error">{payError}</p> : null}
            <button type="button" onClick={onCheckout} disabled={payLoading} className="zn-btn zn-btn--primary zn-btn--lg v2-modal__button">
              {payLoading ? 'Opening checkout…' : 'Preorder for $15'}
            </button>
            <button type="button" onClick={onClose} className="v2-modal__secondary">Not now, keep me posted</button>
          </div>
        )}

        {step === "listed" && (
          <div>
            <span className="zn-eyebrow zn-eyebrow--soft">You’re on the list</span>
            <h3 className="v2-modal__title">Thanks, you’re following along.</h3>
            <p className="v2-modal__frame">
              We’ll email you at launch and whenever there’s something worth sharing. Changed your mind? You can back Zernote as a founding researcher anytime.
            </p>
            <button type="button" onClick={onClose} className="zn-btn zn-btn--primary zn-btn--lg v2-modal__button">Done</button>
          </div>
        )}

        {step === "success" && (
          <div>
            <span className="zn-eyebrow zn-eyebrow--soft">Founding researcher</span>
            <h3 className="v2-modal__title">You’re in. Welcome aboard.</h3>
            <p className="v2-modal__frame">
              Your pre-order is confirmed and a receipt is on its way to your inbox. Early access opens in Q3 2026, and we’ll send you the data handling terms before you use Zernote in a live interview.
            </p>
            {V2_CONVERSION_ONBOARDING_CALL_URL && !V2_CONVERSION_ONBOARDING_CALL_URL.startsWith('[') ? (
              <a href={V2_CONVERSION_ONBOARDING_CALL_URL} target="_blank" rel="noopener noreferrer" className="zn-btn zn-btn--primary zn-btn--lg v2-modal__button">Book a 15-min onboarding call</a>
            ) : null}
            <button type="button" onClick={onClose} className="v2-modal__secondary">Maybe later</button>
          </div>
        )}
      </div>
    </div>
  );
};

const MascotFeature = ({ mascot, num, title, body }) =>
  <div className="zn-feat zn-feat--mascot">
    <img className="zn-feat__mascot" src={mascot} alt="" />
    <span className="zn-feat__num">{num}</span>
    <h3 className="zn-feat__title">{title}</h3>
    <p className="zn-feat__body">{body}</p>
  </div>;

const TrustRow = ({ icon, title, body }) =>
  <div className="v2-trust-row">
    <span className="v2-trust-row__icon">
      <Icon name={icon} size={20} />
    </span>
    <div>
      <h3>{title}</h3>
      <p>{body}</p>
    </div>
  </div>;

window.V2Conversion = V2Conversion;
window.V2 = V2Conversion;
