// Pricing page for bileksamen.no — checkout funnel
const { useState, useEffect, useRef } = React;

// ---- Config ----
const ENABLE_VIPPS = false; // flip when Vipps eHandel approval lands
const SUPABASE_URL = 'https://eqihrzxhrrqqpfgteqye.supabase.co';
const STRIPE_CHECKOUT_FN = `${SUPABASE_URL}/functions/v1/stripe-checkout`;
const CAPTURE_EMAIL_FN = `${SUPABASE_URL}/functions/v1/capture-email`;
const BASE_URL = window.location.origin;
const PLAN_SLUG = 'klasse-b';
const CURRENCY = 'NOK';

// Bil tiers — id is plan_tiers.slug; backend resolves stripe_price_id from
// (planSlug, tierSlug). Prices come from window.PRICES (shared/prices.js,
// loaded synchronously by Priser before this file). Stripe price IDs
// live in supabase/migrations/20260515000000_seed_stripe_price_ids_live.sql.
const TIERS = [
  {
    id: '3d', label: 'Sprint', days: 3, price: window.PRICES['klasse-b']['3d'],
    tagline: 'Du har prøven snart og trenger en rask intensivkur.',
    features: [
      'Full tilgang i 72 timer',
      '1 600+ spørsmål Klasse B',
      'Alle skilt og forklaringer',
      'Ubegrenset prøveeksamen',
      'Tilgang på mobil og web',
    ],
  },
  {
    id: '14d', label: 'Standard', days: 14, price: window.PRICES['klasse-b']['14d'], popular: true,
    tagline: 'Den anbefalte ruten — nok tid til å virkelig forstå stoffet.',
    features: [
      'Full tilgang i 14 dager',
      'Adaptiv læringsplan',
      'Daglige fremgangsrapporter',
      'Personlig svake-områder-fokus',
      'Prioritert kundestøtte på chat',
    ],
  },
  {
    id: '30d', label: 'Trygg', days: 30, price: window.PRICES['klasse-b']['30d'],
    tagline: 'Rolig tempo — for deg som vil ta tiden i bruk.',
    features: [
      'Full tilgang i 30 dager',
      'Alt i Standard-planen',
      'Pause-funksjon (frys i 14 dg)',
      'Førstehjelp-modul inkludert',
      'Eksport av notater til PDF',
      'Bestå-garanti eller pengene tilbake',
    ],
  },
];

// ---- Inline icons (kept lightweight to avoid pulling all of icons.jsx) ----
function IconCheck({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
         strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M20 6 9 17l-5-5" />
    </svg>
  );
}
function IconLock({ size = 13 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
         strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="11" width="18" height="11" rx="2" />
      <path d="M7 11V7a5 5 0 0 1 10 0v4" />
    </svg>
  );
}
function IconShield({ size = 13 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
         strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 2 4 5v7c0 5 3.5 8.5 8 10 4.5-1.5 8-5 8-10V5l-8-3z" />
      <path d="m9 12 2 2 4-4" />
    </svg>
  );
}
function IconPhone({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
         strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="5" y="2" width="14" height="20" rx="2.5" />
      <path d="M11 18h2" />
    </svg>
  );
}

