// Scenes for the MiPaghi storyboard — realistic version.
// Real product photos, no stylized icons; assistant-driven order creation; new scenes.

const PRODUCTS = {
  bag:   { id: 'bag',   name: 'Borsa elegante',   sku: 'BG-1245', sub: 'Pelle nera · tracolla',  price: 189.00, photo: 'assets/bag.jpg'   },
  shoe:  { id: 'shoe',  name: 'Sneaker nera',     sku: 'SK-0042', sub: 'Pelle · taglia 42',      price: 129.00, photo: 'assets/shoe.jpg'  },
  shirt: { id: 'shirt', name: 'T-shirt cotone',   sku: 'TS-0301', sub: 'Cotone organico · M',    price:  79.00, photo: 'assets/shirt.jpg' },
};

const fmt = (n) => n.toLocaleString('it-IT', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const eur = (n) => `€ ${fmt(n)}`;

// Realistic product photo. Default `contain` so we don't zoom into the image.
function ProductPhoto({ product, size = 120, radius = 12, fit = 'contain' }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: radius, overflow: 'hidden', flexShrink: 0,
      background: '#F2EEE6',
      boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.04)',
      display: 'grid', placeItems: 'center',
    }}>
      <img src={product.photo} alt={product.name}
           style={{ width: '100%', height: '100%', objectFit: fit, display: 'block' }}/>
    </div>
  );
}

// App chrome
function AppChrome({ title = 'Nuovo ordine', back, right, sub }) {
  return (
    <div style={{
      position: 'sticky', top: 0, zIndex: 10,
      background: '#fff',
      borderBottom: '1px solid var(--line-2)',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 16px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
          {back ? (
            <button onClick={back} style={{
              border: 'none', background: 'transparent', width: 28, height: 28,
              display: 'grid', placeItems: 'center', color: 'var(--ink)', cursor: 'pointer', padding: 0,
            }}><IconArrowL size={18} stroke={2}/></button>
          ) : (
            <MiPaghiMark size={24}/>
          )}
          <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.15, minWidth: 0 }}>
            <span style={{ fontWeight: 700, fontSize: 14, color: 'var(--ink)' }}>{title}</span>
            {sub && <span style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 500 }}>{sub}</span>}
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>{right}</div>
      </div>
    </div>
  );
}

function PrimaryBtn({ children, onClick, full = true, icon, secondary = false, disabled }) {
  return (
    <button onClick={onClick} disabled={disabled} style={{
      border: 'none', cursor: disabled ? 'default' : 'pointer',
      background: secondary ? 'var(--blue-pale)' : 'var(--blue)',
      color: secondary ? 'var(--ink)' : '#fff',
      padding: '13px 18px', borderRadius: 12, fontWeight: 700, fontSize: 14,
      width: full ? '100%' : 'auto',
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      opacity: disabled ? .45 : 1, fontFamily: 'inherit',
      boxShadow: secondary ? 'none' : '0 4px 12px rgba(30,120,200,.25)',
      transition: 'transform .12s',
    }}
    onMouseDown={e => !disabled && (e.currentTarget.style.transform = 'scale(.98)')}
    onMouseUp={e => e.currentTarget.style.transform = 'scale(1)'}
    onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}>
      {children}{icon}
    </button>
  );
}

function SectionLabel({ children, style }) {
  return <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--ink-3)', margin: '14px 0 8px', ...style }}>{children}</div>;
}

