// screens-preview.jsx — PreviewScreen + PaidPreviewScreen
//
// PreviewScreen sits between ProcessingScreen and SubmittedScreen. It polls
// dashboard.gravida.nl/api/scan/<sessionId>/preview every 5 seconds while
// the 3D service is generating, then drops in Google's <model-viewer> web component
// once the GLB URL is available, plus a "Reserve €35" CTA that opens a Mollie
// checkout in a browser tab.
//
// PaidPreviewScreen is shown when the Mollie checkout returns successfully
// (the deposit endpoint sets a return URL of /?paid=GRV-XXXX which the app
// detects on load).

const { useState: useP, useEffect: useEP, useRef: useRP } = React;

const PREVIEW_POLL_MS = 5000;
// Deposit and prices come from the partner's settings (brand.js), read at
// render time: the branding may arrive after this file is loaded.
// null = this partner takes no deposit in the app.
function depositEur() { return window.BRAND ? window.BRAND.aanbetaling_eur : 10; }
// Only Gravida mails the credit code from her own webshop; other partners get
// the code here in the app (Mollie Connect, Marit 2026-11-18).
function isGravidaApp() { const p = window.BRAND && window.BRAND.partner; return !p || p.slug === 'gravida'; }
function prijs(k) { const p = window.BRAND && window.BRAND.prijzen; return p ? p[k] : null; }
const TEST_PHASE = false;

// The scan that still waits for the deposit, kept on this phone for a day
// (Marit 2026-11-12). Before, leaving for the payment page and coming back
// with the back button (or closing the app) lost the scan: she could not pay
// or use her code any more. Only the session id is kept, nothing personal.
const OPEN_SCAN_KEY = 'scan-open';
const openScan = {
  bewaar(sessionId) {
    try { localStorage.setItem(OPEN_SCAN_KEY, JSON.stringify({ sessionId, op: Date.now() })); } catch (e) {}
  },
  lees() {
    try {
      const o = JSON.parse(localStorage.getItem(OPEN_SCAN_KEY) || 'null');
      if (!o || !o.sessionId || Date.now() - (o.op || 0) > 24 * 3600 * 1000) return null;
      return o;
    } catch (e) { return null; }
  },
  wis() { try { localStorage.removeItem(OPEN_SCAN_KEY); } catch (e) {} },
};
// Who sends the proposal: the reviewer (Gravida: Marit), else the studio's contact person.
function voorstelVan(standaard) {
  const B = window.BRAND || {};
  return B.beoordelaar || B.contactpersoon || standaard;
}

// Lazy-load Google's model-viewer web component the first time the screen
// mounts. The script tag registers a <model-viewer> custom element globally.
function ensureModelViewerLoaded() {
  if (typeof window === 'undefined') return;
  if (window.__modelViewerLoaded) return;
  const s = document.createElement('script');
  s.type   = 'module';
  s.src    = 'https://unpkg.com/@google/model-viewer@4.0.0/dist/model-viewer.min.js';
  s.async  = true;
  document.head.appendChild(s);
  window.__modelViewerLoaded = true;
}

