// app.jsx — flow controller for Gravida Scan (Atelier AI tier)
// Production version: no Android device frame, no tweaks panel. Renders full viewport.

const { useState: useApp, useEffect: useAppE } = React;

const SCREENS = {
  welcome:      { C: 'WelcomeScreen',      dark: false },
  choose:       { C: 'ChooseScreen',       dark: false },
  privacy:      { C: 'PrivacyScreen',      dark: false },
  setup:        { C: 'SetupScreen',        dark: false },
  overview:     { C: 'OverviewScreen',     dark: false },
  capture:      { C: 'CaptureScreen',      dark: true  },
  details:      { C: 'DetailsScreen',      dark: false },
  processing:   { C: 'ProcessingScreen',   dark: false },
  preview:      { C: 'PreviewScreen',      dark: false },
  paidPreview:  { C: 'PaidPreviewScreen',  dark: false },
  submitted:    { C: 'SubmittedScreen',    dark: false },
  atelier:      { C: 'AtelierScreen',      dark: false },
  poses:        { C: 'PosesScreen',        dark: false },
  bts:          { C: 'BTSScreen',          dark: false },
  proefEinde:   { C: 'ProefEindeScreen',   dark: false },
};

// Preview from the GWP customer portal (window.APP_PROEF): the studio sees its
// own app and nothing is ever sent. Inside the portal (an embedded frame) the
// camera cannot run, so the preview stops before it. Opened on a phone the
// whole app works, camera included; sending is only simulated (Marit
// 2026-11-12) and the photos stay on the phone.
window.APP_INGEBED = (function () { try { return window.self !== window.top; } catch (e) { return true; } })();

function ProefEindeScreen({ ctx }) {
  const ingebed = window.APP_INGEBED;
  return (
    <div className="scr scr--paper">
      <div className="pad flex1 col" style={{ justifyContent: 'center', textAlign: 'center' }}>
        <span className="eyebrow">Preview</span>
        <h1 className="title" style={{ marginTop: 10 }}>
          {ingebed ? 'Try the whole app on your phone.' : 'This is where your customers send their scan.'}
        </h1>
        <p className="lede" style={{ marginTop: 12 }}>
          {ingebed
            ? 'In this window the camera stays off. Scan the QR code next to the phone to try the camera and the rest of the app. Nothing is sent.'
            : 'In the real app your customer pays the deposit here if you set one, and her photos go privately to our atelier, who turns them into a refined sculpture. In this preview the photos stay on this phone and nothing is sent.'}
        </p>
        <button className="btn btn--primary" style={{ marginTop: 24 }} onClick={() => ctx.go('welcome')}>
          Back to the start
        </button>
      </div>
    </div>
  );
}
Object.assign(window, { ProefEindeScreen });

// Fixed brand defaults, chosen from the design hand-off (silhouette guide, warm voice,
// rose accent, help affordance prominent on most screens).
// Screens a partner can switch off (Gravida's own collection, poses, behind
// the scenes, DIY scan-kit choice). Navigation to a switched-off screen goes
// to the sensible next step instead.
function heeft(scherm) {
  const s = window.BRAND && window.BRAND.schermen;
  return !s || s[scherm] !== false;
}
function schermVoorPartner(s) {
  if (s === 'choose' && !heeft('diy_keuze')) return 'privacy';
  if (s === 'atelier' && !heeft('collectie')) return 'submitted';
  if (s === 'poses' && !heeft('poses')) return 'welcome';
  if (s === 'bts' && !heeft('achter_de_schermen')) return 'welcome';
  return s;
}
Object.assign(window, { heeft });

const CTX_DEFAULTS = {
  framing: 'silhouette',
  tone:    'warm',
  help:    6,
};

// Contact channels of the partner (brand.js): Gravida = Laila's WhatsApp, the
// same number as in the transactional email footer. A partner without
// WhatsApp gets email instead.
function waNummer() { return (window.BRAND && window.BRAND.contact && window.BRAND.contact.whatsapp_nummer) || ''; }