function PriserCarLogo({ size = 28 }) {
  const w = size * 1.15, h = size;
  return (
    <svg width={w} height={h} viewBox="0 0 46 40" aria-hidden="true">
      <rect x="1" y="1" width="44" height="38" rx="9" fill="var(--ink)" />
      <g transform="translate(4 10)">
        <path d="M2 14 L2 11 C2 10 3 9 4 9 L9 9 L13 3 C14 1.5 15.5 1 17 1 L26 1 C27.5 1 29 1.5 30.5 3 L34 9 L36 9 C37 9 38 10 38 11 L38 14 Z" fill="var(--bg)" />
        <path d="M14 4 L17 8.2 L23 8.2 L23 3.2 L17.8 3.2 C16.6 3.2 15.7 3.4 14.9 4 Z M24.5 3.2 L24.5 8.2 L32 8.2 L29.4 4.6 C28.6 3.6 27.7 3.2 26.5 3.2 Z" fill="var(--ink)" />
        <circle cx="36" cy="11.5" r="1.5" fill="var(--accent)" />
        <rect x="34" y="13" width="4" height="1" rx="0.5" fill="var(--muted-2)" opacity="0.45" />
        <circle cx="9" cy="14" r="3.4" fill="var(--ink)" stroke="var(--bg)" strokeWidth="1.4" />
        <circle cx="9" cy="14" r="1" fill="var(--bg)" />
        <circle cx="29" cy="14" r="3.4" fill="var(--ink)" stroke="var(--bg)" strokeWidth="1.4" />
        <circle cx="29" cy="14" r="1" fill="var(--bg)" />
      </g>
    </svg>
  );
}

// ---- DataLayer helper (GTM-friendly) ----
function pushDataLayer(event, payload = {}) {
  if (typeof window === 'undefined') return;
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({ event, ...payload });
}

// ---- Attribution capture ----
// First-touch UTM + landing page + referrer, captured once per tab session
// and forwarded through Stripe checkout metadata so the webhook can persist
// it to the user row. Strips the query string off landing_page to avoid
// leaking PII (e.g. session_id) into the stored URL.
// Fire-and-forget: store a valid email the moment it's entered (blur), even if
// the visitor never proceeds to payment. Store-only — no email is ever sent to
// these captures. Guarded so a given address posts at most once per page load.
let _capturedEmail = null;
function captureEmailLead(email, planSlug, tierSlug, attribution) {
  if (!/^\S+@\S+\.\S+$/.test(email || '')) return;
  const clean = email.toLowerCase().trim();
  if (clean === _capturedEmail) return;
  _capturedEmail = clean;
  try {
    fetch(CAPTURE_EMAIL_FN, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email: clean, planSlug, tierSlug, attribution }),
      keepalive: true,
    }).catch(() => {});
  } catch (_) { /* ignore */ }
}

function captureAttribution() {
  if (typeof window === 'undefined') return {};
  const STORAGE_KEY = 'th_attr_v1';
  try {
    const existing = sessionStorage.getItem(STORAGE_KEY);
    if (existing) return JSON.parse(existing);
  } catch (_) {}
  const params = new URLSearchParams(window.location.search);
  const attr = {
    utm_source:   params.get('utm_source')   || null,
    utm_medium:   params.get('utm_medium')   || null,
    utm_campaign: params.get('utm_campaign') || null,
    utm_term:     params.get('utm_term')     || null,
    utm_content:  params.get('utm_content')  || null,
    landing_page: window.location.href.split('?')[0],
    referrer:     document.referrer || null,
  };
  try { sessionStorage.setItem(STORAGE_KEY, JSON.stringify(attr)); } catch (_) {}
  return attr;
}

function tierToItem(t) {
  return {
    item_id: `${PLAN_SLUG}_${t.id}`,
    item_name: `${t.label} · ${t.days} dager`,
    item_category: PLAN_SLUG,
    price: t.price,
    quantity: 1,
  };
}

// ---- Header ----
function PriserNav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <header className={"bt-subnav " + (scrolled ? 'scrolled' : '')}>
      <div className="bt-subnav-inner">
        <a href="index.html" className="bt-logo" aria-label="Bileksamen forside">
          <span className="bt-logo-mark" aria-hidden="true"><PriserCarLogo size={28} /></span>
          <span className="bt-logo-word">Bileksamen</span>
          <span className="bt-logo-tag">.no</span>
        </a>
        <div className="row gap-2">
          <a href="index.html" className="btn btn-ghost btn-sm">← Tilbake</a>
        </div>
      </div>
    </header>
  );
}