// A first look at the raw 3D scan (Marit 2026-11-12, Gravida first). GWP
// makes the real model as soon as the photos are in (about 10 minutes) and
// shows it as pictures all around, cropped like the figurine, the same view
// the studio gets. No 3D file leaves GWP. Shows nothing when the studio does
// not do this, or when the model did not work out (the team checks it).
function RuwModel({ sessionId, hoogte = 360 }) {
  const [st, setSt] = useP(null); // { state: 'uit' | 'bezig' | 'klaar' | 'mislukt', beelden?, seconden? }
  useEP(() => {
    if (!sessionId || window.APP_PROEF) return undefined;
    let stop = false;
    let id = null;
    const kijk = async () => {
      try {
        const cfg = window.SCAN_API_CONFIG || {};
        const base = (cfg.base || '').replace(/\/$/, '');
        const res = await fetch(`${base}/api/scan/${encodeURIComponent(sessionId)}/model-voorbeeld`, {
          headers: cfg.token ? { 'X-Scan-App-Token': cfg.token } : {},
        });
        if (!res.ok || stop) return;
        const d = await res.json();
        if (stop) return;
        setSt(d);
        if (d.state !== 'bezig') clearInterval(id);
      } catch (e) { /* try again next time */ }
    };
    kijk();
    id = setInterval(kijk, 15000);
    return () => { stop = true; clearInterval(id); };
  }, [sessionId]);

  if (!st || st.state === 'uit' || st.state === 'mislukt') return null;
  if (st.state === 'bezig') {
    const deel = Math.min(0.95, (st.seconden || 0) / 660);
    return (
      <div className="card" style={{ display: 'flex', gap: 14, alignItems: 'center', textAlign: 'left' }}>
        <div className="center" style={{ width: 46, height: 46, flex: '0 0 auto', borderRadius: 999, background: 'linear-gradient(135deg, var(--gold), var(--rose))', color: '#fff' }}>
          <span style={{ display: 'inline-flex', animation: 'spin360 6s linear infinite' }}><IcSparkle size={22} /></span>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <p style={{ margin: '0 0 3px', fontWeight: 700, fontSize: 14.5, color: 'var(--ink)' }}>Your 3D scan is being made</p>
          <p style={{ margin: 0, fontSize: 12.5, lineHeight: 1.5, color: 'var(--ink-mute)' }}>
            From all your photos, in about 10 minutes. It appears right here.
          </p>
          <div style={{ height: 5, borderRadius: 999, background: 'var(--hairline)', overflow: 'hidden', marginTop: 8 }}>
            <div style={{ width: `${Math.round(deel * 100)}%`, height: '100%', background: 'linear-gradient(90deg, var(--rose), var(--gold))', transition: 'width .8s ease' }} />
          </div>
        </div>
      </div>
    );
  }
  return (
    <div style={{ textAlign: 'left' }}>
      <div style={{
        borderRadius: 14, padding: '12px 14px', marginBottom: 10,
        background: 'color-mix(in oklch, var(--gold), transparent 86%)',
        border: '1px solid color-mix(in oklch, var(--gold), transparent 60%)',
      }}>
        <p style={{ margin: '0 0 4px', fontSize: 13.5, fontWeight: 700, color: 'var(--ink)' }}>A first look at your raw 3D scan</p>
        <p style={{ margin: 0, fontSize: 12.5, lineHeight: 1.5, color: 'var(--ink-soft)' }}>
          Made by AI from your photos. The head is left off, as on your figurine. Hands, face and fine
          details are still rough: we refine every detail by hand before anything is made.
        </p>
      </div>
      <Draaier beelden={st.beelden || []} hoogte={hoogte} />
      <p style={{ textAlign: 'center', fontSize: 12, color: 'var(--ink-mute)', margin: '8px 0 0' }}>Drag to turn it around.</p>
    </div>
  );
}

// Pictures all around (24 positions): turns slowly by itself until touched,
// then by dragging or the arrows. Upright, no zoom.
function Draaier({ beelden, hoogte }) {
  const [i, setI] = useP(0);
  const [zelf, setZelf] = useP(false);
  const sleep = useRP(null);
  const n = beelden.length || 1;
  useEP(() => { beelden.forEach((u) => { const im = new Image(); im.src = u; }); }, [beelden]);
  useEP(() => {
    if (zelf) return undefined;
    const id = setInterval(() => setI((x) => (x + 1) % n), 220);
    return () => clearInterval(id);
  }, [zelf, n]);
  const stap = (d) => { setZelf(true); setI((x) => (x + d + n) % n); };
  const pijl = {
    position: 'absolute', top: '50%', transform: 'translateY(-50%)', width: 38, height: 38, borderRadius: 999,
    border: '1px solid var(--hairline)', background: 'rgba(255,255,255,.85)', fontSize: 20, cursor: 'pointer', color: 'var(--ink)',
  };
  if (!beelden.length) return null;
  return (
    <div style={{ position: 'relative', background: '#f6f5f2', borderRadius: 16, border: '1px solid var(--hairline)', userSelect: 'none', touchAction: 'pan-y' }}
      onPointerDown={(e) => { setZelf(true); sleep.current = { x: e.clientX, i }; e.currentTarget.setPointerCapture && e.currentTarget.setPointerCapture(e.pointerId); }}
      onPointerMove={(e) => { if (!sleep.current) return; const d = Math.round((e.clientX - sleep.current.x) / 14); setI(((sleep.current.i - d) % n + n) % n); }}
      onPointerUp={() => { sleep.current = null; }} onPointerCancel={() => { sleep.current = null; }}>
      <img src={beelden[i]} alt="Your raw 3D scan" draggable={false}
        style={{ width: '100%', height: hoogte, objectFit: 'contain', display: 'block', pointerEvents: 'none' }} />
      <button type="button" aria-label="Turn left" style={{ ...pijl, left: 8 }} onPointerDown={(e) => e.stopPropagation()} onClick={() => stap(-1)}>‹</button>
      <button type="button" aria-label="Turn right" style={{ ...pijl, right: 8 }} onPointerDown={(e) => e.stopPropagation()} onClick={() => stap(1)}>›</button>
    </div>
  );
}

