// screens-result.jsx — upload, honest "what happens next", and the Atelier catalogue / scan-kit upsell
// No client-facing 3D preview: AI sculpting is an artful estimate; a true 1:1 needs the DIY Scan-kit.

const { useState: useS2, useEffect: useE2 } = React;

// ── Uploading ────────────────────────────────────────────────
// Walks the customer through the three-step real upload to dashboard.gravida.nl:
//   1. open a session                            (upload-init)
//   2. send each captured photo                  (per-photo POST)
//   3. finalise + notify Laila                   (complete)
//
// On any failure, the customer sees a calm retry sheet, not the actual error.
function ProcessingScreen({ ctx }) {
  const steps = [
    'Opening a safe session in Europe',
    'Sending your photos',
    'Letting Laila know',
  ];
  const [active, setActive] = useS2(0);
  const [photoTotal, setPhotoTotal] = useS2(0);
  const [photoDone,  setPhotoDone]  = useS2(0);
  const [done, setDone] = useS2(false);
  const [error, setError] = useS2(null);
  const [retryCount, setRetryCount] = useS2(0);
  const hasRunRef = React.useRef(false);

  // Pull captured photos + contact from the cross-screen ctx store. The mock
  // path (no photos staged, e.g. when someone jumped straight to this screen
  // for a design preview) falls back to a believable timed animation.
  const photos  = (ctx && ctx.capture && Array.isArray(ctx.capture.photos)) ? ctx.capture.photos : [];
  const contact = (ctx && ctx.capture && ctx.capture.contact) || {};

  useE2(() => {
    if (hasRunRef.current) return;
    hasRunRef.current = true;
    // retryCount in deps ensures this effect re-runs when the user taps "Try again"

    // Demo path: no real photos staged → fake the animation so the design
    // can still be walked through without a camera or dashboard connection.
    const upload = window.gravidaUpload;
    if (!upload || photos.length === 0) {
      const t1 = setTimeout(() => setActive(1),                                  1300);
      const t2 = setTimeout(() => setActive(2),                                  2700);
      const t3 = setTimeout(() => { setActive(3); setDone(true); },              4000);
      return () => [t1, t2, t3].forEach(clearTimeout);
    }

    // Real path.
    setPhotoTotal(photos.length);
    (async () => {
      try {
        const scanMode = (ctx && ctx.capture && ctx.capture.scanMode) || 'standing';
        const { sessionId } = await upload.init({
          first_name:      contact.first_name,
          last_name:       contact.last_name,
          email:           contact.email,
          phone:           contact.phone,
          pregnancy_weeks: contact.pregnancy_weeks,
          scan_mode:       scanMode,
        });
        setActive(1);
        // Body angles set p.order_idx explicitly during capture (0 for
        // round 1, 1 for round 2). Hand + detail close-ups don't, so we
        // fall back to a per-angle counter for those.
        const counters = {};
        for (const p of photos) {
          let order = p.order_idx;
          if (typeof order !== 'number') {
            order = counters[p.angle] || 0;
            counters[p.angle] = order + 1;
          }
          await upload.photo(sessionId, p.file, {
            angle:        p.angle,
            order_idx:    order,
            location_idx: p.location_idx ?? 0,
            note:         p.note,
          });
          setPhotoDone((d) => d + 1);
        }
        setActive(2);
        await upload.complete(sessionId, {
          first_name:      contact.first_name,
          last_name:       contact.last_name,
          email:           contact.email,
          phone:           contact.phone,
          pregnancy_weeks: contact.pregnancy_weeks,
          scan_mode:       scanMode,
        });
        // Stash the session id so PreviewScreen can poll for the Rodin mesh.
        if (ctx && ctx.capture) ctx.capture.sessionId = sessionId;
        setActive(3);
        setDone(true);
      } catch (err) {
        setError((err && err.message) || 'Something went wrong while sending');
      }
    })();
  }, [retryCount]);

  const stepLabel = (i) => {
    if (i === 1 && photoTotal > 0 && !done) return `${steps[1]} (${photoDone}/${photoTotal})`;
    return steps[i];
  };

  if (error) {
    return (
      <div className="scr scr--paper">
        <TopBar onHelp={ctx.onHelp} />
        <div className="pad flex1 col" style={{ justifyContent: 'space-between' }}>
          <div className="grow center col">
            <div className="center" style={{ width: 76, height: 76, borderRadius: 999, background: 'color-mix(in oklch, var(--rose), transparent 85%)', color: 'var(--rose-deep)', marginBottom: 18 }}>
              <IcRetake size={32} />
            </div>
            <span className="eyebrow">A small hiccup</span>
            <h1 className="title" style={{ textAlign: 'center', marginTop: 8 }}>Let's try sending again.</h1>
            <p className="lede" style={{ marginTop: 12, textAlign: 'center', maxWidth: 300 }}>
              We could not reach the Atelier just now. Your photos are still safe on this phone, nothing was sent halfway.
            </p>
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <button className="btn btn--ghost" style={{ flex: 1 }} onClick={() => ctx.onHelp()}>Talk to Atelier</button>
            <button className="btn btn--accent" style={{ flex: 1.4 }} onClick={() => { hasRunRef.current = false; setError(null); setActive(0); setPhotoDone(0); setDone(false); setRetryCount(c => c + 1); }}>
              <IcRetake size={18} /> Try again
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="scr scr--paper">
      <TopBar onHelp={ctx.onHelp} />
      <div className="pad flex1 col" style={{ justifyContent: 'space-between' }}>
        <div className="grow center col" style={{ gap: 0 }}>
          <div style={{ position: 'relative', width: 132, height: 132, marginBottom: 30 }}>
            {!done && [0, 1].map((i) => (
              <div key={i} style={{ position: 'absolute', inset: 0, borderRadius: 999, border: '2px solid var(--rose)', animation: `pulsering 2.4s ease-out ${i * 1.2}s infinite` }} />
            ))}
            <div className="center" style={{ position: 'absolute', inset: 0, borderRadius: 999, background: done ? 'var(--ink)' : 'linear-gradient(135deg, var(--rose), var(--gold))', color: '#fff', transition: 'background .5s' }}>
              {done ? <IcCheck size={48} /> : <IcShield size={44} />}
            </div>
          </div>
          <span className="eyebrow">{done ? 'Received' : 'Sending'}</span>
          <h1 className="title" style={{ textAlign: 'center', marginTop: 8 }}>
            {done ? 'Safely with the Atelier.' : 'Sending your photos...'}
          </h1>

          <div style={{ width: '100%', marginTop: 24 }}>
            {steps.map((_, i) => {
              const state = i < active ? 'done' : i === active ? 'now' : 'todo';
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '9px 0', opacity: state === 'todo' ? .4 : 1, transition: 'opacity .4s' }}>
                  <div className="center" style={{ width: 26, height: 26, borderRadius: 999, flex: '0 0 auto', background: state === 'done' ? 'var(--gold)' : 'transparent', border: state === 'done' ? 'none' : '2px solid var(--hairline)', color: '#fff' }}>
                    {state === 'done' ? <IcCheck size={15} /> :
                      state === 'now' ? <div style={{ width: 11, height: 11, borderRadius: 999, border: '2px solid var(--gold)', borderTopColor: 'transparent', animation: 'spin360 .8s linear infinite' }} /> : null}
                  </div>
                  <span style={{ fontSize: 14.5, fontWeight: state === 'now' ? 700 : 500, color: state === 'todo' ? 'var(--ink-mute)' : 'var(--ink)' }}>{stepLabel(i)}</span>
                </div>
              );
            })}
          </div>
          {done && (
            <div className="fadein" style={{ marginTop: 18, display: 'flex', gap: 12, padding: '13px 14px', borderRadius: 12, background: 'color-mix(in oklch, var(--gold), transparent 88%)', border: '1px solid color-mix(in oklch, var(--gold), transparent 68%)' }}>
              <span style={{ color: 'var(--gold)', flex: '0 0 auto', marginTop: 1 }}><IcLeaf size={18} /></span>
              <p style={{ margin: 0, fontSize: 13.5, lineHeight: 1.55, color: 'var(--ink-soft)' }}>
                <b>Within 48 hours</b>, our sculptors will assess your photos and let you know if any angle needs a retake before we begin sculpting.
              </p>
            </div>
          )}
        </div>

        <div>
          {!done && (
            <p className="lede" style={{ fontSize: 13.5, textAlign: 'center', marginBottom: 14 }}>
              Your photos go straight to Laila, encrypted on European servers.
            </p>
          )}
          {done
            ? <button className="btn btn--accent fadein" onClick={() => ctx.go('preview')}>See your first preview <IcArrow size={18} /></button>
            : <button className="btn btn--ghost" onClick={() => ctx.onHelp()}>Notify me &amp; keep browsing</button>}
        </div>
      </div>
    </div>
  );
}