function waLink(text) {
  // wa.me prefilled-message URL. Encoding is per WhatsApp's spec.
  return `https://wa.me/${waNummer()}?text=${encodeURIComponent(text)}`;
}

function mailLink(subject, text) {
  const email = (window.BRAND && window.BRAND.contact && window.BRAND.contact.email) || '';
  return `mailto:${email}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(text)}`;
}

function HelpSheet({ open, onClose, sessionId }) {
  if (!open) return null;
  // Every prefilled WhatsApp message ends with an Atelier-side footer so
  // Laila instantly sees this came from the Gravida Scan app, and includes
  // a short scan reference (first 8 chars of the session UUID) so she can
  // look the scan up in /admin/ai-beoordeling without asking the customer.
  const B = window.BRAND;
  const ref = sessionId ? sessionId.replace(/-/g, '').slice(0, 8) : null;
  const sourceLine = ref
    ? `\n\n— sent from ${B.app_naam} · ref ${ref}`
    : `\n\n— sent from ${B.app_naam}`;
  const wie = B.contactpersoon || B.merknaam;

  // All three rows resolve to a WhatsApp conversation with Laila, but each
  // pre-fills a different opening message so she has context the moment she
  // sees it. This is intentionally not three separate channels: keeping the
  // customer in WhatsApp is the simplest way to start a real conversation.
  const opts = waNummer() ? [
    {
      icon:  <IcChat size={20} />,
      title: `Chat with ${B.team_lidwoord}`,
      sub:   B.contactpersoon ? `${B.contactpersoon} usually replies in minutes` : 'We usually reply quickly',
      href:  waLink(`Hi ${wie}, I have a question about the ${B.app_naam} app.${sourceLine}`),
    },
    {
      icon:  <IcPhone size={20} />,
      title: `WhatsApp ${B.contact.whatsapp_weergave || ''}`,
      sub:   B.contactpersoon ? `Send a photo of your setup, ${B.contactpersoon} will guide you` : "Send a photo of your setup, we'll guide you",
      href:  ref
        ? waLink(`Hi ${wie},${sourceLine}`)
        : `https://wa.me/${waNummer()}`,
    },
    {
      icon:  <IcRing size={20} />,
      title: 'Plan a video call',
      // Home visits are Gravida's; another studio only offers the call.
      sub:   (B.partner && B.partner.slug) === 'gravida' ? 'A calm walk-through, or a home visit if needed' : 'A calm walk-through of your scan',
      href:  waLink(`Hi ${wie}, I'd love to plan a video call about my scan.${sourceLine}`),
    },
  ] : [
    {
      icon:  <IcChat size={20} />,
      title: `Email ${B.team_lidwoord}`,
      sub:   B.contact.email || '',
      href:  mailLink(`Question about the ${B.app_naam} app`, `Hi ${wie},${sourceLine}`),
    },
  ];
  const openHref = (href) => {
    // window.open in TWA + iOS Safari opens the WhatsApp app directly when
    // the user has it installed (wa.me handles the deep-link).
    try { window.open(href, '_blank', 'noopener'); } catch (e) {}
    onClose();
  };
  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 40, background: 'rgba(11,12,8,.5)', backdropFilter: 'blur(3px)', display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
      <div onClick={(e) => e.stopPropagation()} className="fadein" style={{ background: 'var(--paper)', borderRadius: '26px 26px 0 0', padding: 22, color: 'var(--ink)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <span className="eyebrow">We're here</span>
            <h3 className="title" style={{ fontSize: 22, marginTop: 6 }}>Talk to {window.BRAND.merknaam}</h3>
          </div>
          <button onClick={onClose} aria-label="Close" style={{ background: 'var(--paper-2)', border: '1px solid var(--hairline)', borderRadius: 999, width: 38, height: 38, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: 'var(--ink)' }}>
            <IcX size={18} />
          </button>
        </div>
        <div style={{ marginTop: 14 }}>
          {opts.map((o, i) => (
            <button key={i} onClick={() => openHref(o.href)} style={{
              width: '100%', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 14,
              padding: '14px 0', borderTop: i ? '1px solid var(--hairline)' : 'none',
              border: 'none', borderRadius: 0, background: 'transparent', cursor: 'pointer',
              fontFamily: 'inherit', color: 'inherit',
            }}>
              <div className="center" style={{ width: 44, height: 44, borderRadius: 999, flex: '0 0 auto', background: 'color-mix(in oklch, var(--rose), transparent 84%)', color: 'var(--rose-deep)' }}>{o.icon}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 700, fontSize: 15 }}>{o.title}</div>
                <div style={{ fontSize: 13, color: 'var(--ink-mute)' }}>{o.sub}</div>
              </div>
              <IcArrow size={18} />
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// Phone-shaped frame for desktop / tablet preview. On a real phone the viewport already
// matches, so we fill the screen edge-to-edge instead.
function Stage({ children, dark }) {
  const [shape, setShape] = useApp(() => computeShape());
  function computeShape() {
    const vw = window.innerWidth;
    const vh = window.innerHeight;
    const isPhone = vw <= 480;
    if (isPhone) {
      return { width: vw, height: vh, scale: 1, frame: false };
    }
    // Desktop / tablet: show the design at its 412x892 reference, scaled to fit.
    const s = Math.min((vw - 32) / 412, (vh - 32) / 892, 1);
    return { width: 412, height: 892, scale: s, frame: true };
  }
  useAppE(() => {
    const fit = () => setShape(computeShape());
    window.addEventListener('resize', fit);
    return () => window.removeEventListener('resize', fit);
  }, []);

  if (!shape.frame) {
    return (
      <div style={{ width: '100vw', height: '100vh', overflow: 'hidden', background: dark ? 'var(--dark)' : 'var(--beige)' }}>
        {children}
      </div>
    );
  }
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: '100vw', height: '100vh', overflow: 'hidden' }}>
      <div style={{ width: shape.width * shape.scale, height: shape.height * shape.scale }}>
        <div style={{
          width: shape.width, height: shape.height,
          transform: `scale(${shape.scale})`, transformOrigin: 'top left',
          borderRadius: 36, overflow: 'hidden', position: 'relative',
          background: dark ? 'var(--dark)' : 'var(--beige)',
          boxShadow: '0 30px 80px rgba(20,22,15,.35), 0 2px 0 rgba(255,255,255,.5) inset',
          border: '1px solid rgba(20,22,15,.08)',
        }}>
          {children}
        </div>
      </div>
    </div>
  );
}

function App() {
  // If Mollie returned the customer to us with a `?paid=GRV-XXXX` (and
  // optional `?session=<uuid>`) query, jump straight to PaidPreviewScreen and
  // remember the coupon code. We strip the query before rendering so a
  // page-refresh later does not re-trigger this branch.
  const initialBoot = (() => {
    if (typeof window === 'undefined') return { screen: 'welcome', coupon: null, sessionId: null };
    try {
      const url = new URL(window.location.href);
      const coupon    = url.searchParams.get('paid');
      const sessionId = url.searchParams.get('session');
      if (coupon) {
        // Clean up the URL so the route doesn't stick.
        url.searchParams.delete('paid');
        url.searchParams.delete('session');
        window.history.replaceState({}, '', url.pathname + (url.search || '') + url.hash);
        return { screen: 'paidPreview', coupon, sessionId };
      }
    } catch (e) {}
    return { screen: 'welcome', coupon: null, sessionId: null };
  })();

  const [screen, setScreen] = useApp(initialBoot.screen);
  // Only before the scan starts may the app reload for a new version: once the
  // camera is open, photos are taken or a scan exists (upload, preview,
  // deposit), a reload would lose her place. index.html waits for this flag.
  useAppE(() => {
    const c = captureRef.current || {};
    const veilig = !c.sessionId && (c.photos || []).length === 0 && !['capture', 'details', 'processing'].includes(screen);
    window.__SCAN_BEZIG = !veilig;
    if (window.__herlaadAlsNodig) window.__herlaadAlsNodig();
  }, [screen]);
  // Redraw when the partner's branding arrives after the first screen (brand.js).
  const [, setBrandVersie] = useApp(0);
  React.useEffect(() => {
    const opnieuw = () => setBrandVersie((v) => v + 1);
    window.addEventListener('brand-bijgewerkt', opnieuw);
    return () => window.removeEventListener('brand-bijgewerkt', opnieuw);
  }, []);
  const [hist,   setHist]   = useApp([]);
  const [help,   setHelp]   = useApp(false);
  // Lifted preview-poll state so it survives screen navigation. PreviewScreen
  // reads from here via ctx instead of running its own poller; that way the
  // "Notify me & keep browsing" button can navigate the customer to the
  // Atelier collection while we keep polling and ping them when the mesh
  // is ready.
  const [previewState, setPreviewState] = useApp(null); // { state, glb_url?, elapsed_seconds?, ... } | null

  // Cross-screen capture store. CaptureScreen pushes the four main photos here;
  // DetailsScreen pushes any extra close-ups + the customer's contact details;
  // ProcessingScreen reads it all and ships it to the dashboard.
  const captureRef = React.useRef({
    photos: [],                                       // { angle, file, note? }
    contact: null,                                    // { first_name, last_name, email, ... }
    sessionId: initialBoot.sessionId,                 // populated by ProcessingScreen
    couponCode: initialBoot.coupon,                   // populated by Mollie return
    scanMode: 'standing',                             // 'standing' or 'seated'; set on OverviewScreen
  });

  // Back from the payment page with the back button, or the app was closed
  // before paying (Marit 2026-11-12: the scan was gone and she could not pay
  // or use her code any more). If this phone has a scan that still waits for
  // the deposit, open the payment screen again. Waits for the partner's key.
  useAppE(() => {
    if (initialBoot.screen !== 'welcome' || window.APP_PROEF || !window.openScan) return undefined;
    const open = window.openScan.lees();
    if (!open) return undefined;
    let gedaan = false;
    const probeer = async () => {
      const cfg = window.SCAN_API_CONFIG || {};
      if (gedaan || !cfg.token) return;
      gedaan = true;
      try {
        const base = (cfg.base || '').replace(/\/$/, '');
        const res = await fetch(`${base}/api/scan/${encodeURIComponent(open.sessionId)}/deposit/status`, {
          headers: { 'X-Scan-App-Token': cfg.token },
        });
        if (!res.ok) { if (res.status === 404) window.openScan.wis(); return; }
        const data = await res.json();
        if (!data.waiting) { window.openScan.wis(); return; }
        if (captureRef.current.sessionId || (captureRef.current.photos || []).length) return;
        captureRef.current.sessionId = open.sessionId;
        setScreen((s) => (s === 'welcome' ? 'preview' : s));
      } catch (e) { gedaan = false; }
    };
    probeer();
    window.addEventListener('brand-bijgewerkt', probeer);
    return () => window.removeEventListener('brand-bijgewerkt', probeer);
  }, []);

  // Background preview poller. Active whenever a sessionId is set and the
  // preview is not yet ready. Runs every 7 seconds, posts a system
  // notification (if permission granted) the moment status flips to 'ready'
  // and the customer is on a non-preview screen.
  const prevReadyRef = React.useRef(false);
  useAppE(() => {
    const poll = async () => {
      if (!window.APP_TOONT_VOORBEELD) return;      // preview not shown in the app
      const sessionId = captureRef.current.sessionId;
      if (!sessionId) return;
      if (prevReadyRef.current) return;            // already ready, no need to poll
      const cfg = (typeof window !== 'undefined' && window.SCAN_API_CONFIG) || {};
      const base  = (cfg.base  || '').replace(/\/$/, '');
      const token = cfg.token || '';
      try {
        const res = await fetch(`${base}/api/scan/${encodeURIComponent(sessionId)}/preview`, {
          headers: token ? { 'X-Scan-App-Token': token } : {},
        });
        if (!res.ok) return;
        const data = await res.json();
        setPreviewState(data);
        if (data.state === 'ready' && !prevReadyRef.current) {
          prevReadyRef.current = true;
          // Fire a system notification if the user has granted permission.
          // Silently fails on iOS Safari + older browsers without the API.
          if (typeof Notification !== 'undefined' && Notification.permission === 'granted') {
            try {
              new Notification(`Your ${window.BRAND.partner.naam} preview is ready`, {
                body: 'Tap to see your first 3D look.',
                icon: '/img/icon-512.png',
                tag:  'gravida-preview-ready',
              });
            } catch (e) {}
          }
        }
      } catch (e) {
        // network blip, try again next tick
      }
    };
    poll();                                         // immediate first call so the spinner doesn't sit empty
    const id = setInterval(poll, 7000);
    return () => clearInterval(id);
  }, []);

  const ctx = {
    tone:    CTX_DEFAULTS.tone,
    help:    CTX_DEFAULTS.help,
    framing: CTX_DEFAULTS.framing,
    capture: captureRef.current,
    previewState,                                     // for PreviewScreen to read from
    go:      (s) => {
      s = schermVoorPartner(s);
      if (window.APP_PROEF && window.APP_INGEBED && ['capture', 'details', 'processing'].includes(s)) s = 'proefEinde';
      setHist((h) => [...h, screen]); setScreen(s); setHelp(false);
    },
    back:    () => {
      setHelp(false);
      setScreen(hist[hist.length - 1] || 'welcome');
      setHist((h) => h.slice(0, -1));
    },
    onHelp:  () => setHelp(true),
  };

  const meta = SCREENS[screen];
  const Comp = window[meta.C];

  // Render a small floating banner whenever the preview becomes ready and the
  // customer is browsing somewhere else (Atelier collection, BTS, etc.).
  const showPreviewReadyBanner =
    window.APP_TOONT_VOORBEELD &&
    previewState?.state === 'ready' &&
    screen !== 'preview' &&
    screen !== 'paidPreview' &&
    screen !== 'processing';

  return (
    <Stage dark={meta.dark}>
      <div style={{ position: 'relative', height: '100%', width: '100%' }}>
        <div key={screen} style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
          {Comp ? <Comp ctx={ctx} /> : null}
        </div>
        {window.APP_PROEF && (
          <div style={{
            position: 'absolute', top: 4, left: '50%', transform: 'translateX(-50%)', zIndex: 40, pointerEvents: 'none',
            background: 'var(--ink)', color: '#fff', fontSize: 10, fontWeight: 700,
            letterSpacing: '.12em', textTransform: 'uppercase', padding: '3px 9px', borderRadius: 6, opacity: .88,
          }}>
            Preview
          </div>
        )}
        {showPreviewReadyBanner && (
          <button onClick={() => { setHist((h) => [...h, screen]); setScreen('preview'); }}
            style={{
              position: 'absolute', top: 14, left: 14, right: 14, zIndex: 35,
              background: 'var(--ink)', color: 'var(--paper)',
              padding: '12px 16px', borderRadius: 14, border: 'none', cursor: 'pointer',
              boxShadow: '0 12px 30px rgba(20,22,15,.45)',
              display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left',
              animation: 'scr-in .4s cubic-bezier(.22,.61,.36,1) both',
            }}>
            <span style={{ flex: 1 }}>
              <span style={{ display: 'block', fontSize: 10.5, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--gold-soft)', fontWeight: 700 }}>Preview ready</span>
              <span style={{ display: 'block', fontSize: 14, fontWeight: 600, marginTop: 1 }}>Your first 3D look is here</span>
            </span>
            <IcArrow size={18} />
          </button>
        )}
        <HelpSheet open={help} onClose={() => setHelp(false)} sessionId={captureRef.current.sessionId} />
      </div>
    </Stage>
  );
}

// Wait for the partner's branding (brand.js) so a partner never sees Gravida
// flash by; brand.js resolves within 2.5 s at most, and instantly when cached.
(window.brandKlaar || Promise.resolve()).then(() => {
  ReactDOM.createRoot(document.getElementById('root')).render(<App />);
});