function PreviewScreen({ ctx }) {
  const [reserving, setReserving] = useP(false);
  const [reserveErr, setReserveErr] = useP(null);
  const [notifAsked, setNotifAsked] = useP(false);
  const [codeOpen, setCodeOpen] = useP(false);
  const [codeValue, setCodeValue] = useP('');
  const [codeRedeeming, setCodeRedeeming] = useP(false);
  const [codeErr, setCodeErr] = useP(null);
  const modelViewerRef = useRP(null);

  // The sessionId was stashed by ProcessingScreen on success, on ctx.capture.
  const sessionId = ctx?.capture?.sessionId || null;
  const contact   = ctx?.capture?.contact || {};
  // A discount code lowers the deposit; null = the partner's standard amount.
  const [bedrag, setBedrag] = useP(ctx?.capture?.bedrag ?? null);
  const [codeMelding, setCodeMelding] = useP(null);
  const teBetalen = () => (bedrag != null ? bedrag : depositEur());
  useEP(() => { if (sessionId && !window.APP_PROEF) openScan.bewaar(sessionId); }, [sessionId]);

  // App polls the preview status at the App level (so the poller survives
  // navigation to Atelier when the customer taps "Notify me & keep
  // browsing"). PreviewScreen just reads the latest from ctx.previewState.
  // Without the preview in the app this screen is simply the next step:
  // the editing plan, the deposit and the code field (APP_TOONT_VOORBEELD).
  const toontVoorbeeld = !!window.APP_TOONT_VOORBEELD;
  // The rough preview never blocks this screen (Marit 2026-11-12): the editing
  // plan, the deposit and the code field are always there. The preview is a
  // block on top while it is being made, and quietly disappears if it fails
  // or there is none for this scan.
  const pv = toontVoorbeeld
    ? (ctx?.previewState || { state: sessionId ? 'loading' : 'unavailable' })
    : { state: 'unavailable' };
  const toonBlok = toontVoorbeeld && pv.state !== 'unavailable' && pv.state !== 'failed';
  const pvKlaar  = pv.state === 'ready' && !!pv.glb_url;
  const state = { state: 'ready' };

  useEP(() => { if (toontVoorbeeld) ensureModelViewerLoaded(); }, []);

  // Re-skin the 3D service's neutral GLB with a single bronze PBR material so the
  // preview matches the brand finish (one of Atelier Gravida's signature
  // colour-ways, "Bronze-Look Resin"). The base GLB from the 3D service ships with a
  // light-grey PBR; we wipe every texture and force a warm metallic bronze.
  // Re-runs whenever the GLB URL changes (i.e. a new scan finished).
  useEP(() => {
    const mv = modelViewerRef.current;
    if (!mv) return;
    const applyBronze = () => {
      try {
        const mats = mv.model && mv.model.materials;
        if (!mats || !mats.length) return;
        for (const m of mats) {
          // Warm bronze: brown-gold base, ~90% metallic, semi-polished.
          m.pbrMetallicRoughness.setBaseColorFactor([0.72, 0.50, 0.29, 1.0]);
          m.pbrMetallicRoughness.setMetallicFactor(0.9);
          m.pbrMetallicRoughness.setRoughnessFactor(0.35);
          // Strip every texture so the flat colour wins over the 3D service's neutral
          // bake. Wrapped in try/catch because not every material has every
          // texture slot and model-viewer throws on null setters.
          try { m.pbrMetallicRoughness.baseColorTexture.setTexture(null); } catch {}
          try { m.pbrMetallicRoughness.metallicRoughnessTexture.setTexture(null); } catch {}
          try { m.normalTexture.setTexture(null); } catch {}
          try { m.emissiveTexture.setTexture(null); } catch {}
          try { m.occlusionTexture.setTexture(null); } catch {}
          try { m.setEmissiveFactor([0, 0, 0]); } catch {}
        }
      } catch (err) { console.warn('bronze override failed:', err); }
    };
    mv.addEventListener('load', applyBronze);
    // If a model is already loaded (component re-mount, src unchanged), apply now.
    if (mv.model) applyBronze();
    return () => mv.removeEventListener('load', applyBronze);
  }, [pv.glb_url]);

  // Tap "Notify me & keep browsing": request notification permission (so
  // App can ping when status flips to ready), then navigate to the Atelier
  // collection. The App-level poller keeps running in the background.
  const notifyAndBrowse = async () => {
    if (typeof Notification !== 'undefined' && Notification.permission === 'default') {
      try { await Notification.requestPermission(); } catch (e) {}
    }
    setNotifAsked(true);
    ctx.go('atelier');
  };

  const reserve = async () => {
    if (window.APP_PROEF) { ctx.go('proefEinde'); return; }
    if (!sessionId) return;
    setReserveErr(null); setReserving(true);
    try {
      const cfg = (typeof window !== 'undefined' && window.SCAN_API_CONFIG) || {};
      const base  = (cfg.base  || '').replace(/\/$/, '');
      const token = cfg.token || '';
      const res = await fetch(`${base}/api/scan/${encodeURIComponent(sessionId)}/deposit`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(token ? { 'X-Scan-App-Token': token } : {}),
        },
        body: JSON.stringify({ email: contact.email, first_name: contact.first_name }),
      });
      const data = await res.json();
      if (!res.ok || !data.checkout_url) throw new Error(data.error || 'Could not start payment');
      window.location.href = data.checkout_url;
    } catch (err) {
      setReserveErr((err && err.message) || 'Payment could not start');
      setReserving(false);
    }
  };

  const redeemCode = async () => {
    const code = codeValue.trim().toUpperCase();
    if (!code) { setCodeErr('Please enter a code'); return; }
    if (window.APP_PROEF) { ctx.go('proefEinde'); return; }
    if (!sessionId) return;
    setCodeErr(null); setCodeRedeeming(true);
    try {
      const cfg = (typeof window !== 'undefined' && window.SCAN_API_CONFIG) || {};
      const base  = (cfg.base  || '').replace(/\/$/, '');
      const token = cfg.token || '';
      const res = await fetch(`${base}/api/scan/${encodeURIComponent(sessionId)}/redeem-code`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(token ? { 'X-Scan-App-Token': token } : {}),
        },
        body: JSON.stringify({ code }),
      });
      const data = await res.json().catch(() => ({}));
      if (data.korting && data.aanbetaling_eur != null) {
        // A discount code: she pays the lower amount with the same button.
        setBedrag(data.aanbetaling_eur);
        if (ctx && ctx.capture) ctx.capture.bedrag = data.aanbetaling_eur;
        setCodeOpen(false); setCodeValue(''); setCodeRedeeming(false);
        setCodeMelding(`Code applied. Your editing plan is now €${data.aanbetaling_eur}.`);
        return;
      }
      if (!res.ok) throw new Error(data.error || 'This code could not be redeemed');
      // ok: true or ok: true + already: true — both mean we can continue.
      // A code has no credit code to wait for, so tell the next screen.
      if (ctx && ctx.capture) ctx.capture.viaCode = true;
      openScan.wis();
      ctx.go('paidPreview');
    } catch (err) {
      setCodeErr((err && err.message) || 'This code could not be redeemed');
      setCodeRedeeming(false);
    }
  };

  // state.state === 'ready'
  return (
    <div className="scr scr--paper">
      <TopBar onBack={() => ctx.back()} onHelp={ctx.onHelp} />
      <div style={{ flex: 1, minHeight: 0, overflowY: 'auto' }}>
        <div className="pad" style={{ paddingBottom: 10 }}>
          <span className="eyebrow">Your photos are in</span>
          <h1 className="title" style={{ marginTop: 8 }}>Now we shape your sculpture by hand.</h1>
          <p className="lede" style={{ fontSize: 14.5, marginTop: 10 }}>
            {window.BRAND.team_lidwoord.charAt(0).toUpperCase() + window.BRAND.team_lidwoord.slice(1)} turns your
            photos into a digital model and refines every line by hand. Here is how it works.
          </p>
        </div>

        {sessionId && (
          <div className="pad" style={{ paddingTop: 0, paddingBottom: 12 }}>
            <RuwModel sessionId={sessionId} />
          </div>
        )}

        {toonBlok && !pvKlaar && (
          <div className="pad" style={{ paddingTop: 0, paddingBottom: 12 }}>
            <div className="card" style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
              <div className="center" style={{ width: 46, height: 46, flex: '0 0 auto', borderRadius: 999, background: 'linear-gradient(135deg, var(--gold), var(--rose))', color: '#fff' }}>
                <span style={{ display: 'inline-flex', animation: 'spin360 6s linear infinite' }}><IcSparkle size={22} /></span>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <p style={{ margin: '0 0 3px', fontWeight: 700, fontSize: 14.5, color: 'var(--ink)' }}>A first rough look is on its way</p>
                <p style={{ margin: 0, fontSize: 12.5, lineHeight: 1.5, color: 'var(--ink-mute)' }}>
                  A quick AI sketch from your front photo. It takes about two minutes and shows up right here.
                </p>
                <div style={{ height: 5, borderRadius: 999, background: 'var(--hairline)', overflow: 'hidden', marginTop: 8 }}>
                  <div style={{ width: `${Math.round(Math.min(0.95, (pv.elapsed_seconds || 0) / 150) * 100)}%`, height: '100%', background: 'linear-gradient(90deg, var(--rose), var(--gold))', transition: 'width .8s ease' }} />
                </div>
              </div>
            </div>
          </div>
        )}

        {toonBlok && pvKlaar && (<>
        {/* Disclaimer BEFORE the viewer, so the customer reads it before seeing
            a possibly odd-looking model. Made from the front photo only, so the
            viewer only turns a little to the left and right: the back would be
            made up. */}
        <div className="pad" style={{ paddingTop: 0, paddingBottom: 12 }}>
          <div style={{
            borderRadius: 14, padding: '14px 16px',
            background: 'color-mix(in oklch, var(--gold), transparent 86%)',
            border: '1px solid color-mix(in oklch, var(--gold), transparent 60%)',
            display: 'flex', gap: 11,
          }}>
            <span style={{ color: 'var(--gold-deep, #b08030)', flex: '0 0 auto', marginTop: 2 }}><IcLeaf size={20} /></span>
            <div>
              <p style={{ margin: '0 0 5px', fontSize: 13.5, fontWeight: 700, color: 'var(--ink)' }}>
                A rough first look, not your sculpture.
              </p>
              <p style={{ margin: 0, fontSize: 13, lineHeight: 1.55, color: 'var(--ink-soft)' }}>
                The AI made this quick sketch from your front photo only. The hands are rough,
                the face is not yet recognisable and fine detail is missing. That is normal: our
                sculptors work from all your photos and refine every line by hand.
              </p>
            </div>
          </div>
        </div>

        <div style={{ height: 380, margin: '0 16px', borderRadius: 18, overflow: 'hidden', background: 'radial-gradient(80% 70% at 50% 40%, #f4efe4 0%, #e9e3d6 100%)', border: '1px solid var(--hairline)' }}>
          {React.createElement('model-viewer', {
            ref: modelViewerRef,
            src: pv.glb_url,
            alt: 'A rough first look, in bronze',
            'camera-controls': true,
            // Front view only: a little to the left and right, no tilting,
            // zooming or turning round to the back.
            'camera-orbit': '0deg 85deg auto',
            'min-camera-orbit': '-30deg 85deg auto',
            'max-camera-orbit': '30deg 85deg auto',
            'disable-zoom': true,
            'disable-pan': true,
            'disable-tap': true,
            'shadow-intensity': '1.1',
            'shadow-softness': '0.85',
            'environment-image': 'neutral',
            exposure: '0.95',
            'tone-mapping': 'aces',
            style: { width: '100%', height: '100%', backgroundColor: 'transparent' },
          })}
        </div>
        <p style={{ textAlign: 'center', fontSize: 12, color: 'var(--ink-mute)', margin: '8px 20px 0' }}>
          Rough AI sketch from your front photo. Drag a little to the left or right.
        </p>
        </>)}

        {/* What the customer controls on the final preview. Specifically
            calls out the default smoothing under the belly so they know
            privacy is handled, and that they can override it. */}
        <div className="pad" style={{ paddingTop: 12, paddingBottom: 4 }}>
          <div className="card" style={{ background: 'color-mix(in oklch, var(--rose), transparent 88%)', borderColor: 'color-mix(in oklch, var(--rose), transparent 64%)' }}>
            <div style={{ display: 'flex', gap: 11 }}>
              <span style={{ color: 'var(--rose-deep)', flex: '0 0 auto', marginTop: 1 }}><IcEye size={19} /></span>
              <p style={{ margin: 0, fontSize: 13, lineHeight: 1.5, color: 'var(--ink-soft)' }}>
                <b>You decide what stays and what we soften.</b> By default we gently
                smooth the area below the belly so no intimate detail is shown,
                and any visible cellulite is minimised, unless you tell us
                otherwise.
              </p>
            </div>
          </div>
        </div>

        {/* How digital sculpting works — the 3-step ladder. Each step is its
            own payment in the live version; clearly hand-drawn, up to 14 days.
            The digital model is a standalone product the customer keeps. */}
        {depositEur() != null && (
        <div className="pad" style={{ paddingTop: 12, paddingBottom: 4 }}>
          <div className="card">
            <p style={{ margin: '0 0 4px', fontWeight: 700, fontSize: 15, color: 'var(--ink)' }}>
              How your digital sculpture works
            </p>
            <p style={{ margin: '0 0 14px', fontSize: 12.5, lineHeight: 1.5, color: 'var(--ink-mute)' }}>
              Turning your photos into a refined sculpture is two gentle steps.
            </p>

            {[
              ['1', 'Editing plan', `€${prijs('editing_plan')}`,
               'We review your model in detail: we name what is not quite right and describe exactly what we want to refine by hand. You tell us your own wishes. The raw scan arrives at our atelier in about 15 minutes — you will receive our proposal within 72 hours.'],
              ['2', 'Your digital model', `€${prijs('digitaal_model')}`,
               `Once you approve, our sculptors refine every line by hand. Your model gets a permanent personal page — view it in 360 degrees any time, and order a sculpture whenever you like. (Your €${prijs('editing_plan')} code from step 1 brings this to €${prijs('digitaal_model_met_code')}.)`],
            ].map(([n, title, price, body]) => (
              <div key={n} style={{ display: 'flex', gap: 11, marginBottom: 12 }}>
                <span className="center" style={{
                  width: 24, height: 24, flex: '0 0 auto', borderRadius: 999,
                  background: 'var(--ink)', color: 'var(--paper)', fontSize: 12.5, fontWeight: 700,
                }}>{n}</span>
                <div>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                    <b style={{ fontSize: 13.5, color: 'var(--ink)' }}>{title}</b>
                    <span className="serif-num" style={{ fontSize: 13.5, color: 'var(--gold)' }}>{price}</span>
                  </div>
                  <p style={{ margin: '2px 0 0', fontSize: 12.5, lineHeight: 1.5, color: 'var(--ink-soft)' }}>{body}</p>
                </div>
              </div>
            ))}

            <p style={{ margin: '4px 0 0', fontSize: 12.5, lineHeight: 1.5, color: 'var(--ink-soft)' }}>
              The editing plan is where we make it truly yours. No file download by default; if you want the file
              itself that is €{prijs('bestand_extra')} extra.
            </p>
          </div>
        </div>
        )}
      </div>

      {/* Sticky CTA. During the test phase the button registers interest only
          and never charges. In the live version this is step 1 (€35) of the
          digital sculpting ladder. */}
      <div style={{ flex: '0 0 auto', padding: '12px 20px 14px', borderTop: '1px solid var(--hairline)', background: 'var(--paper)' }}>
        {depositEur() == null ? (
          <>
            <p style={{ margin: '0 0 10px', fontSize: 13, color: 'var(--ink-mute)', textAlign: 'center' }}>
              Your scan is with {window.BRAND.team_lidwoord}. We'll contact you by email about the next step.
            </p>
            <button className="btn btn--accent" onClick={() => ctx.go('submitted')}>
              Done <IcArrow size={18} />
            </button>
          </>
        ) : (
          <>
            <p style={{ margin: '0 0 10px', fontSize: 12.5, color: 'var(--ink-mute)', textAlign: 'center' }}>
              Get your personal editing plan for <b style={{ color: 'var(--ink)' }}>€{teBetalen()}</b>.
              Includes a detailed proposal from {voorstelVan('us')} and a €{depositEur()} credit towards your digital model.
            </p>
            {/* One button at a time (Marit 2026-11-12): with the code field open
                there were two, the right one fell off the screen, and the big
                one started a payment instead of using the code. Now the big
                button uses the code while the field is open. */}
            {codeOpen ? (
              <div style={{ marginBottom: 10 }}>
                <input
                  type="text"
                  placeholder="Your code"
                  autoFocus
                  autoCapitalize="characters"
                  value={codeValue}
                  onChange={(e) => { setCodeValue(e.target.value.toUpperCase()); setCodeErr(null); }}
                  onKeyDown={(e) => e.key === 'Enter' && redeemCode()}
                  style={{
                    width: '100%', boxSizing: 'border-box', padding: '12px 14px', borderRadius: 10,
                    border: `1px solid ${codeErr ? 'var(--rose-deep)' : 'var(--hairline)'}`,
                    fontSize: 16, fontFamily: 'inherit', background: 'var(--paper)', color: 'var(--ink)',
                    outline: 'none', textAlign: 'center', letterSpacing: '.04em',
                  }}
                />
                {codeErr && <p style={{ margin: '6px 0 0', fontSize: 12.5, color: 'var(--rose-deep)', textAlign: 'center' }}>{codeErr}</p>}
              </div>
            ) : (
              <button className="linkbtn" style={{ display: 'block', margin: '0 auto 8px' }} onClick={() => { setCodeOpen(true); setCodeMelding(null); }}>
                Have a code?
              </button>
            )}
            {codeMelding && (
              <p style={{ margin: '0 0 8px', fontSize: 12.5, color: 'var(--ink)', textAlign: 'center', fontWeight: 600 }}>{codeMelding}</p>
            )}
            {reserveErr && (
              <p style={{ margin: '0 0 8px', fontSize: 12.5, color: 'var(--rose-deep)', textAlign: 'center' }}>{reserveErr}</p>
            )}
            {codeOpen ? (
              <>
                <button className="btn btn--accent" disabled={codeRedeeming} onClick={redeemCode}
                  style={codeRedeeming ? { opacity: .6, pointerEvents: 'none' } : null}>
                  {codeRedeeming ? 'Checking your code...' : 'Use this code'}
                  <IcArrow size={18} />
                </button>
                <button className="linkbtn" style={{ display: 'block', margin: '10px auto 0' }}
                  onClick={() => { setCodeOpen(false); setCodeValue(''); setCodeErr(null); }}>
                  No code? Pay €{teBetalen()} instead
                </button>
              </>
            ) : (
              <>
                <button className="btn btn--accent" disabled={reserving}
                  onClick={reserve}
                  style={reserving ? { opacity: .6, pointerEvents: 'none' } : null}>
                  {reserving ? 'Opening checkout...' : `Get your editing plan — €${teBetalen()}`}
                  <IcArrow size={18} />
                </button>
                {heeft('collectie') && (
                  <button className="linkbtn" style={{ display: 'block', margin: '10px auto 0' }} onClick={() => ctx.go('atelier')}>
                    Just browse the Collection first
                  </button>
                )}
              </>
            )}
          </>
        )}
      </div>
    </div>
  );
}