// ── What happens next (honest about AI sculpting) ────────────
function SubmittedScreen({ ctx }) {
  return (
    <div className="scr scr--light">
      <TopBar onBack={() => ctx.go('processing')} onHelp={ctx.onHelp} />
      <div className="pad flex1 col" style={{ justifyContent: 'space-between' }}>
        <div>
          <span className="eyebrow">With the Atelier now</span>
          <h1 className="display display--sm" style={{ marginTop: 10 }}>Now our sculptors shape your piece.</h1>
          <p className="lede" style={{ marginTop: 14 }}>
            From your set of photos, our team of digital sculptors shapes your figure by hand, guided by AI. It's an artful likeness, shaped to your form and finished in the Atelier over the coming days.
          </p>

          {/* honesty card */}
          <div className="card" style={{ marginTop: 18, background: 'color-mix(in oklch, var(--gold), transparent 90%)', borderColor: 'color-mix(in oklch, var(--gold), transparent 72%)' }}>
            <div style={{ display: 'flex', gap: 12 }}>
              <div className="chk" style={{ background: 'transparent', color: 'var(--gold)' }}><IcLeaf size={18} /></div>
              <div>
                <h4 style={{ margin: '2px 0 4px', fontSize: 15, fontWeight: 700 }}>Honest about what this is</h4>
                <p style={{ margin: 0, fontSize: 13.5, lineHeight: 1.5, color: 'var(--ink-soft)' }}>
                  An AI sculpture is a beautiful estimate built from your photos, not a millimetre-exact measurement. For a true 1:1 copy of your body, we'll show you the Scan-kit next.
                </p>
              </div>
            </div>
          </div>

          <div className="tag" style={{ marginTop: 16 }}>
            <IcEye size={14} /> You'll receive your finished views by email
          </div>
        </div>
        <div className="btn-row" style={{ marginTop: 16 }}>
          <button className="btn btn--primary" onClick={() => ctx.go('atelier')}>
            See materials &amp; the Scan-kit <IcArrow size={18} />
          </button>
        </div>
      </div>
    </div>
  );
}