// ---- Tier cards ----
function TierCards({ selectedId, onSelect }) {
  return (
    <div className="pr-tiers" role="radiogroup" aria-label="Velg plan">
      {TIERS.map(t => {
        const isSel = t.id === selectedId;
        return (
          <button
            key={t.id}
            type="button"
            role="radio"
            aria-checked={isSel}
            className={"pr-tier " + (isSel ? 'pr-tier--selected ' : '') + (t.popular ? 'pr-tier--popular' : '')}
            onClick={() => onSelect(t.id)}
          >
            {t.popular && <span className="pr-tier-ribbon">Mest valgt</span>}
            <div className="pr-tier-head">
              <span className="pr-tier-meta">{t.days} dager · {t.label}</span>
              <span className="pr-tier-radio" aria-hidden="true">
                {isSel && <IconCheck size={14} />}
              </span>
            </div>
            <div className="pr-tier-price">
              <span className="pr-tier-amount">{t.price}</span>
              <span className="pr-tier-currency">kr</span>
            </div>
            <div style={{ fontSize: '12px', color: 'var(--ink-3)', marginTop: '-4px', marginBottom: '10px', letterSpacing: '0.01em' }}>Inkl. mva.</div>
            <p className="pr-tier-tagline">{t.tagline}</p>
            <ul className="pr-tier-features">
              {t.features.map((f, i) => (
                <li key={i}><IconCheck size={14} /> {f}</li>
              ))}
            </ul>
          </button>
        );
      })}
    </div>
  );
}

// ---- Checkout panel ----
function CheckoutPanel({ tier, email, setEmail, onPay, loading, error }) {
  const emailValid = /^\S+@\S+\.\S+$/.test(email);
  const canPay = emailValid && !loading;
  return (
    <div className="pr-checkout" id="checkout">
      <div className="pr-checkout-summary">
        <span className="pr-checkout-label">Du betaler for</span>
        <div className="pr-checkout-row">
          <strong>bileksamen.no · {tier.days} dager — {tier.label}</strong>
          <span className="pr-checkout-amount">{tier.price} kr</span>
        </div>
        <span className="pr-checkout-sub">Engangsbeløp. Ingen abonnement. Tilgang umiddelbart.</span>
      </div>

      <div style={{margin:'0 0 14px', padding:'11px 13px', borderRadius:10, background:'rgba(0,0,0,0.035)', border:'1px solid rgba(0,0,0,0.09)', fontSize:12.5, lineHeight:1.5}}>
        <strong>📱 Mobilappen kommer snart — øv i nettleseren i dag.</strong>{' '}
        <span style={{color:'var(--muted)'}}>Kjøpet gir deg full tilgang på web med én gang. Når iOS- og Android-appen lanseres, logger du inn med samme konto og har tilgangen der også — uten ekstra kostnad.</span>
      </div>

      <label className="pr-field">
        <span className="pr-field-label">E-post</span>
        <input
          type="email"
          autoComplete="email"
          inputMode="email"
          placeholder="navn@eksempel.no"
          value={email}
          onChange={e => setEmail(e.target.value)}
          onBlur={() => captureEmailLead(email, PLAN_SLUG, tier.id, captureAttribution())}
          className="pr-field-input"
        />
        <span className="pr-field-hint">Vi sender innloggingslenke og kvittering hit.</span>
      </label>

      {error && <div className="pr-error">{error}</div>}

      <div className="pr-pay-row">
        {ENABLE_VIPPS && (
          <button type="button" className="btn btn-primary btn-lg" onClick={onPay} disabled={!canPay}>
            Betal med Vipps
          </button>
        )}
        <button
          type="button"
          className="btn btn-accent btn-lg"
          onClick={onPay}
          disabled={!canPay}
        >
          {loading ? 'Sender til betaling…' : <>Betal med kort <span className="arrow">→</span></>}
        </button>
      </div>

      <div className="pr-checkout-trust">
        <span><IconLock size={13} /> Sikker betaling via Stripe</span>
        <span><IconShield size={13} /> Bestå-garanti inkludert</span>
      </div>
      <div style={{marginTop:10, fontSize:12, lineHeight:1.5, color:'var(--muted)', textAlign:'center'}}>
        Ved å gå videre godtar du <a href="Vilkar" style={{color:'inherit', textDecoration:'underline'}}>Vilkår</a> og <a href="Personvern" style={{color:'inherit', textDecoration:'underline'}}>Personvern</a>.
      </div>
    </div>
  );
}