function PaidPreviewScreen({ ctx }) {
  // The app boots into this screen with `?paid=pending&session=<uuid>` when
  // the customer comes back from Mollie. Mollie sends her back whether she
  // paid or not, so nothing says "Confirmed" until the payment is in
  // (Marit 2026-11-12: after stopping on the payment page she saw
  // "Confirmed" and could not pay or use a code any more).
  //   checking  asking the server
  //   paid      paid; the credit code follows (webhook, usually 2-5 s)
  //   done      no payment needed: a code, or the team sent the scan on
  //   failed    cancelled, failed or expired: try again or use a code
  //   late      still not in after ~30 s
  const sessionId = (ctx?.capture?.sessionId) || null;
  const [couponCode, setCouponCode] = useP((ctx?.capture?.couponCode && ctx.capture.couponCode !== 'pending') ? ctx.capture.couponCode : null);
  // Unlocked with a code (tester, invite): no payment, so no credit code to poll for.
  const viaCode = !!(ctx?.capture?.viaCode);
  const [stand, setStand] = useP(viaCode ? 'done' : couponCode ? 'paid' : sessionId ? 'checking' : 'done');
  const [polling, setPolling] = useP(!viaCode && !couponCode && !!sessionId);
  const [timedOut, setTimedOut] = useP(false);

  useEP(() => {
    if (!sessionId || couponCode || viaCode) { if (viaCode || couponCode) openScan.wis(); return; }
    const cfg = (typeof window !== 'undefined' && window.SCAN_API_CONFIG) || {};
    const base  = (cfg.base  || '').replace(/\/$/, '');
    const token = cfg.token || '';
    let tries = 0, gestopt = false, betaald = false;
    const MAX_TRIES = 15;
    const stop = () => { gestopt = true; setPolling(false); clearInterval(id); };
    const kijk = async () => {
      if (gestopt) return;
      tries++;
      try {
        const res = await fetch(`${base}/api/scan/${encodeURIComponent(sessionId)}/deposit/status`, {
          headers: token ? { 'X-Scan-App-Token': token } : {},
        });
        if (res.ok && !gestopt) {
          const data = await res.json();
          if (data.state === 'paid') {
            betaald = true;
            setStand('paid');
            openScan.wis();
            if (data.coupon_code) {
              setCouponCode(data.coupon_code);
              if (ctx && ctx.capture) ctx.capture.couponCode = data.coupon_code;
              stop();
              return;
            }
          } else if (data.waiting === false) {
            setStand('done'); openScan.wis(); stop(); return;
          } else if (data.state === 'failed') {
            setStand('failed'); stop(); return;
          }
        }
      } catch (e) {}
      if (tries >= MAX_TRIES && !gestopt) {
        if (betaald) setTimedOut(true); else setStand('late');
        stop();
      }
    };
    const id = setInterval(kijk, 2000);
    kijk();
    return () => { gestopt = true; clearInterval(id); };
  }, [sessionId]);

  const opnieuw = () => ctx.go('preview');
  const team = window.BRAND.team_lidwoord;

  if (stand === 'checking' || stand === 'failed' || stand === 'late') {
    return (
      <div className="scr scr--light">
        <TopBar onHelp={ctx.onHelp} />
        <div className="pad flex1 col" style={{ justifyContent: 'space-between' }}>
          <div className="grow center col" style={{ textAlign: 'center' }}>
            {stand === 'checking' ? (
              <>
                <div style={{ width: 44, height: 44, borderRadius: 999, border: '3px solid var(--gold)', borderTopColor: 'transparent', animation: 'spin360 .8s linear infinite', marginBottom: 22 }} />
                <span className="eyebrow">One moment</span>
                <h1 className="display display--sm" style={{ marginTop: 10 }}>Checking your payment.</h1>
              </>
            ) : (
              <>
                <div className="center" style={{ width: 76, height: 76, borderRadius: 999, background: 'color-mix(in oklch, var(--rose), transparent 85%)', color: 'var(--rose-deep)', marginBottom: 22 }}>
                  <IcRetake size={32} />
                </div>
                <span className="eyebrow">{stand === 'failed' ? 'Not paid' : 'Not in yet'}</span>
                <h1 className="display display--sm" style={{ marginTop: 10 }}>
                  {stand === 'failed' ? 'Your payment did not go through.' : 'We have not received your payment yet.'}
                </h1>
                <p className="lede" style={{ marginTop: 12, maxWidth: 320 }}>
                  {stand === 'failed'
                    ? `Nothing was charged. Your photos are safe with ${team}. You can try again, or use a code if you have one.`
                    : (isGravidaApp()
                      ? `If you paid, you will receive an email with your credit code within a few minutes. If you stopped halfway, you can try again or use a code. Your photos are safe with ${team}.`
                      : `If you paid, it can take a minute to come through. If you stopped halfway, you can try again or use a code. Your photos are safe with ${team}.`)}
                </p>
              </>
            )}
          </div>
          {stand !== 'checking' && (
            <button className="btn btn--accent" onClick={opnieuw}>
              Back to payment or code <IcArrow size={18} />
            </button>
          )}
        </div>
      </div>
    );
  }

  return (
    <div className="scr scr--light">
      <TopBar onHelp={ctx.onHelp} />
      <div className="pad flex1 col" style={{ justifyContent: 'space-between', overflowY: 'auto', minHeight: 0 }}>
        <div className="grow center col" style={{ textAlign: 'center' }}>
          <div className="center" style={{ width: 76, height: 76, borderRadius: 999, background: 'var(--ink)', color: 'var(--rose)', marginBottom: 22 }}>
            <IcCheck size={40} />
          </div>
          <span className="eyebrow">Confirmed</span>
          <h1 className="display display--sm" style={{ marginTop: 10 }}>Your editing plan is on its way.</h1>
          <p className="lede" style={{ marginTop: 12, maxWidth: 320 }}>
            Thank you. The raw scan arrives at our atelier in about 15 minutes.
            {' '}{voorstelVan('We')} will review your model and send you our proposal within 72 hours.
          </p>

          {couponCode && (
            <div className="card" style={{ marginTop: 20, padding: 16, background: 'var(--paper)' }}>
              <p style={{ margin: 0, fontSize: 11.5, fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--gold)' }}>
                Your €{depositEur()} credit code
              </p>
              <p style={{ margin: '8px 0 0', fontFamily: 'ui-monospace, Menlo, monospace', fontSize: 22, fontWeight: 700, color: 'var(--ink)', letterSpacing: '.04em' }}>
                {couponCode}
              </p>
              <p style={{ margin: '8px 0 0', fontSize: 12.5, color: 'var(--ink-mute)' }}>
                {isGravidaApp()
                  ? <>Also sent to your email. Use it when you order your digital model — brings the price from €{prijs('digitaal_model')} to €{prijs('digitaal_model_met_code')}.</>
                  : <>Keep this code and mention it when you order from {window.BRAND.merknaam || 'us'}.</>}
              </p>
            </div>
          )}
          {stand === 'paid' && !couponCode && polling && (
            <div className="card" style={{ marginTop: 20, padding: 14, background: 'var(--paper)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, justifyContent: 'center' }}>
                <div style={{ width: 14, height: 14, borderRadius: 999, border: '2px solid var(--gold)', borderTopColor: 'transparent', animation: 'spin360 .8s linear infinite' }} />
                <p style={{ margin: 0, fontSize: 13, color: 'var(--ink-mute)' }}>Generating your credit code...</p>
              </div>
            </div>
          )}
          {stand === 'paid' && !couponCode && timedOut && (
            <div className="card" style={{ marginTop: 20, padding: 14, background: 'var(--paper)' }}>
              <p style={{ margin: 0, fontSize: 13, color: 'var(--ink-mute)', textAlign: 'center' }}>
                {isGravidaApp() ? 'Your credit code is on its way by email within a few minutes.' : 'Your payment is received.'}
              </p>
            </div>
          )}

          <p style={{ marginTop: 22, fontSize: 13, color: 'var(--ink-mute)' }}>
            {voorstelVan('We')} will email you within 72 hours with our full proposal.
          </p>

          {sessionId && (
            <div style={{ width: '100%', marginTop: 18 }}>
              <RuwModel sessionId={sessionId} hoogte={300} />
            </div>
          )}
        </div>
        <button className="btn btn--accent" onClick={() => ctx.go('atelier')}>
          See materials &amp; finishes <IcArrow size={18} />
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { PreviewScreen, PaidPreviewScreen, openScan });