// ── The Atelier: full collection from studiogravida.com (names, prices, finishes) ──
// Each row: [name, subtitle, price, swatch tone (fallback), local photo (or null),
//            webshop url that opens when the card is tapped].
//
// Image filenames mirror studiogravida.com/products/<filename>, so a tap deep-links
// to the same file the live shop uses.
const SHOP = 'https://www.studiogravida.com';
const SG = (file) => `${SHOP}/products/${file}`;
const COLLECTION = `${SHOP}/collection`;

const FINISHES = [
  ['White Resin',          'Pure white, matte',              'from €309', '#ece7da', 'img/products/Wit-zwangerschapsbeeldje.jpg',                          SG('Wit-zwangerschapsbeeldje.jpg')],
  ['Black Resin',          'Deep black, matte',              'from €309', '#26251f', 'img/products/zwart-resin-zwangerschapsbeeld.jpg',                    SG('zwart-resin-zwangerschapsbeeld.jpg')],
  ['Gold Resin',           'Gold, hand-applied wax',         'from €359', '#b88a3c', 'img/products/Gouden-zwangerschapsbeeld.jpg',                         SG('Gouden-zwangerschapsbeeld.jpg')],
  ['Bronze-Look Resin',    'The depth of bronze, lighter',   'from €359', '#8a6a3e', 'img/products/bronslook-zwangerschapsbeeld.jpg',                      SG('bronslook-zwangerschapsbeeld.jpg')],
  ['Royal Blue Resin',     'Saturated, glossy lacquer',      'from €409', '#2e3c63', 'img/products/royal-blue-zwangerschapsbeeldje.png',                   SG('royal-blue-zwangerschapsbeeldje.png')],
  ['Red Premium Resin',    'Deep premium red, glossy',       'from €409', '#7e2a28', 'img/products/red-premium.jpg',                                       SG('red-premium.jpg')],
  ['Turquoise Resin',      'Jewel-like depth',               'from €409', '#2f7a72', 'img/products/turquoise.jpg',                                         SG('turquoise.jpg')],
  ['Off-White Resin',      'Soft cream tone',                'from €409', '#e4dccb', 'img/products/Offwhite-resin-zwangerschapsbeeld.png',                 SG('Offwhite-resin-zwangerschapsbeeld.png')],
  ['Refined Bronze',       'Warm, deep tone',                'from €439', '#8a6a3e', 'img/products/veredeld-brons-zwangerschapsbeeld.png',                 SG('veredeld-brons-zwangerschapsbeeld.png')],
  ['Refined Copper',       'Rich, warm glow',                'from €439', '#b07a52', 'img/products/veredeld-koper-zwangerschapsbeeld.jpg',                 SG('veredeld-koper-zwangerschapsbeeld.jpg')],
  ['Refined Light Bronze', 'Matte, soft variation',          'from €439', '#a98c5a', null,                                                                  COLLECTION],
  ['Refined Blue Bronze',  'Quiet blue undertone',           'from €439', '#5b6b6e', 'img/products/veredeld-brons-blauw-zwangerschapsbeeld.png',           SG('veredeld-brons-blauw-zwangerschapsbeeld.png')],
  ['Composite Stone',      'Sandstone composite, matte',     'from €509', '#cdbfa3', 'img/products/Composiet-steen-zwangerschapsbeeldje.jpg',              SG('Composiet-steen-zwangerschapsbeeldje.jpg')],
  ['Clear Epoxy',          'Matte, lets the light through',  'from €509', '#d6cdbd', 'img/products/Epoxy-mat-zwangerschapsbeeldje.jpg',                    SG('Epoxy-mat-zwangerschapsbeeldje.jpg')],
  ['Blue Epoxy',           'Saturated, softly contained',    'from €509', '#486a89', 'img/products/blauw-epoxy-zwangerschapsbeeld.png',                    SG('blauw-epoxy-zwangerschapsbeeld.png')],
  ['Taupe Epoxy',          'Warm neutral',                   'from €509', '#a89478', 'img/products/epoxy-zwangerschapsbeeld-1.png',                        SG('epoxy-zwangerschapsbeeld-1.png')],
  ['Classic Bronze',       'Solid cast, traditional',        'from €852', '#7d5c33', 'img/products/klassiek-brons-zwangerschapsbeeld.png',                 SG('klassiek-brons-zwangerschapsbeeld.png')],
  ['Deep Patina Bronze',   'Dark, layered patina',           'from €852', '#3f4a3e', 'img/products/diep-gepatineerd-brons-gegoten-zwangerschapsbeeld.jpg', SG('diep-gepatineerd-brons-gegoten-zwangerschapsbeeld.jpg')],
  ['White Bronze',         'Polished, warm ivory',           'from €852', '#d7c8a6', 'img/products/witbrons-zwangerschapsbeeldje.webp',                    SG('witbrons-zwangerschapsbeeldje.webp')],
  ['Verdigris Bronze',     'Natural blue-green patina',      'from €852', '#4d7d6b', 'img/products/groen-blauw-gepatineerd-zwangerschapsbeeld.png',        SG('groen-blauw-gepatineerd-zwangerschapsbeeld.png')],
  ['Light Patina Bronze',  'Soft, light patina',             'from €852', '#9c8350', 'img/products/licht-gepatineerd-brons-zwangerschapsbeeld.jpg',        SG('licht-gepatineerd-brons-zwangerschapsbeeld.jpg')],
  ['Warm Bronze',          'Deeper, weighted warmth',        'from €852', '#8a5f33', 'img/products/warm-brons-gegoten.jpg',                                SG('warm-brons-gegoten.jpg')],
];
const CHARMS = [
  ['Pregnancy Charm, Silver',   'Sterling silver, on a chain', 'from €339', '#c6c9cb', 'img/products/bedel-zwangere-lichaam.png', SG('bedel-zwangere-lichaam.png')],
  ['Pregnancy Charm, 14K Gold', 'Solid 14 karat gold',         'from €709', '#c79a3f', 'img/products/1000073740.png',             SG('1000073740.png')],
];
const MINIS = [
  ['Sterling Silver Mini',  'Hand-cast 925 silver',            'from €1109', '#c6c9cb', null,               `${SHOP}/products/minis-zilver-slider.jpg`],
  ['Gold-Plated Mini',      'Solid silver, gold plating',      'from €1258', '#c8a24a', 'img/mat-gold.png', `${SHOP}/products/mini-goud-slider.jpg`],
  ['Rose-Gold-Plated Mini', 'Solid silver, rose-gold plating', 'from €1258', '#c89a88', null,               `${SHOP}/products/minis-rosegold-slider.jpg`],
];