// ─────────────────────────────────────────────────────────────
// SCENE 1 — Intro: camera-live preview rotating through products
// ─────────────────────────────────────────────────────────────
function Scene0_Intro({ actions }) {
  const products = Object.values(PRODUCTS);
  const [idx, setIdx] = React.useState(0);
  React.useEffect(() => {
    const t = setInterval(() => setIdx(i => (i + 1) % products.length), 1800);
    return () => clearInterval(t);
  }, []);
  const current = products[idx];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', position: 'relative' }}>
      {/* status bar already in iOS frame; here we just show the camera live UI */}
      <div style={{ position: 'absolute', inset: 0, background: '#0E1A24', overflow: 'hidden' }}>
        {/* Camera viewfinder with the product */}
        <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', transition: 'background .6s' }}>
          <img key={current.id} src={current.photo} alt=""
            style={{
              width: '78%', maxHeight: '60%', objectFit: 'contain',
              animation: 'fadeInSlow .6s ease both',
              filter: 'drop-shadow(0 20px 40px rgba(0,0,0,.4))',
            }}/>
        </div>
        {/* viewfinder corners */}
        {[
          { top: 100, left: 18, br: '14px 0 0 0' },
          { top: 100, right: 18, br: '0 14px 0 0' },
          { bottom: 160, left: 18, br: '0 0 0 14px' },
          { bottom: 160, right: 18, br: '0 0 14px 0' },
        ].map((s, i) => (
          <div key={i} style={{
            position: 'absolute', width: 22, height: 22, ...s,
            borderTop: s.top != null ? '2px solid #fff' : 'none',
            borderBottom: s.bottom != null ? '2px solid #fff' : 'none',
            borderLeft: s.left != null ? '2px solid #fff' : 'none',
            borderRight: s.right != null ? '2px solid #fff' : 'none',
            opacity: .6,
          }}/>
        ))}
        {/* Top label */}
        <div style={{
          position: 'absolute', top: 58, left: '50%', transform: 'translateX(-50%)',
          padding: '5px 12px', borderRadius: 999, background: 'rgba(0,0,0,.4)',
          backdropFilter: 'blur(10px)', color: '#fff', fontSize: 11, fontWeight: 600,
          display: 'flex', alignItems: 'center', gap: 6,
        }}>
          <div style={{ width: 6, height: 6, borderRadius: 3, background: '#FF453A', animation: 'pulseDot 1.5s infinite' }}/>
          MiPaghi · Acquisizione
        </div>
        {/* Mode selector (Foto/Video) */}
        <div style={{
          position: 'absolute', bottom: 110, left: 0, right: 0,
          display: 'flex', justifyContent: 'center', gap: 18, fontSize: 11, fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase',
        }}>
          <span style={{ color: '#FFB400' }}>Foto</span>
          <span style={{ color: 'rgba(255,255,255,.5)' }}>Video</span>
        </div>
        {/* Shutter */}
        <div style={{
          position: 'absolute', left: '50%', bottom: 56, transform: 'translateX(-50%)',
          display: 'flex', alignItems: 'center', gap: 28,
        }}>
          <div style={{ width: 36, height: 36, borderRadius: 8, background: 'rgba(255,255,255,.14)' }}/>
          <div style={{
            width: 64, height: 64, borderRadius: '50%', background: '#fff',
            boxShadow: 'inset 0 0 0 4px #0E1A24, 0 0 0 3px #fff',
          }}/>
          <div style={{ width: 36, height: 36, borderRadius: 8, background: 'rgba(255,255,255,.14)', display: 'grid', placeItems: 'center' }}>
            <IconCamera size={18} color="#fff" stroke={1.6}/>
          </div>
        </div>
      </div>

      {/* Bottom CTA overlay — sticks above the home indicator */}
      <div style={{
        position: 'absolute', left: 14, right: 14, bottom: 44, zIndex: 5,
      }}>
        <PrimaryBtn onClick={actions.next} icon={<IconArrow size={16} stroke={2.2}/>}>
          Simula la vendita
        </PrimaryBtn>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// SCENE 2 — Pick: 3 product photos, "Scatta foto" CTA per item
// ─────────────────────────────────────────────────────────────
function Scene1_Pick({ state, actions }) {
  const remaining = Object.values(PRODUCTS).filter(p => !state.cart.some(c => c.id === p.id));
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <AppChrome
        title="Nuovo ordine"
        sub={state.cart.length === 0 ? 'Avvia la vendita' : `${state.cart.length} nel carrello · ${eur(state.cart.reduce((s,l)=>s+l.price,0))}`}
        back={state.cart.length > 0 ? actions.back : null}
      />
      <div style={{ padding: '14px 16px 8px' }}>
        <h2 style={{ margin: 0, fontSize: 19, fontWeight: 800, letterSpacing: '-0.015em', color: 'var(--ink)' }}>
          {state.cart.length === 0 ? 'Quale prodotto vuole il cliente?' : 'Cosa aggiungi all\u2019ordine?'}
        </h2>
        <p style={{ margin: '4px 0 0', fontSize: 12, color: 'var(--ink-3)', fontWeight: 500 }}>
          Scatta una foto per iniziare la riga ordine.
        </p>
      </div>
      <div style={{ padding: '8px 16px 16px', display: 'flex', flexDirection: 'column', gap: 10, overflowY: 'auto', flex: 1 }}>
        {remaining.map((p, i) => (
          <button key={p.id} onClick={() => actions.pickProduct(p.id)} style={{
            border: '1px solid var(--line-2)', background: '#fff', borderRadius: 14, padding: 10,
            display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer', textAlign: 'left',
            fontFamily: 'inherit',
            animation: `fadeIn .25s ${i*0.05}s both`,
            transition: 'border-color .15s, box-shadow .15s',
          }}
          onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--blue)'; e.currentTarget.style.boxShadow = '0 4px 14px rgba(14,42,61,.06)'; }}
          onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line-2)'; e.currentTarget.style.boxShadow = 'none'; }}>
            <ProductPhoto product={p} size={64} radius={10}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink)' }}>{p.name}</div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 500 }}>{p.sub}</div>
            </div>
            <div style={{
              background: 'var(--blue-pale)', color: 'var(--blue)', padding: '7px 11px',
              borderRadius: 10, fontSize: 11, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0,
            }}>
              <IconCamera size={13} stroke={2}/> Scatta
            </div>
          </button>
        ))}
        {state.cart.length > 0 && (
          <button onClick={actions.toCart} style={{
            border: '1px dashed var(--line)', background: 'transparent', borderRadius: 14, padding: 12,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            color: 'var(--ink-2)', fontWeight: 700, fontSize: 12, cursor: 'pointer', fontFamily: 'inherit',
          }}>
            Vai al carrello <IconArrow size={13} stroke={2.2}/>
          </button>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// SCENE 3 — Capture: shutter → preview → form with typing
// ─────────────────────────────────────────────────────────────
function Scene2_Capture({ state, actions }) {
  const product = PRODUCTS[state.pendingProduct];
  // phases: framing → flash → preview → form  (framing waits for user tap)
  const isFollowup = state.cart.length > 0;
  const [phase, setPhase] = React.useState('framing');
  const [name, setName] = React.useState('');
  const [desc, setDesc] = React.useState('');
  const [price, setPrice] = React.useState('');
  const [note, setNote] = React.useState('');

  // After user taps shutter, run flash → preview → form sequence
  const triggerShutter = () => {
    if (phase !== 'framing') return;
    setPhase('flash');
    setTimeout(() => setPhase('preview'), 300);
    setTimeout(() => setPhase('form'), 1000);
  };

  // Typing helper: types target into setter at given speed
  const typeInto = (target, setter, speed = 35, startDelay = 0) => {
    setTimeout(() => {
      let i = 0;
      const tick = () => {
        i += 1;
        setter(target.slice(0, i));
        if (i < target.length) setTimeout(tick, speed);
      };
      tick();
    }, startDelay);
  };

  React.useEffect(() => {
    if (phase !== 'form') return;
    // For follow-ups, do everything quickly and auto-advance
    const speed = isFollowup ? 18 : 32;
    const baseDelay = isFollowup ? 200 : 400;
    typeInto(product.name, setName, speed, baseDelay);
    typeInto(product.sub, setDesc, speed, baseDelay + product.name.length * speed + 200);
    const priceStr = product.price.toFixed(2).replace('.', ',');
    typeInto(priceStr, setPrice, speed + 10, baseDelay + product.name.length * speed + product.sub.length * speed + 500);
    if (isFollowup) {
      // auto advance after typing
      const total = baseDelay + (product.name.length + product.sub.length + priceStr.length) * speed + 1200;
      setTimeout(() => actions.confirmPrice(product.price, { name: product.name, desc: product.sub, note: '' }), total);
    }
  }, [phase]);

  const priceComplete = price.replace(',', '.') === product.price.toFixed(2);

  if (phase !== 'form') {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: '#0E1A24', position: 'relative' }}>
        <div style={{ position: 'absolute', top: 58, left: '50%', transform: 'translateX(-50%)', zIndex: 3,
          padding: '5px 12px', borderRadius: 999, background: 'rgba(0,0,0,.4)', backdropFilter: 'blur(10px)',
          color: '#fff', fontSize: 11, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6 }}>
          <div style={{ width: 6, height: 6, borderRadius: 3, background: '#FF453A', animation: 'pulseDot 1.5s infinite' }}/>
          Foto prodotto
        </div>
        {/* Hint to tap shutter */}
        {phase === 'framing' && (
          <div style={{ position: 'absolute', top: 92, left: 0, right: 0, zIndex: 3, textAlign: 'center',
            color: 'rgba(255,255,255,.85)', fontSize: 11, fontWeight: 600, letterSpacing: '.04em' }}>
            Tocca il pulsante per scattare
          </div>
        )}
        <div style={{ flex: 1, display: 'grid', placeItems: 'center', position: 'relative' }}>
          <img src={product.photo} alt=""
            style={{ width: '78%', maxHeight: '60%', objectFit: 'contain',
              transform: phase === 'preview' ? 'scale(.85)' : 'scale(1)',
              transition: 'transform .4s', filter: 'drop-shadow(0 20px 40px rgba(0,0,0,.4))' }}/>
        </div>
        {/* viewfinder corners */}
        {phase === 'framing' && [
          { top: 120, left: 18 }, { top: 120, right: 18 }, { bottom: 160, left: 18 }, { bottom: 160, right: 18 },
        ].map((s, i) => (
          <div key={i} style={{
            position: 'absolute', width: 22, height: 22, ...s,
            borderTop: s.top != null ? '2px solid #fff' : 'none',
            borderBottom: s.bottom != null ? '2px solid #fff' : 'none',
            borderLeft: s.left != null ? '2px solid #fff' : 'none',
            borderRight: s.right != null ? '2px solid #fff' : 'none', opacity: .6,
          }}/>
        ))}
        {/* Tappable shutter button */}
        <button onClick={triggerShutter} aria-label="Scatta"
          disabled={phase !== 'framing'}
          style={{
            position: 'absolute', left: '50%', bottom: 56,
            transform: phase === 'flash' ? 'translateX(-50%) scale(.85)' : 'translateX(-50%) scale(1)',
            width: 68, height: 68, borderRadius: '50%', background: '#fff',
            boxShadow: 'inset 0 0 0 4px #0E1A24, 0 0 0 3px #fff, 0 0 0 0 rgba(255,255,255,.45)',
            border: 'none', padding: 0, cursor: phase === 'framing' ? 'pointer' : 'default',
            transition: 'transform .15s',
            animation: phase === 'framing' ? 'shutterPulse 1.6s ease-in-out infinite' : 'none',
          }}/>
        {phase === 'flash' && (
          <div style={{ position: 'absolute', inset: 0, background: '#fff', animation: 'flash .35s ease both', pointerEvents: 'none' }}/>
        )}
        {phase === 'preview' && (
          <div style={{ position: 'absolute', bottom: 56, left: '50%', transform: 'translateX(-50%)',
            background: 'rgba(255,255,255,.95)', borderRadius: 12, padding: '8px 12px',
            display: 'flex', alignItems: 'center', gap: 8, animation: 'fadeIn .25s' }}>
            <IconCheck size={14} color="var(--blue)" stroke={2.6}/>
            <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink)' }}>Foto acquisita</span>
          </div>
        )}
      </div>
    );
  }

  // FORM phase
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', animation: 'fadeIn .3s' }}>
      <AppChrome title="Nuovo ordine" sub="Riga ordine" back={actions.back}
        right={<button onClick={() => setPhase('framing')} style={{
          border: 'none', background: 'transparent', color: 'var(--ink-3)', fontSize: 11,
          fontWeight: 600, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 4, fontFamily: 'inherit',
        }}><IconCamera size={13} stroke={2}/> Rifai</button>}/>

      <div style={{ padding: '14px 16px', flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 14 }}>
        {/* Photo card */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <ProductPhoto product={product} size={84} radius={12}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>SKU · {product.sku}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4, display: 'flex', alignItems: 'center', gap: 4 }}>
              <IconSparkle size={11} stroke={2}/> Riconosciuto da AI
            </div>
            <button onClick={() => setPhase('framing')} style={{
              marginTop: 6, fontSize: 11, color: 'var(--blue)', fontWeight: 700,
              border: 'none', background: 'transparent', padding: 0, cursor: 'pointer', fontFamily: 'inherit',
            }}>Rifai foto</button>
          </div>
        </div>

        {/* Name */}
        <Field label="Nome prodotto">
          <span>{name}{name.length < product.name.length && <Caret/>}</span>
        </Field>
        {/* Description */}
        <Field label="Descrizione">
          <span>{desc}{desc.length > 0 && desc.length < product.sub.length && <Caret/>}</span>
        </Field>
        {/* Price - manual */}
        <Field label="Prezzo" hint="Inserito manualmente dall'assistente">
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
            <span style={{ color: 'var(--blue)', fontWeight: 700 }}>€</span>
            <span style={{ fontSize: 18, fontWeight: 800, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.01em' }}>
              {price || <span style={{ color: 'var(--ink-3)', opacity: .4 }}>0,00</span>}
            </span>
            {!priceComplete && price.length > 0 && <Caret/>}
          </div>
        </Field>
        {/* Note */}
        <Field label="Nota (opzionale)">
          <input value={note} onChange={e => setNote(e.target.value)} placeholder="Es. taglia M, regalo…"
            style={{ border: 'none', outline: 'none', fontFamily: 'inherit', fontSize: 13, fontWeight: 500, color: 'var(--ink)', background: 'transparent', width: '100%' }}/>
        </Field>
      </div>

      <div style={{ padding: '12px 16px calc(16px + 34px)', borderTop: '1px solid var(--line-2)', background: '#fff' }}>
        <PrimaryBtn onClick={() => actions.confirmPrice(product.price, { name: product.name, desc: product.sub, note })} disabled={!priceComplete}
          icon={<IconArrow size={16} stroke={2.2}/>}>
          Aggiungi al carrello
        </PrimaryBtn>
      </div>
    </div>
  );
}