// ---- Mobile-only summary bar ----
function MobileSummaryBar({ tier, visible }) {
  return (
    <div className={"pr-stickybar " + (visible ? 'is-visible' : '')} aria-hidden={!visible}>
      <div className="pr-stickybar-inner">
        <div className="pr-stickybar-meta">
          <span className="pr-stickybar-label">{tier.days} dager · {tier.label}</span>
          <span className="pr-stickybar-amount">{tier.price} kr</span>
        </div>
        <a href="#checkout" className="btn btn-accent btn-sm">Betal →</a>
      </div>
    </div>
  );
}

// ---- Trust band ----
function PriserTrust() {
  return (
    <div className="pr-trustband">
      <div className="pr-trust-chip"><IconShield size={14} /> Bestå-garanti</div>
      <div className="pr-trust-chip"><IconCheck size={14} /> Engangsbeløp — ikke abonnement</div>
      <div className="pr-trust-chip"><IconPhone size={14} /> Norsk support</div>
      <a href="Sample" className="pr-trust-sample">Prøv en spørsmålsrunde →</a>
    </div>
  );
}

// ---- Mini-FAQ ----
function PriserFAQ() {
  const items = [
    { q: 'Hva dekker bestå-garantien?', a: 'Hvis du gjennomfører det anbefalte opplegget i appen og likevel stryker på teoriprøven på første forsøk, refunderer vi hele beløpet. Du sender oss kvittering på prøveresultatet — så ordner vi resten.' },
    { q: 'Hvordan får jeg tilgang etter betaling?', a: 'Du sendes til en kvitteringsside og får en innloggingslenke på e-post umiddelbart. Klikk lenken og du er inne i appen.' },
    { q: 'Kan jeg bytte plan etterpå?', a: 'Ja. Trenger du mer tid, kan du oppgradere til en lengre plan. Kontakt support og vi ordner mellomlegget.' },
  ];
  const [open, setOpen] = useState(0);
  return (
    <div className="pr-faq">
      <span className="eyebrow">Spørsmål om betaling</span>
      <div className="faq-list" style={{marginTop: 14}}>
        {items.map((it, i) => (
          <div className={"faq-item " + (open === i ? 'open' : '')} key={i}>
            <button type="button" className="faq-q" onClick={() => setOpen(open === i ? -1 : i)} aria-expanded={open === i}>
              <span>{it.q}</span>
              <span className="faq-icon" aria-hidden="true">+</span>
            </button>
            <div className="faq-a"><div className="faq-a-inner">{it.a}</div></div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---- Footer ----
function PriserFooter() {
  return (
    <footer className="bt-subfoot">
      <div className="container bt-subfoot-row">
        <span>© 2026 bileksamen.no — Made in Norway</span>
        <span className="bt-subfoot-links">
          <a href="index.html">Forside</a>
          <a href="Sample">Prøv quiz</a>
          <a href="Vilkar">Vilkår</a>
          <a href="Personvern">Personvern</a>
          <button type="button" className="footer-col-btn" onClick={() => window.openConsentPreferences && window.openConsentPreferences()}>Endre samtykke</button>
          <span>Made in Norway</span>
        </span>
      </div>
    </footer>
  );
}

// ---- App root ----
function PriserApp() {
  const params = new URLSearchParams(window.location.search);
  const fromParam = params.get('plan');
  const initialId =
    (fromParam && TIERS.some(t => t.id === fromParam)) ? fromParam :
    (TIERS.find(t => t.popular)?.id) || TIERS[0].id;

  const [selectedId, setSelectedId] = useState(initialId);
  const [email, setEmail] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [stickyVisible, setStickyVisible] = useState(false);

  const tier = TIERS.find(t => t.id === selectedId) || TIERS[0];
  const tiersSentinelRef = useRef(null);

  // Fire view_item_list on mount
  useEffect(() => {
    pushDataLayer('view_item_list', {
      ecommerce: {
        item_list_name: `${PLAN_SLUG}_pricing`,
        items: TIERS.map(tierToItem),
      },
    });
  }, []);

  // Show mobile sticky bar once tier cards scroll out of view
  useEffect(() => {
    if (!tiersSentinelRef.current) return;
    const observer = new IntersectionObserver(
      ([entry]) => setStickyVisible(!entry.isIntersecting),
      { rootMargin: '0px 0px -40% 0px' },
    );
    observer.observe(tiersSentinelRef.current);
    return () => observer.disconnect();
  }, []);

  const handleSelect = (id) => {
    if (id === selectedId) return;
    setSelectedId(id);
    setError(null);
    const t = TIERS.find(x => x.id === id);
    pushDataLayer('select_item', {
      ecommerce: {
        item_list_name: `${PLAN_SLUG}_pricing`,
        items: [tierToItem(t)],
      },
    });
  };

  const handlePay = async () => {
    setError(null);
    if (!/^\S+@\S+\.\S+$/.test(email)) {
      setError('Skriv inn en gyldig e-postadresse.');
      return;
    }

    pushDataLayer('begin_checkout', {
      ecommerce: {
        currency: CURRENCY,
        value: tier.price,
        items: [tierToItem(tier)],
      },
    });

    setLoading(true);
    try {
      const response = await fetch(STRIPE_CHECKOUT_FN, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          planSlug: PLAN_SLUG,
          tierSlug: tier.id,
          customer_email: email,
          attribution: captureAttribution(),
          success_url: `${BASE_URL}/Takk?session_id={CHECKOUT_SESSION_ID}&plan=${tier.id}`,
          cancel_url: `${BASE_URL}/Priser?retry=1&plan=${tier.id}`,
        }),
      });
      const data = await response.json();
      if (!response.ok || !data.url) {
        throw new Error(data.error || 'Kunne ikke starte betaling. Prøv igjen.');
      }
      window.location.href = data.url;
    } catch (e) {
      console.error('Checkout error', e);
      setError(e.message || 'Noe gikk galt. Prøv igjen.');
      setLoading(false);
    }
  };

  return (
    <>
      <PriserNav />
      <main>
        <section className="pr-section pr-section--hero">
          <div className="container">
            <div className="pr-hero">
              <span className="eyebrow"><span className="dot" />PRIS · KLASSE B</span>
              <h1>Velg perioden som passer prøvedatoen din.</h1>
              <p className="lead">Engangsbeløp. Ingen abonnement. Bestå-garanti inkludert.</p>
            </div>
          </div>
        </section>

        <section className="pr-section">
          <div className="container">
            <TierCards selectedId={selectedId} onSelect={handleSelect} />
            <div ref={tiersSentinelRef} className="pr-tiers-sentinel" aria-hidden="true" />
          </div>
        </section>

        <section className="pr-section">
          <div className="pr-narrow">
            <CheckoutPanel
              tier={tier}
              email={email}
              setEmail={setEmail}
              onPay={handlePay}
              loading={loading}
              error={error}
            />
          </div>
        </section>

        <section className="pr-section">
          <div className="pr-narrow">
            <PriserTrust />
          </div>
        </section>

        <section className="pr-section pr-section--faq">
          <div className="pr-narrow">
            <PriserFAQ />
          </div>
        </section>
      </main>
      <MobileSummaryBar tier={tier} visible={stickyVisible} />
      <PriserFooter />
    </>
  );
}

window.PriserApp = PriserApp;