function ShopCard({ item }) {
  const [name, sub, price, tone, img, url] = item;
  const open = () => { if (url) window.open(url, '_blank', 'noopener,noreferrer'); };
  return (
    <button onClick={open} aria-label={`${name}, ${price}, view on studiogravida.com`}
      style={{
        all: 'unset', cursor: 'pointer', display: 'block', boxSizing: 'border-box',
        borderRadius: 14, overflow: 'hidden', background: 'var(--paper)',
        border: '1px solid var(--hairline)', WebkitTapHighlightColor: 'transparent',
        transition: 'transform .15s ease, box-shadow .25s ease',
      }}
      onMouseEnter={(e) => { e.currentTarget.style.boxShadow = '0 6px 22px rgba(20,22,15,.10)'; e.currentTarget.style.transform = 'translateY(-1px)'; }}
      onMouseLeave={(e) => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}>
      <div style={{ height: 128, position: 'relative' }}>
        {img
          ? <Placeholder src={img} label={name} />
          : <div style={{ width: '100%', height: '100%', background: `radial-gradient(65% 58% at 34% 26%, rgba(255,255,255,.30), rgba(255,255,255,0) 60%), ${tone}` }} />}
      </div>
      <div style={{ padding: '10px 12px 12px' }}>
        <div style={{ fontWeight: 700, fontSize: 13.5, lineHeight: 1.22, color: 'var(--ink)' }}>{name}</div>
        <div style={{ fontSize: 12, color: 'var(--ink-mute)', marginTop: 2 }}>{sub}</div>
        <div className="serif-num" style={{ fontSize: 15.5, color: 'var(--gold)', marginTop: 7 }}>{price}</div>
      </div>
    </button>
  );
}
function ShopGrid({ items }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 12 }}>
      {items.map((m) => <ShopCard key={m[0]} item={m} />)}
    </div>
  );
}