function Field({ label, hint, children }) {
  return (
    <div>
      <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 6 }}>{label}</div>
      <div style={{
        background: 'var(--paper)', border: '1px solid var(--line-2)', borderRadius: 10,
        padding: '10px 12px', minHeight: 40, fontSize: 13, fontWeight: 600, color: 'var(--ink)',
        display: 'flex', alignItems: 'center',
      }}>{children}</div>
      {hint && <div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 4, fontWeight: 500 }}>{hint}</div>}
    </div>
  );
}
function Caret() {
  return <span style={{ display: 'inline-block', width: 2, height: 14, marginLeft: 2, background: 'var(--blue)', verticalAlign: 'middle', animation: 'blink 1s steps(1) infinite' }}/>;
}

// ─────────────────────────────────────────────────────────────
// SCENE 4 — Cart: add another or finish
// ─────────────────────────────────────────────────────────────
function Scene4_AddOrDone({ state, actions }) {
  const total = state.cart.reduce((s, l) => s + l.price, 0);
  const remaining = Object.values(PRODUCTS).filter(p => !state.cart.some(c => c.id === p.id)).length;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <AppChrome title="Carrello" sub={`${state.cart.length} ${state.cart.length === 1 ? 'articolo' : 'articoli'}`} back={actions.back}/>
      <div style={{ padding: '14px 16px 8px' }}>
        <h2 style={{ margin: 0, fontSize: 18, fontWeight: 800, letterSpacing: '-0.015em' }}>L'ordine si compone in tempo reale</h2>
      </div>
      <div style={{ padding: '8px 16px', flex: 1, display: 'flex', flexDirection: 'column', gap: 8, overflowY: 'auto' }}>
        {state.cart.map((line, i) => (
          <div key={line.id} style={{
            display: 'flex', alignItems: 'center', gap: 10, padding: 10,
            background: '#fff', border: '1px solid var(--line-2)', borderRadius: 12,
            animation: `fadeIn .25s ${i*0.05}s both`,
          }}>
            <ProductPhoto product={PRODUCTS[line.id]} size={48} radius={8}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 700 }}>{line.name}</div>
              <div style={{ fontSize: 10, color: 'var(--ink-3)', fontWeight: 500 }}>SKU · {PRODUCTS[line.id].sku}</div>
            </div>
            <div style={{ fontSize: 14, fontWeight: 800, fontVariantNumeric: 'tabular-nums' }}>{eur(line.price)}</div>
          </div>
        ))}
        <div style={{
          marginTop: 4, padding: 12, borderRadius: 12,
          background: 'var(--paper)', border: '1px solid var(--line-2)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>Totale</div>
          <div style={{ fontSize: 22, fontWeight: 800, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.015em' }}>{eur(total)}</div>
        </div>
      </div>
      <div style={{ padding: '12px 16px calc(16px + 34px)', display: 'flex', flexDirection: 'column', gap: 8, borderTop: '1px solid var(--line-2)' }}>
        <PrimaryBtn onClick={actions.toCheckout} icon={<IconArrow size={16} stroke={2.2}/>}>Completa la vendita</PrimaryBtn>
        {remaining > 0 && (
          <PrimaryBtn onClick={actions.addAnother} secondary icon={<IconPlus size={15} stroke={2.4}/>}>
            Aggiungi un altro prodotto
          </PrimaryBtn>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// SCENE 5 — Checkout: manual shipping, % + € discount
// ─────────────────────────────────────────────────────────────
function Scene6_Checkout({ state, actions }) {
  const [delivery, setDelivery] = React.useState(null);
  const [shippingCostStr, setShippingCostStr] = React.useState('');
  const [discPctStr, setDiscPctStr] = React.useState('');
  const [discValStr, setDiscValStr] = React.useState('');

  const subtotal = state.cart.reduce((s, l) => s + l.price, 0);
  const shippingCost = parseFloat(shippingCostStr.replace(',', '.')) || 0;
  const discPct = parseFloat(discPctStr.replace(',', '.')) || 0;
  const discVal = parseFloat(discValStr.replace(',', '.')) || 0;
  const totalDiscount = (subtotal * discPct / 100) + discVal;
  const total = Math.max(0, subtotal - totalDiscount + shippingCost);

  const canProceed = delivery && (delivery !== 'ship' || shippingCost > 0);

  // When user picks a percentage, sync the value display; when they type value, leave pct alone
  const onPctChange = (v) => {
    setDiscPctStr(v);
    setDiscValStr('');
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <AppChrome title="Checkout" sub={`${state.cart.length} articoli · ${eur(subtotal)}`} back={actions.back}/>
      <div style={{ padding: '4px 16px 14px', flex: 1, overflowY: 'auto' }}>

        <SectionLabel>Articoli</SectionLabel>
        <div style={{
          background: '#fff', border: '1px solid var(--line-2)', borderRadius: 12,
          padding: 4, display: 'flex', flexDirection: 'column',
        }}>
          {state.cart.map((line, i) => (
            <div key={line.id} style={{
              display: 'flex', alignItems: 'center', gap: 10, padding: 8,
              borderBottom: i < state.cart.length - 1 ? '1px solid var(--line-2)' : 'none',
            }}>
              <ProductPhoto product={PRODUCTS[line.id]} size={36} radius={7}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12, fontWeight: 700 }}>{line.name}</div>
                <div style={{ fontSize: 10, color: 'var(--ink-3)' }}>SKU · {PRODUCTS[line.id].sku}</div>
              </div>
              <div style={{ fontSize: 12, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{eur(line.price)}</div>
            </div>
          ))}
        </div>

        <SectionLabel>Consegna</SectionLabel>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          <DeliveryOption active={delivery==='pickup'} onClick={() => setDelivery('pickup')} Icon={IconStore} title="Ritiro in negozio" meta="Gratuito"/>
          <DeliveryOption active={delivery==='ship'} onClick={() => setDelivery('ship')} Icon={IconTruck} title="Spedizione" meta="2–3 giorni"/>
        </div>
        {delivery === 'ship' && (
          <div style={{ marginTop: 8, animation: 'fadeIn .25s' }}>
            <InputRow label="Costo spedizione" prefix="€" value={shippingCostStr} onChange={setShippingCostStr} placeholder="0,00"/>
          </div>
        )}

        <SectionLabel>Sconto</SectionLabel>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          <InputRow label="Percentuale" suffix="%" value={discPctStr} onChange={onPctChange} placeholder="0"/>
          <InputRow label="Valore" prefix="€" value={discValStr} onChange={(v)=>{setDiscValStr(v); setDiscPctStr('');}} placeholder="0,00"/>
        </div>

        {/* Totals */}
        <div style={{
          marginTop: 16, padding: 14, borderRadius: 12, background: 'var(--navy)', color: '#fff',
          display: 'flex', flexDirection: 'column', gap: 6,
        }}>
          <TotalRow label="Subtotale" value={eur(subtotal)}/>
          {totalDiscount > 0 && <TotalRow label={`Sconto${discPct > 0 ? ` ${discPct}%` : ''}`} value={`− ${eur(totalDiscount)}`} accent="#9FE6C2"/>}
          {delivery === 'ship' && shippingCost > 0 && <TotalRow label="Spedizione" value={eur(shippingCost)}/>}
          {delivery === 'pickup' && <TotalRow label="Ritiro in negozio" value="Gratuito" muted/>}
          <div style={{ height: 1, background: 'rgba(255,255,255,.12)', margin: '4px 0' }}/>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', opacity: .7 }}>Totale</div>
            <div style={{ fontSize: 24, fontWeight: 800, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.02em' }}>{eur(total)}</div>
          </div>
        </div>
      </div>

      <div style={{ padding: '12px 16px calc(16px + 34px)', borderTop: '1px solid var(--line-2)' }}>
        <PrimaryBtn onClick={() => actions.toPayment({ delivery, shippingCost, discount: totalDiscount, total })} disabled={!canProceed} icon={<IconArrow size={16} stroke={2.2}/>}>
          Procedi al pagamento
        </PrimaryBtn>
      </div>
    </div>
  );
}

function InputRow({ label, prefix, suffix, value, onChange, placeholder }) {
  return (
    <div>
      <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 6 }}>{label}</div>
      <div style={{
        background: '#fff', border: '1px solid var(--line-2)', borderRadius: 10,
        padding: '8px 10px', display: 'flex', alignItems: 'center', gap: 6,
      }}>
        {prefix && <span style={{ color: 'var(--ink-3)', fontWeight: 700, fontSize: 13 }}>{prefix}</span>}
        <input value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder}
          style={{ border: 'none', outline: 'none', fontFamily: 'inherit', fontSize: 14, fontWeight: 700, color: 'var(--ink)', background: 'transparent', width: '100%', minWidth: 0, fontVariantNumeric: 'tabular-nums' }}/>
        {suffix && <span style={{ color: 'var(--ink-3)', fontWeight: 700, fontSize: 13 }}>{suffix}</span>}
      </div>
    </div>
  );
}

function DeliveryOption({ active, onClick, Icon, title, meta }) {
  return (
    <button onClick={onClick} style={{
      border: active ? '1.5px solid var(--blue)' : '1px solid var(--line-2)',
      background: active ? 'var(--blue-pale)' : '#fff',
      borderRadius: 12, padding: 10, cursor: 'pointer', textAlign: 'left',
      display: 'flex', flexDirection: 'column', gap: 4, fontFamily: 'inherit',
      boxShadow: active ? '0 0 0 3px rgba(30,120,200,.08)' : 'none',
    }}>
      <Icon size={16} stroke={1.8} color={active ? 'var(--blue)' : 'var(--ink-2)'}/>
      <div style={{ fontSize: 12, fontWeight: 700, marginTop: 4 }}>{title}</div>
      <div style={{ fontSize: 10, color: 'var(--ink-3)', fontWeight: 500 }}>{meta}</div>
    </button>
  );
}

function TotalRow({ label, value, muted, accent }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
      <span style={{ opacity: muted ? .6 : .8, fontWeight: 600 }}>{label}</span>
      <span style={{ color: accent || '#fff', fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{value}</span>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// SCENE 6 — Payment: brighter BNPL
// ─────────────────────────────────────────────────────────────
function Scene9_Payment({ state, actions }) {
  const [method, setMethod] = React.useState(null);
  const total = state.checkout.total;
  const installment = total / 3;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <AppChrome title="Pagamento" sub={`Totale ${eur(total)}`} back={actions.back}/>
      <div style={{ padding: '4px 16px 14px', flex: 1, overflowY: 'auto' }}>
        <div style={{ padding: '10px 0' }}>
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 800, letterSpacing: '-0.015em' }}>Scegli il metodo di pagamento</h2>
          <p style={{ margin: '4px 0 0', fontSize: 12, color: 'var(--ink-3)', fontWeight: 500 }}>
            Sarà disponibile per il cliente nel link.
          </p>
        </div>

        <SectionLabel>Standard</SectionLabel>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <PaymentOption active={method==='card'} onClick={() => setMethod('card')} Icon={IconCard} title="Carta di credito" sub="Visa · Mastercard · Amex"/>
          <PaymentOption active={method==='bank'} onClick={() => setMethod('bank')} Icon={IconBank} title="Bonifico bancario" sub="SEPA istantaneo"/>
        </div>

        <SectionLabel>Pagamento flessibile</SectionLabel>
        <button onClick={() => setMethod('bnpl')} style={{
          position: 'relative', width: '100%',
          border: '1.5px solid', borderColor: method==='bnpl' ? 'var(--blue)' : 'rgba(30,120,200,.4)',
          background: method==='bnpl'
            ? 'linear-gradient(135deg, #E8F1FA 0%, #D2E5F4 100%)'
            : 'linear-gradient(135deg, #F2F7FC 0%, #E8F1FA 100%)',
          color: 'var(--ink)',
          borderRadius: 14, padding: 14, cursor: 'pointer', textAlign: 'left',
          fontFamily: 'inherit', overflow: 'hidden',
          boxShadow: method==='bnpl' ? '0 6px 20px rgba(30,120,200,.20)' : '0 2px 8px rgba(30,120,200,.08)',
          transition: 'all .2s',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 38, height: 38, borderRadius: 10, background: 'var(--blue)', color: '#fff', display: 'grid', placeItems: 'center' }}>
              <IconSplit size={17} stroke={2}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <div style={{ fontSize: 14, fontWeight: 800 }}>Paga in 3 rate</div>
                <span style={{ fontSize: 9, fontWeight: 800, letterSpacing: '.06em', textTransform: 'uppercase', background: 'var(--blue)', color: '#fff', padding: '2px 6px', borderRadius: 999 }}>BNPL</span>
              </div>
              <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-2)', marginTop: 2 }}>
                3 × {eur(installment)} · senza interessi
              </div>
            </div>
            <div style={{ width: 20, height: 20, borderRadius: '50%',
              border: '1.5px solid var(--blue)',
              background: method==='bnpl' ? 'var(--blue)' : 'transparent',
              display: 'grid', placeItems: 'center' }}>
              {method==='bnpl' && <IconCheck size={12} color="#fff" stroke={3}/>}
            </div>
          </div>
          <div style={{ marginTop: 12, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
            {[0,1,2].map(i => (
              <div key={i} style={{ background: 'rgba(255,255,255,.7)', border: '1px solid rgba(30,120,200,.18)', borderRadius: 8, padding: '6px 8px' }}>
                <div style={{ fontSize: 9, fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>{i===0 ? 'Oggi' : `${i*30} gg`}</div>
                <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--ink)', fontVariantNumeric: 'tabular-nums' }}>{eur(installment)}</div>
              </div>
            ))}
          </div>
        </button>
      </div>
      <div style={{ padding: '12px 16px calc(16px + 34px)', borderTop: '1px solid var(--line-2)' }}>
        <PrimaryBtn onClick={() => actions.toCustomerData(method)} disabled={!method} icon={<IconArrow size={16} stroke={2.2}/>}>
          Conferma metodo
        </PrimaryBtn>
      </div>
    </div>
  );
}

function PaymentOption({ active, onClick, Icon, title, sub }) {
  return (
    <button onClick={onClick} style={{
      border: active ? '1.5px solid var(--blue)' : '1px solid var(--line-2)',
      background: active ? 'var(--blue-pale)' : '#fff',
      borderRadius: 12, padding: 10, cursor: 'pointer', textAlign: 'left',
      display: 'flex', alignItems: 'center', gap: 10, fontFamily: 'inherit',
    }}>
      <div style={{ width: 32, height: 32, borderRadius: 8, background: active ? 'var(--blue)' : 'var(--blue-pale)', color: active ? '#fff' : 'var(--blue)', display: 'grid', placeItems: 'center' }}>
        <Icon size={15} stroke={1.8}/>
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13, fontWeight: 700 }}>{title}</div>
        <div style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 500 }}>{sub}</div>
      </div>
      <div style={{ width: 20, height: 20, borderRadius: '50%', border: '1.5px solid', borderColor: active ? 'var(--blue)' : 'var(--line)', background: active ? 'var(--blue)' : 'transparent', display: 'grid', placeItems: 'center' }}>
        {active && <IconCheck size={12} color="#fff" stroke={3}/>}
      </div>
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// SCENE 7 — Customer data + link generation + channel choice
// ─────────────────────────────────────────────────────────────
function Scene7_Share({ state, actions }) {
  const [step, setStep] = React.useState('data'); // data → link → sent
  const [customer, setCustomer] = React.useState({ first: '', last: '', addr: '', city: '', cap: '', email: '', phone: '' });
  const [channel, setChannel] = React.useState(null);
  const orderId = '8F3KD9';
  const linkUrl = `mipaghi.it/ordine/${orderId}`;

  const set = (k) => (e) => setCustomer(c => ({ ...c, [k]: e.target.value }));
  // Tutti i campi sono FACOLTATIVI: il link può essere generato anche con form vuoto.

  // Demo helper: prefill
  const prefill = () => setCustomer({
    first: 'Giulia', last: 'Bianchi', addr: 'Via Brera 12', city: 'Milano', cap: '20121',
    email: 'giulia.bianchi@email.it', phone: '+39 333 1234567',
  });

  if (step === 'data') {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        <AppChrome title="Dati cliente" sub="Step 1 di 3 · Tutti i campi sono facoltativi" back={actions.back}
          right={<button onClick={prefill} style={{ border: 'none', background: 'transparent', color: 'var(--blue)', fontSize: 11, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>Compila demo</button>}/>
        <div style={{ padding: '12px 16px', flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 10 }}>
          <p style={{ margin: 0, fontSize: 12, color: 'var(--ink-3)', fontWeight: 500 }}>
            Inserisci i dati del cliente per personalizzare il link e la spedizione, oppure procedi senza compilare nulla — sono tutti opzionali.
          </p>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <FormField label="Nome" optional value={customer.first} onChange={set('first')} placeholder="Giulia"/>
            <FormField label="Cognome" optional value={customer.last} onChange={set('last')} placeholder="Bianchi"/>
          </div>
          <FormField label="Indirizzo" optional value={customer.addr} onChange={set('addr')} placeholder="Via, civico"/>
          <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 8 }}>
            <FormField label="Città" optional value={customer.city} onChange={set('city')} placeholder="Milano"/>
            <FormField label="CAP" optional value={customer.cap} onChange={set('cap')} placeholder="20121"/>
          </div>
          <FormField label="Email" optional value={customer.email} onChange={set('email')} placeholder="cliente@email.it" type="email"/>
          <FormField label="Telefono" optional value={customer.phone} onChange={set('phone')} placeholder="+39 …"/>
        </div>
        <div style={{ padding: '10px 16px calc(16px + 34px)', borderTop: '1px solid var(--line-2)' }}>
          <PrimaryBtn onClick={() => setStep('link')} icon={<IconArrow size={16} stroke={2.2}/>}>
            Genera link ordine
          </PrimaryBtn>
        </div>
      </div>
    );
  }

  if (step === 'link') {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        <AppChrome title="Link ordine" sub={`Step 2 di 3 · #${orderId}`} back={() => setStep('data')}/>
        <div style={{ padding: '12px 16px', flex: 1, overflowY: 'auto' }}>
          {/* Link card */}
          <div style={{
            background: 'linear-gradient(135deg, var(--navy), var(--navy-2))', color: '#fff',
            borderRadius: 14, padding: 14, marginBottom: 12, position: 'relative', overflow: 'hidden',
          }}>
            <div style={{ position: 'absolute', right: -20, top: -20, width: 90, height: 90, borderRadius: '50%', background: 'var(--blue)', opacity: .25 }}/>
            <div style={{ position: 'relative' }}>
              <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', opacity: .6, marginBottom: 6 }}>Link generato</div>
              <code style={{ fontSize: 12, fontWeight: 700, fontFamily: 'inherit' }}>{linkUrl}</code>
              <div style={{ marginTop: 10, display: 'flex', gap: 8, alignItems: 'center' }}>
                <button style={{ background: 'rgba(255,255,255,.14)', color: '#fff', border: 'none', borderRadius: 8, padding: '6px 10px', fontSize: 11, fontWeight: 700, fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
                  <IconCopy size={11} stroke={2}/> Copia link
                </button>
                <span style={{ fontSize: 11, fontWeight: 700,
                  background: state.payment === 'bnpl' ? 'var(--blue)' : 'rgba(255,255,255,.14)',
                  padding: '4px 8px', borderRadius: 999, display: 'flex', alignItems: 'center', gap: 4,
                }}>
                  {state.payment === 'bnpl' ? <><IconSplit size={11} stroke={2}/> BNPL</> :
                   state.payment === 'card' ? <><IconCard size={11} stroke={2}/> Carta</> : <><IconBank size={11} stroke={2}/> Bonifico</>}
                </span>
              </div>
            </div>
          </div>

          <div style={{ background: 'var(--paper)', border: '1px solid var(--line-2)', borderRadius: 10, padding: 10, marginBottom: 14 }}>
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 4 }}>Destinatario</div>
            {customer.first || customer.last
              ? <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ink)' }}>{[customer.first, customer.last].filter(Boolean).join(' ')}</div>
              : <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ink-3)', fontStyle: 'italic' }}>Cliente anonimo</div>}
            <div style={{ fontSize: 11, color: 'var(--ink-2)' }}>
              {[customer.email, customer.phone].filter(Boolean).join(' · ') || 'Nessun contatto inserito — invia il link manualmente'}
            </div>
          </div>

          <SectionLabel>Come vuoi inviarlo?</SectionLabel>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            <ChannelRow Icon={IconWA}   color="#25D366" title="WhatsApp" sub={customer.phone || 'Inserisci o copia il link manualmente'} disabled={!customer.phone} active={channel==='wa'}    onClick={() => customer.phone && setChannel('wa')}/>
            <ChannelRow Icon={IconMail} color="#1E78C8" title="Email"    sub={customer.email || 'Inserisci o copia il link manualmente'} disabled={!customer.email} active={channel==='email'} onClick={() => customer.email && setChannel('email')}/>
            <ChannelRow Icon={IconSMS}  color="#7A8A98" title="SMS"      sub={customer.phone || 'Inserisci o copia il link manualmente'} disabled={!customer.phone} active={channel==='sms'}   onClick={() => customer.phone && setChannel('sms')}/>
            <ChannelRow Icon={IconCopy} color="#0E2A3D" title="Copia link" sub="Incollalo in qualsiasi conversazione" active={channel==='copy'} onClick={() => setChannel('copy')}/>
          </div>
        </div>
        <div style={{ padding: '10px 16px calc(16px + 34px)', borderTop: '1px solid var(--line-2)' }}>
          <PrimaryBtn onClick={() => actions.sendLink(channel, customer)} disabled={!channel} icon={<IconArrow size={16} stroke={2.2}/>}>
            Invia al cliente
          </PrimaryBtn>
        </div>
      </div>
    );
  }
}

function FormField({ label, value, onChange, placeholder, type = 'text', optional }) {
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
        <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>{label}</span>
        {optional && <span style={{ fontSize: 9, fontWeight: 700, color: 'var(--ink-3)', opacity: .7, letterSpacing: '.05em' }}>opzionale</span>}
      </div>
      <input type={type} value={value} onChange={onChange} placeholder={placeholder}
        style={{
          width: '100%', border: '1px solid var(--line-2)', background: '#fff', borderRadius: 10,
          padding: '9px 11px', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, color: 'var(--ink)', outline: 'none',
          transition: 'border-color .15s',
        }}
        onFocus={e => e.target.style.borderColor = 'var(--blue)'}
        onBlur={e => e.target.style.borderColor = 'var(--line-2)'}/>
    </div>
  );
}

function ChannelRow({ Icon, color, title, sub, active, onClick, disabled }) {
  return (
    <button onClick={onClick} disabled={disabled} style={{
      border: active ? `1.5px solid ${color}` : '1px solid var(--line-2)',
      background: active ? color + '12' : '#fff',
      borderRadius: 12, padding: 10, cursor: disabled ? 'default' : 'pointer', textAlign: 'left',
      display: 'flex', alignItems: 'center', gap: 10, fontFamily: 'inherit',
      opacity: disabled ? .5 : 1,
    }}>
      <div style={{ width: 34, height: 34, borderRadius: 8, background: color + '20', color, display: 'grid', placeItems: 'center' }}>
        <Icon size={16} stroke={2}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 700 }}>{title}</div>
        <div style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{sub}</div>
      </div>
      <div style={{ width: 18, height: 18, borderRadius: '50%', border: '1.5px solid', borderColor: active ? color : 'var(--line)', background: active ? color : 'transparent', display: 'grid', placeItems: 'center' }}>
        {active && <IconCheck size={10} color="#fff" stroke={3}/>}
      </div>
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// SCENE 8 — Customer experience (channel-specific)
// ─────────────────────────────────────────────────────────────
function Scene8_Customer({ state, actions }) {
  const [view, setView] = React.useState('channel'); // channel → checkout → confirm
  const ch = state.channel;
  const installment = state.checkout.total / 3;
  const orderId = '8F3KD9';

  if (view === 'channel') {
    return <CustomerChannel state={state} ch={ch} orderId={orderId} onOpen={() => setView('checkout')} actions={actions}/>;
  }
  if (view === 'checkout') {
    return <CustomerCheckout state={state} orderId={orderId} onPay={() => setView('confirm')} actions={actions} onBack={() => setView('channel')}/>;
  }
  return <CustomerConfirm state={state} installment={installment} actions={actions} onContinue={() => actions.toBackoffice()}/>;
}

function CustomerChannel({ state, ch, orderId, onOpen, actions }) {
  // WhatsApp (chat) | Email (inbox) | SMS (Messages)
  if (ch === 'email') {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: '#fff' }}>
        <div style={{ padding: '8px 14px 10px', background: '#F2F2F7', display: 'flex', alignItems: 'center', gap: 10, borderBottom: '1px solid #E5E5EA' }}>
          <button onClick={actions.back} style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--blue)', fontSize: 12, fontWeight: 600, padding: 0 }}>‹ Inbox</button>
          <div style={{ marginLeft: 'auto', fontSize: 10, color: 'var(--ink-3)', fontWeight: 600 }}>vista cliente</div>
        </div>
        <div style={{ padding: 16 }}>
          <h3 style={{ margin: 0, fontSize: 17, fontWeight: 700, letterSpacing: '-0.01em' }}>Il tuo ordine è pronto</h3>
          <div style={{ marginTop: 6, fontSize: 11, color: 'var(--ink-3)', display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--navy)', color: '#fff', display: 'grid', placeItems: 'center', fontSize: 10, fontWeight: 700 }}>BS</div>
            <div>
              <div style={{ color: 'var(--ink)', fontSize: 12, fontWeight: 700 }}>Boutique Sienna</div>
              <div>noreply@mipaghi.it · oggi, 14:32</div>
            </div>
          </div>
          <p style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.55, marginTop: 18 }}>
            Ciao {state.customer?.first || 'Giulia'},<br/>
            grazie per essere passata da noi. Ho preparato l'ordine — puoi rivederlo e completarlo direttamente da questo link:
          </p>
          <a onClick={onOpen} style={{
            display: 'block', marginTop: 16, padding: 12,
            background: 'var(--blue-pale)', borderRadius: 10, color: 'var(--blue)',
            fontSize: 12, fontWeight: 700, cursor: 'pointer', textDecoration: 'none',
            border: '1px solid rgba(30,120,200,.2)',
          }}>
            mipaghi.it/ordine/{orderId}
          </a>
          <p style={{ fontSize: 11, color: 'var(--ink-3)', lineHeight: 1.5, marginTop: 16 }}>
            Il link scade in 48 ore. Per qualsiasi domanda, rispondi a questa email.<br/><br/>A presto,<br/>Boutique Sienna
          </p>
        </div>
      </div>
    );
  }
  if (ch === 'sms') {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: '#fff' }}>
        <div style={{ padding: '10px 14px 12px', borderBottom: '1px solid #E5E5EA', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
          <button onClick={actions.back} style={{ alignSelf: 'flex-start', border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--blue)', fontSize: 12, fontWeight: 600, padding: 0 }}>‹ Messaggi</button>
          <div style={{ width: 38, height: 38, borderRadius: '50%', background: 'var(--navy)', color: '#fff', display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 700 }}>BS</div>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Boutique Sienna</div>
        </div>
        <div style={{ flex: 1, padding: '14px 14px 14px', background: '#fff', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{ alignSelf: 'flex-start', maxWidth: '85%', background: '#E5E5EA', color: 'var(--ink)', padding: '8px 12px', borderRadius: 18, fontSize: 12, lineHeight: 1.4 }}>
            Ciao {state.customer?.first || 'Giulia'}! Il tuo ordine è pronto.
          </div>
          <div style={{ alignSelf: 'flex-start', maxWidth: '85%', background: '#E5E5EA', color: 'var(--ink)', padding: '8px 12px', borderRadius: 18, fontSize: 12, lineHeight: 1.4 }}>
            mipaghi.it/ordine/{orderId}
          </div>
          <button onClick={onOpen} style={{ marginTop: 6, alignSelf: 'flex-start', border: '1px solid var(--line)', background: '#fff', borderRadius: 12, padding: '8px 12px', fontSize: 11, fontWeight: 700, color: 'var(--blue)', cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 6 }}>
            Apri il link <IconArrow size={11} stroke={2.4}/>
          </button>
        </div>
      </div>
    );
  }
  // default WhatsApp
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ background: '#075E54', color: '#fff', padding: '8px 14px 12px', display: 'flex', alignItems: 'center', gap: 10 }}>
        <button onClick={actions.back} style={{ border: 'none', background: 'transparent', color: '#fff', cursor: 'pointer', padding: 0 }}><IconArrowL size={18} stroke={2}/></button>
        <div style={{ width: 30, height: 30, borderRadius: '50%', background: 'rgba(255,255,255,.18)', display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700 }}>BS</div>
        <div style={{ flex: 1, lineHeight: 1.1 }}>
          <div style={{ fontSize: 13, fontWeight: 700 }}>Boutique Sienna</div>
          <div style={{ fontSize: 10, opacity: .75 }}>online</div>
        </div>
        <div style={{ fontSize: 10, opacity: .65, fontWeight: 600 }}>vista cliente</div>
      </div>
      <div style={{ flex: 1, background: '#ECE5DD', padding: 14, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', gap: 6 }}>
        <div style={{ alignSelf: 'flex-start', maxWidth: '85%', background: '#fff', borderRadius: 12, padding: 10, fontSize: 12, color: 'var(--ink)', lineHeight: 1.4 }}>
          Ciao {state.customer?.first || 'Giulia'}, ecco il riepilogo dei prodotti che hai scelto.
        </div>
        <div style={{ alignSelf: 'flex-start', maxWidth: '90%', background: '#fff', borderRadius: 12, overflow: 'hidden' }}>
          <div style={{ background: 'linear-gradient(135deg, var(--navy), var(--navy-2))', color: '#fff', padding: 10 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><MiPaghiMark size={16}/> <span style={{ fontSize: 9, fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase', opacity: .7 }}>MiPaghi · Ordine</span></div>
            <div style={{ fontSize: 12, fontWeight: 700, marginTop: 4 }}>Riepilogo ordine #{orderId}</div>
            <div style={{ fontSize: 11, opacity: .8 }}>{state.cart.length} articoli · {eur(state.checkout.total)}</div>
          </div>
          <div style={{ padding: '6px 10px', fontSize: 11, color: 'var(--ink-3)' }}>mipaghi.it/ordine/{orderId}</div>
        </div>
        <button onClick={onOpen} style={{ alignSelf: 'flex-start', background: '#fff', border: '1px solid var(--line)', borderRadius: 12, padding: '8px 12px', fontSize: 11, fontWeight: 700, color: 'var(--blue)', cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 6 }}>
          Apri il link <IconArrow size={12} stroke={2.4}/>
        </button>
      </div>
    </div>
  );
}

function CustomerCheckout({ state, orderId, onPay, actions, onBack }) {
  const installment = state.checkout.total / 3;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: '#fff' }}>
      <div style={{ padding: '10px 14px', borderBottom: '1px solid var(--line-2)', display: 'flex', alignItems: 'center', gap: 10, background: 'var(--paper)' }}>
        <button onClick={onBack} style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 0 }}><IconArrowL size={18} stroke={2} color="var(--ink)"/></button>
        <MiPaghiMark size={20}/>
        <div style={{ fontSize: 12, fontWeight: 700 }}>Boutique Sienna</div>
        <div style={{ marginLeft: 'auto', fontSize: 10, color: 'var(--ink-3)', fontWeight: 600 }}>vista cliente</div>
      </div>
      <div style={{ padding: '14px 16px', flex: 1, overflowY: 'auto' }}>
        <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>Ordine #{orderId}</div>
        <h2 style={{ margin: '4px 0 14px', fontSize: 17, fontWeight: 800, letterSpacing: '-0.015em' }}>Conferma il tuo ordine</h2>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
          {state.cart.map((line, i) => (
            <div key={line.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 0', borderBottom: '1px solid var(--line-2)' }}>
              <ProductPhoto product={PRODUCTS[line.id]} size={48} radius={8}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12, fontWeight: 700 }}>{line.name}</div>
                <div style={{ fontSize: 10, color: 'var(--ink-3)' }}>{PRODUCTS[line.id].sub}</div>
              </div>
              <div style={{ fontSize: 12, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{eur(line.price)}</div>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 10, padding: '10px 0' }}>
          {state.checkout.delivery === 'ship' && state.checkout.shippingCost > 0 && (
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '4px 0', color: 'var(--ink-2)' }}>
              <span>Spedizione</span><span style={{ fontVariantNumeric: 'tabular-nums', fontWeight: 600 }}>{eur(state.checkout.shippingCost)}</span>
            </div>
          )}
          {state.checkout.delivery === 'pickup' && (
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '4px 0', color: 'var(--ink-2)' }}>
              <span>Ritiro in negozio</span><span style={{ fontWeight: 600 }}>Gratuito</span>
            </div>
          )}
          {state.checkout.discount > 0 && (
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '4px 0', color: 'var(--ok)' }}>
              <span>Sconto</span><span style={{ fontVariantNumeric: 'tabular-nums', fontWeight: 600 }}>− {eur(state.checkout.discount)}</span>
            </div>
          )}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 8, paddingTop: 10, borderTop: '1px solid var(--line-2)' }}>
            <span style={{ fontSize: 12, fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>Totale</span>
            <span style={{ fontSize: 22, fontWeight: 800, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.02em' }}>{eur(state.checkout.total)}</span>
          </div>
        </div>

        {state.payment === 'bnpl' && (
          <div style={{ marginTop: 10, padding: 12, borderRadius: 12, background: 'linear-gradient(135deg, #E8F1FA, #D2E5F4)', border: '1px solid rgba(30,120,200,.2)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
              <IconSplit size={14} stroke={2} color="var(--blue)"/>
              <div style={{ fontSize: 12, fontWeight: 800, color: 'var(--ink)' }}>Paga in 3 rate</div>
              <span style={{ fontSize: 9, fontWeight: 800, letterSpacing: '.06em', textTransform: 'uppercase', background: 'var(--blue)', color: '#fff', padding: '2px 6px', borderRadius: 999 }}>BNPL</span>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
              {[0,1,2].map(i => (
                <div key={i} style={{ background: 'rgba(255,255,255,.7)', borderRadius: 8, padding: '6px 8px' }}>
                  <div style={{ fontSize: 9, fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>{i===0 ? 'Oggi' : `${i*30} gg`}</div>
                  <div style={{ fontSize: 11, fontWeight: 800, fontVariantNumeric: 'tabular-nums' }}>{eur(installment)}</div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
      <div style={{ padding: '12px 16px calc(16px + 34px)', borderTop: '1px solid var(--line-2)' }}>
        <PrimaryBtn onClick={onPay} icon={<IconLock size={14} stroke={2}/>}>
          {state.payment === 'bnpl' ? 'Paga ora la prima rata' : 'Paga ora'}
        </PrimaryBtn>
      </div>
    </div>
  );
}

function CustomerConfirm({ state, installment, actions, onContinue }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', alignItems: 'center', justifyContent: 'center', padding: 22, background: '#fff' }}>
      <div style={{ position: 'relative', width: 76, height: 76, marginBottom: 18 }}>
        <div style={{ position: 'absolute', inset: 0, borderRadius: '50%', background: 'var(--blue)', opacity: .15, animation: 'ringPing 1.6s ease-out infinite' }}/>
        <div style={{ position: 'absolute', inset: 8, borderRadius: '50%', background: 'var(--blue)', display: 'grid', placeItems: 'center' }}>
          <IconCheck size={28} color="#fff" stroke={2.6}/>
        </div>
      </div>
      <div style={{ fontSize: 20, fontWeight: 800, letterSpacing: '-0.02em', marginBottom: 6 }}>Pagamento confermato</div>
      <div style={{ fontSize: 12, color: 'var(--ink-2)', textAlign: 'center', maxWidth: 260, lineHeight: 1.5, fontWeight: 500 }}>
        {state.payment === 'bnpl'
          ? <>Prima rata di <b>{eur(installment)}</b> autorizzata. Le prossime in automatico.</>
          : <>{eur(state.checkout.total)} incassati. Riconciliazione automatica nel backoffice.</>}
      </div>
      <div style={{ marginTop: 22, padding: '8px 12px', borderRadius: 999, background: 'var(--paper)', border: '1px solid var(--line-2)', display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{ width: 6, height: 6, borderRadius: 3, background: 'var(--ok)' }}/>
        <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-2)' }}>Stato: <b style={{ color: 'var(--ink)' }}>completato</b></span>
      </div>
      <div style={{ marginTop: 20, width: '100%' }}>
        <PrimaryBtn onClick={onContinue} icon={<IconArrow size={14} stroke={2.2}/>}>Vedi nel backoffice</PrimaryBtn>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// SCENE 9 — Backoffice dashboard (NEW)
// We render this directly into the device frame (looks like a tablet/phone backoffice app)
// ─────────────────────────────────────────────────────────────
function Scene9_Backoffice({ state, actions }) {
  const [tab, setTab] = React.useState('orders');
  const [dateFrom, setDateFrom] = React.useState('2026-05-01');
  const [dateTo, setDateTo] = React.useState('2026-05-04');
  const cust = state.customer || { first: 'Giulia', last: 'Bianchi' };
  const orders = [
    { id: '8F3KD9', who: `${cust.first} ${cust.last}`, items: state.cart.length, total: state.checkout.total, status: 'paid', method: state.payment, when: 'Adesso', isCurrent: true },
    { id: '7A1MR2', who: 'Marco Rossi', items: 2, total: 248.00, status: 'paid', method: 'card', when: 'Oggi · 12:18' },
    { id: '6B9PN5', who: 'Elena Conti', items: 1, total: 79.00, status: 'pending', method: 'bnpl', when: 'Oggi · 11:02' },
    { id: '5K2WD1', who: 'Davide Ferri', items: 3, total: 412.50, status: 'paid', method: 'bank', when: 'Ieri · 18:44' },
    { id: '4H7TR8', who: 'Anna De Luca', items: 1, total: 189.00, status: 'expired', method: 'card', when: 'Ieri · 09:21' },
  ];
  const totalToday = orders.filter(o => o.when.startsWith('Oggi') || o.isCurrent).reduce((s,o)=>s+o.total,0);
  const paidCount = orders.filter(o => o.status === 'paid').length;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: 'var(--paper)' }}>
      <div style={{ background: 'var(--navy)', color: '#fff', padding: '12px 16px 14px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <MiPaghiMark size={22}/>
            <div style={{ fontSize: 13, fontWeight: 800 }}>Backoffice</div>
          </div>
          <div style={{ width: 26, height: 26, borderRadius: '50%', background: 'rgba(255,255,255,.16)', display: 'grid', placeItems: 'center', fontSize: 10, fontWeight: 700 }}>BS</div>
        </div>
        <div style={{ marginTop: 14, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
          <Stat label="Incasso oggi" value={eur(totalToday)} accent="#9FE6C2"/>
          <Stat label="Ordini" value={String(orders.length)}/>
          <Stat label="Pagati" value={`${paidCount}/${orders.length}`}/>
        </div>
      </div>

      {/* Tab bar with date range filter on the same line */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 14px', gap: 8, borderBottom: '1px solid var(--line-2)', background: '#fff' }}>
        <div style={{ display: 'flex', gap: 14 }}>
          {['orders','team'].map(t => (
            <button key={t} onClick={() => setTab(t)} style={{
              border: 'none', background: 'transparent', cursor: 'pointer', fontFamily: 'inherit',
              padding: '10px 0', fontSize: 12, fontWeight: 700,
              color: tab === t ? 'var(--ink)' : 'var(--ink-3)',
              borderBottom: '2px solid', borderColor: tab === t ? 'var(--blue)' : 'transparent',
            }}>{t === 'orders' ? 'Ordini' : 'Operatori'}</button>
          ))}
        </div>
        {/* Date range — visible at all times */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '5px 6px', borderRadius: 8, background: 'var(--paper)', border: '1px solid var(--line-2)' }}>
          <DateChip value={dateFrom} onChange={setDateFrom} label="Da"/>
          <span style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 700 }}>→</span>
          <DateChip value={dateTo} onChange={setDateTo} label="A"/>
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 12px 12px' }}>
        {tab === 'orders' && orders.map((o, i) => (
          <OrderRow key={o.id} o={o} index={i}/>
        ))}
        {tab === 'team' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, paddingTop: 6 }}>
            {[
              { name: 'Sara Marchetti', role: 'Senior assistant', orders: 12, value: 2840, on: true },
              { name: 'Luca Bianchi', role: 'Sales associate', orders: 7, value: 1620, on: true },
              { name: 'Chiara Romano', role: 'Sales associate', orders: 5, value: 980, on: false },
            ].map((p, i) => (
              <div key={i} style={{ background: '#fff', border: '1px solid var(--line-2)', borderRadius: 12, padding: 10, display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--blue-pale)', color: 'var(--blue)', display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 800 }}>
                  {p.name.split(' ').map(s => s[0]).join('')}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <span style={{ fontSize: 12, fontWeight: 700 }}>{p.name}</span>
                    {p.on && <span style={{ width: 6, height: 6, borderRadius: 3, background: 'var(--ok)' }}/>}
                  </div>
                  <div style={{ fontSize: 10, color: 'var(--ink-3)' }}>{p.role} · {p.orders} ordini · {eur(p.value)}</div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      <div style={{ padding: '10px 16px calc(16px + 34px)', borderTop: '1px solid var(--line-2)', background: '#fff' }}>
        <PrimaryBtn onClick={actions.restart} secondary icon={<IconArrow size={14} stroke={2.2}/>}>
          Ricomincia la demo
        </PrimaryBtn>
      </div>
    </div>
  );
}

function Stat({ label, value, accent }) {
  return (
    <div style={{ background: 'rgba(255,255,255,.08)', border: '1px solid rgba(255,255,255,.10)', borderRadius: 10, padding: '8px 10px' }}>
      <div style={{ fontSize: 9, fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase', opacity: .65 }}>{label}</div>
      <div style={{ fontSize: 14, fontWeight: 800, color: accent || '#fff', marginTop: 2, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.01em' }}>{value}</div>
    </div>
  );
}

// Compact date chip: shows DD/MM and toggles a hidden native date input on click
function DateChip({ value, onChange, label }) {
  const ref = React.useRef(null);
  const display = value ? (() => {
    const [y,m,d] = value.split('-');
    return `${d}/${m}`;
  })() : '—';
  const open = () => {
    if (!ref.current) return;
    if (typeof ref.current.showPicker === 'function') ref.current.showPicker();
    else ref.current.click();
  };
  return (
    <button type="button" onClick={open} style={{
      border: 'none', background: '#fff', borderRadius: 6,
      padding: '4px 7px', fontFamily: 'inherit', cursor: 'pointer',
      display: 'flex', flexDirection: 'column', alignItems: 'flex-start', lineHeight: 1.05,
      boxShadow: 'inset 0 0 0 1px var(--line-2)', position: 'relative',
    }}>
      <span style={{ fontSize: 8, fontWeight: 700, color: 'var(--ink-3)', letterSpacing: '.08em', textTransform: 'uppercase' }}>{label}</span>
      <span style={{ fontSize: 11, fontWeight: 800, color: 'var(--ink)', fontVariantNumeric: 'tabular-nums' }}>{display}</span>
      <input ref={ref} type="date" value={value} onChange={e => onChange(e.target.value)}
        style={{ position: 'absolute', inset: 0, opacity: 0, width: '100%', height: '100%', cursor: 'pointer', border: 'none' }}/>
    </button>
  );
}

function OrderRow({ o, index }) {
  const statusColor = o.status === 'paid' ? 'var(--ok)' : o.status === 'pending' ? 'var(--warn)' : 'var(--ink-3)';
  const statusLabel = o.status === 'paid' ? 'Pagato' : o.status === 'pending' ? 'In attesa' : 'Scaduto';
  const methodLabel = o.method === 'bnpl' ? 'BNPL' : o.method === 'card' ? 'Carta' : 'Bonifico';
  return (
    <div style={{
      background: '#fff', border: o.isCurrent ? '1.5px solid var(--blue)' : '1px solid var(--line-2)',
      borderRadius: 12, padding: 10, marginBottom: 6,
      animation: `fadeIn .25s ${index*0.04}s both`,
      boxShadow: o.isCurrent ? '0 0 0 3px rgba(30,120,200,.10)' : 'none',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', minWidth: 38 }}>
          <div style={{ width: 6, height: 6, borderRadius: 3, background: statusColor }}/>
          <div style={{ fontSize: 9, fontWeight: 700, color: statusColor, marginTop: 4, letterSpacing: '.06em', textTransform: 'uppercase' }}>{statusLabel}</div>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ fontSize: 12, fontWeight: 700 }}>{o.who}</span>
            {o.isCurrent && <span style={{ fontSize: 9, fontWeight: 800, letterSpacing: '.06em', textTransform: 'uppercase', background: 'var(--blue)', color: '#fff', padding: '2px 5px', borderRadius: 4 }}>Nuovo</span>}
          </div>
          <div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 2 }}>
            #{o.id} · {o.items} {o.items === 1 ? 'articolo' : 'articoli'} · {methodLabel} · {o.when}
          </div>
        </div>
        <div style={{ fontSize: 13, fontWeight: 800, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.01em' }}>{eur(o.total)}</div>
      </div>
    </div>
  );
}

Object.assign(window, {
  PRODUCTS, eur, fmt,
  Scene0_Intro, Scene1_Pick, Scene2_Capture, Scene4_AddOrDone,
  Scene6_Checkout, Scene9_Payment, Scene7_Share, Scene8_Customer, Scene9_Backoffice,
});