function AtelierScreen({ ctx }) {
  return (
    <div className="scr scr--paper">
      <div style={{ flex: '0 0 auto' }}>
        <TopBar onBack={() => ctx.back()} onHelp={ctx.onHelp} />
      </div>

      <div style={{ flex: 1, minHeight: 0, overflowY: 'auto' }}>
        <div className="pad" style={{ paddingBottom: 16 }}>
          <span className="eyebrow">The Collection</span>
          <h1 className="title" style={{ marginTop: 8 }}>Each one different.</h1>
          <p className="lede" style={{ fontSize: 14.5, marginTop: 10 }}>
            The same scan, carried into a different material. Twenty-two finishes, two charms and a line of solid-metal minis, each finished by hand in Haarlem.
          </p>

          <div style={{ marginTop: 20 }}><span className="eyebrow">The Sculptures · 22 finishes</span></div>
          <ShopGrid items={FINISHES} />

          <div style={{ marginTop: 24 }}><span className="eyebrow">The Charm · worn close</span></div>
          <ShopGrid items={CHARMS} />

          <div style={{ marginTop: 24 }}><span className="eyebrow">The Mini · cast in metal</span></div>
          <ShopGrid items={MINIS} />

          <button className="btn btn--ghost" style={{ marginTop: 20 }} onClick={() => window.open('https://www.studiogravida.com/collection', '_blank')}>
            See it all on studiogravida.com <IcArrow size={17} />
          </button>
        </div>

        <hr className="hair" />

        {/* the clear distinction */}
        <div className="pad" style={{ paddingTop: 22, paddingBottom: 28 }}>
          <span className="eyebrow">Two ways to capture you</span>
          <h2 className="title" style={{ marginTop: 8 }}>An AI likeness, or a true 1:1.</h2>

          {/* This app */}
          <div className="card" style={{ marginTop: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                <span className="center" style={{ width: 34, height: 34, borderRadius: 999, background: 'color-mix(in oklch, var(--rose), transparent 85%)', color: 'var(--rose-deep)' }}><IcCamera size={18} /></span>
                <b style={{ fontSize: 15.5 }}>This app · AI sculpting</b>
              </div>
              <span className="tag" style={{ background: 'var(--ink)', color: 'var(--paper)', border: 'none' }}>You're here</span>
            </div>
            <p style={{ fontSize: 13.5, lineHeight: 1.5, color: 'var(--ink-soft)', margin: '12px 0 0' }}>
              From home, in minutes. A free AI preview from your photos. Turn it into a refined,
              hand-finished digital model from €10 — yours to keep and to have made into a figurine
              whenever you like. A beautiful artistic likeness, not an exact measurement.
            </p>
          </div>

          {/* Scan-kit */}
          <div className="card" style={{ marginTop: 12, background: 'var(--ink)', border: 'none', color: 'var(--on-dark)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
              <span className="center" style={{ width: 34, height: 34, borderRadius: 999, background: 'rgba(138,122,90,.28)', color: 'var(--gold-soft)' }}><IcSparkle size={18} /></span>
              <b style={{ fontSize: 15.5, color: 'var(--paper)' }}>DIY Scan-kit · a true 1:1</b>
            </div>
            <p style={{ fontSize: 13.5, lineHeight: 1.5, color: 'var(--on-dark-mute)', margin: '12px 0 14px' }}>
              A scientifically exact copy of your body. We post you a professional 3D scanner, you scan at home in a week, and we shape it from there.
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
              {[
                'A true 1:1 copy of your body',
                'Scan at home, around weeks 30 to 36',
                '€200 deposit, fully refundable',
              ].map((b) => (
                <div key={b} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <span style={{ color: 'var(--gold-soft)', display: 'flex' }}><IcCheck size={16} /></span>
                  <span style={{ fontSize: 13.5, color: 'var(--on-dark)' }}>{b}</span>
                </div>
              ))}
            </div>
            <button className="btn btn--ghost" style={{ marginTop: 16, borderColor: 'rgba(236,231,218,.28)', color: 'var(--paper)' }} onClick={() => window.open('https://www.studiogravida.com/diy-scan', '_blank')}>
              Reserve your kit <IcArrow size={17} />
            </button>
          </div>

          <div style={{ marginTop: 18 }}>
            <HelpBar prominence={ctx.help} onHelp={ctx.onHelp} />
          </div>
        </div>
      </div>

      {/* sticky book bar — back to PreviewScreen where the real €35 deposit CTA lives */}
      <div style={{ flex: '0 0 auto', padding: '12px 20px 14px', borderTop: '1px solid var(--hairline)', background: 'var(--paper)' }}>
        <button className="btn btn--accent" onClick={() => ctx.go('preview')}>
          Book your sculpture <IcArrow size={18} />
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { ProcessingScreen, SubmittedScreen, AtelierScreen });
