// MiPaghi · Beauty Corner — orchestrator
// Scene da components/scenes-beauty.jsx

const TWEAK_DEFAULTS_B = /*EDITMODE-BEGIN*/{
  "showBackdrop": true,
  "showSidePanel": true
}/*EDITMODE-END*/;

const SCENE_FLOW_B = [
  { id: 'auth',      short: 'Login',      label: 'Autenticazione addetta · store + PIN' },
  { id: 'corner',    short: 'Corner',     label: 'Dashboard iniziativa · nuova vendita' },
  { id: 'catalog',   short: 'Catalogo',   label: 'Prodotti corner + bundle' },
  { id: 'livephoto', short: 'Foto live',  label: 'Prodotto fuori corner' },
  { id: 'cart',      short: 'Carrello',   label: 'Omaggio a soglia · promo iniziativa' },
  { id: 'delivery',  short: 'Consegna',   label: 'Ritiro al corner / spedizione' },
  { id: 'payment',   short: 'Pagamento',  label: 'Carta, bonifico, BNPL' },
  { id: 'share',     short: 'Link',       label: 'Dati cliente · invio link' },
  { id: 'customer',  short: 'Cliente',    label: 'Esperienza cliente' },
  { id: 'backoffice',short: 'Backoffice', label: 'Report per store e addetta' },
];

const SIDE_COPY_B = {
  auth: {
    eyebrow: '01 · Autenticazione',
    title: 'Ogni vendita ha un volto e uno store.',
    body: 'L\u2019addetta si autentica con il proprio profilo e PIN. MiPaghi traccia venduto, store e venditrice: base per performance e reportistica filtrata.',
  },
  corner: {
    eyebrow: '02 · Il corner co-marketing',
    title: 'Uno stand brandizzato, uno strumento di vendita.',
    body: 'Iniziativa co-marketing LUMÉA Paris × MiPaghi: corner dedicato in-store, promo esclusive, omaggi a soglia. La vendita parte da qui — cliente al corner o remota.',
  },
  catalog: {
    eyebrow: '03 · Catalogo corner',
    title: 'Solari, creme, profumi e bundle pronti al tap.',
    body: 'Il corner ha un catalogo pre-caricato: prodotti singoli e bundle con omaggio. Per articoli fuori corner resta la foto live.',
  },
  livephoto: {
    eyebrow: '04 · Foto live',
    title: 'Fuori catalogo? Scatta e vendi.',
    body: 'La cliente chiede un prodotto non a scaffale del corner: foto, nome, prezzo. La riga ordine nasce comunque in pochi secondi.',
  },
  cart: {
    eyebrow: '05 · Carrello',
    title: 'Bundle, omaggi a soglia, promo iniziativa.',
    body: 'Superata la soglia scatta l\u2019omaggio; la promo \u221220% sui solari si applica con un tap. Meccaniche promozionali visibili e tracciate.',
  },
  delivery: {
    eyebrow: '06 · Consegna',
    title: 'Cliente al corner o a casa.',
    body: 'Ritiro immediato al corner oppure spedizione a domicilio per la clientela remota intercettata via social e WhatsApp.',
  },
  payment: {
    eyebrow: '07 · Pagamento',
    title: 'Carta, bonifico o 3 rate.',
    body: 'Il metodo viene proposto nel link. Il BNPL \u00e8 una scelta in pi\u00f9 per lo scontrino medio alto \u2014 profumi e routine complete.',
  },
  share: {
    eyebrow: '08 · Invio link',
    title: 'L\u2019ordine viaggia via WhatsApp, email o SMS.',
    body: 'Dati cliente facoltativi, link generato e tracciato su store e addetta. La vendita si chiude anche a distanza.',
  },
  customer: {
    eyebrow: '09 · Esperienza cliente',
    title: 'La cliente conferma dal proprio telefono.',
    body: 'Riepilogo con promo e omaggio ben visibili, pagamento in 30 secondi. La conferma rimbalza sul backoffice.',
  },
  backoffice: {
    eyebrow: '10 · Backoffice · solo admin',
    title: 'Il controllo è dell\u2019amministratore.',
    body: 'Report filtrati per store e per addetta, riservati al responsabile dell\u2019iniziativa. Ogni addetta vede solo le proprie vendite: qui l\u2019admin legge le performance complessive del co-marketing.',
  },
};

function AppBeauty() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS_B);
  const [scene, setScene] = React.useState('auth');
  const [staff, setStaff] = React.useState(null);
  const [store, setStore] = React.useState(null);
  const [saleMode, setSaleMode] = React.useState('local'); // local | remote
  const [cart, setCart] = React.useState([]);
  const [checkout, setCheckout] = React.useState({ delivery: null, shippingCost: 0, promoVal: 0, promoOn: true, gift: false, total: 0, totalAfterPromo: 0 });
  const [payment, setPayment] = React.useState(null);
  const [customer, setCustomer] = React.useState(null);
  const [channel, setChannel] = React.useState(null);

  const state = { scene, staff, store, saleMode, cart, checkout, payment, customer, channel };
  const order = SCENE_FLOW_B.map(s => s.id);

  const ensureDefaults = (target) => {
    const i = order.indexOf(target);
    if (i >= order.indexOf('corner') && !staff) {
      setStaff(STAFF_B[0]); setStore(STORES_B[0]);
    }
    if (i >= order.indexOf('cart') && cart.length === 0 && target !== 'catalog' && target !== 'livephoto') {
      setCart([
        { id: 'kitsolari', name: CATB.kitsolari.name, price: CATB.kitsolari.price },
        { id: 'parfum',    name: CATB.parfum.name,    price: CATB.parfum.price },
      ]);
    }
    if (i >= order.indexOf('delivery') && (!checkout.delivery || checkout.total === 0)) {
      const subtotal = (cart.length ? cart : [
        { id: 'kitsolari', price: CATB.kitsolari.price },
        { id: 'parfum', price: CATB.parfum.price },
      ]).reduce((s,l)=>s+l.price,0);
      const promoVal = CATB.kitsolari.price * 0.20;
      const after = subtotal - promoVal;
      setCheckout({ delivery: 'pickup', shippingCost: 0, promoOn: true, promoVal, gift: after >= GIFT_THRESHOLD_B, total: after, totalAfterPromo: after });
    }
    if (i >= order.indexOf('share') && !payment) setPayment('bnpl');
    if (i >= order.indexOf('customer') && (!customer || !channel)) {
      if (!customer) setCustomer({ first: 'Sofia', last: 'Greco', email: 'sofia.greco@email.it', phone: '+39 340 9876543' });
      if (!channel) setChannel('wa');
    }
  };

  const actions = {
    login: (st, sto) => { setStaff(st); setStore(sto); setScene('corner'); },
    startSale: (mode) => { setSaleMode(mode); setScene('catalog'); },
    pickItem: (id) => {
      const it = CATB[id];
      setCart(c => [...c, { id: it.id, name: it.name, price: it.price }]);
    },
    toLivePhoto: () => setScene('livephoto'),
    addCustomItem: (name, price) => {
      setCart(c => [...c, { id: 'custom-' + Date.now(), name, price }]);
      setScene('cart');
    },
    toCart: () => setScene('cart'),
    addAnother: () => setScene('catalog'),
    toDelivery: (info) => { setCheckout(k => ({ ...k, ...info })); setScene('delivery'); },
    toPayment: (info) => { setCheckout(k => ({ ...k, ...info })); setScene('payment'); },
    toShare: (method) => { setPayment(method); setScene('share'); },
    sendLink: (ch, cust) => { setChannel(ch); setCustomer(cust); setScene('customer'); },
    toBackoffice: () => setScene('backoffice'),
    back: () => {
      const i = order.indexOf(scene);
      if (i > 0) setScene(order[i - 1]);
    },
    restart: () => {
      setStaff(null); setStore(null); setSaleMode('local'); setCart([]);
      setCheckout({ delivery: null, shippingCost: 0, promoVal: 0, promoOn: true, gift: false, total: 0, totalAfterPromo: 0 });
      setPayment(null); setCustomer(null); setChannel(null);
      setScene('auth');
    },
    jumpTo: (id) => { ensureDefaults(id); setScene(id); },
  };

  let SceneEl = null;
  switch (scene) {
    case 'auth':       SceneEl = <B_Auth actions={actions}/>; break;
    case 'corner':     SceneEl = <B_Corner state={state} actions={actions}/>; break;
    case 'catalog':    SceneEl = <B_Catalog state={state} actions={actions}/>; break;
    case 'livephoto':  SceneEl = <B_LivePhoto state={state} actions={actions}/>; break;
    case 'cart':       SceneEl = <B_Cart state={state} actions={actions}/>; break;
    case 'delivery':   SceneEl = <B_Delivery state={state} actions={actions}/>; break;
    case 'payment':    SceneEl = <B_Payment state={state} actions={actions}/>; break;
    case 'share':      SceneEl = <B_Share state={state} actions={actions}/>; break;
    case 'customer':   SceneEl = <B_Customer state={state} actions={actions}/>; break;
    case 'backoffice': SceneEl = <B_Backoffice state={state} actions={actions}/>; break;
    default:           SceneEl = <B_Auth actions={actions}/>;
  }

  const stepIndex = Math.max(0, SCENE_FLOW_B.findIndex(s => s.id === scene));
  const isCustomer = scene === 'customer';
  const copy = SIDE_COPY_B[scene];
  const sceneNum = stepIndex + 1;

  // Ambientazioni stilizzate beauty (in attesa delle foto reali):
  // vendita = interno profumeria con stand brand; backoffice = ufficio responsabile beauty
  const beautyAmbience = `
    radial-gradient(700px 420px at 78% 18%, rgba(200,110,138,.45), transparent 60%),
    radial-gradient(560px 380px at 15% 85%, rgba(201,162,75,.35), transparent 60%),
    linear-gradient(165deg, #331B2A 0%, #14384F 62%, #0E2A3D 100%)`;
  const adminAmbience = `
    radial-gradient(700px 420px at 80% 15%, rgba(201,162,75,.30), transparent 60%),
    radial-gradient(500px 360px at 12% 88%, rgba(200,110,138,.22), transparent 60%),
    linear-gradient(165deg, #14384F 0%, #0E2A3D 85%)`;
  const asideBg = sceneNum === 10 ? adminAmbience : beautyAmbience;

  return (
    <div style={{
      width: '100vw', height: '100vh', position: 'relative',
      background: 'var(--cream)',
      display: 'grid',
      gridTemplateColumns: t.showSidePanel ? 'minmax(320px, 0.9fr) minmax(420px, 1fr)' : '1fr',
      overflow: 'hidden',
    }}>
      {t.showSidePanel && (
        <aside style={{
          padding: '40px 48px 32px', display: 'flex', flexDirection: 'column',
          minWidth: 0, position: 'relative', overflow: 'hidden',
          color: '#fff',
          background: asideBg,
          transition: 'background .4s',
        }}>
          {/* Foto di contesto: trascina qui l'immagine reale (addetta in profumeria / responsabile) */}
          <div style={{ position: 'absolute', inset: 0, zIndex: 0 }}>
            {sceneNum === 10 ? (
              <image-slot key="admin" id="foto-responsabile-beauty" shape="rect" fit="contain"
                src="assets/beauty-responsabile.webp"
                credit="Foto di Andrea Piacquadio su Pexels" credit-href="https://www.pexels.com/photo/woman-in-white-blazer-holding-tablet-computer-789822/"
                placeholder="Trascina qui la foto del responsabile commerciale (store beauty & parfum)"></image-slot>
            ) : (
              <image-slot key="vendita" id="foto-addetta-profumeria" shape="rect"
                src="assets/beauty-addetta.webp"
                credit="Foto di Arina Krasnikova su Pexels" credit-href="https://www.pexels.com/photo/boutique-saleswoman-giving-shopping-bags-to-a-customer-5424937/"
                placeholder="Trascina qui la foto dell'addetta nello store profumi/cosmetica"></image-slot>
            )}
          </div>
          {/* Overlay di leggibilità sopra la foto */}
          <div style={{ position: 'absolute', inset: 0, zIndex: 1, background: 'linear-gradient(180deg, rgba(14,42,61,.55) 0%, rgba(14,42,61,.35) 40%, rgba(14,42,61,.72) 100%)', pointerEvents: 'none' }}/>
          <div style={{ position: 'absolute', inset: 0, zIndex: 1, background: 'radial-gradient(80% 50% at 30% 60%, rgba(0,0,0,.25), transparent 70%)', pointerEvents: 'none' }}/>
          {/* Stand brand decorativo — simula il corner LUMÉA in negozio */}
          {sceneNum < 10 && (
            <div style={{
              position: 'absolute', right: 34, top: 104, zIndex: 1, pointerEvents: 'none',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, opacity: .8,
            }}>
              <div style={{
                padding: '14px 18px', borderRadius: 16,
                background: 'rgba(255,255,255,.07)', backdropFilter: 'blur(8px)',
                border: '1px solid rgba(255,255,255,.14)',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
              }}>
                <div style={{ fontSize: 15, fontWeight: 800, letterSpacing: '.28em', color: '#F2D8E1' }}>LUMÉA</div>
                <div style={{ fontSize: 8, fontWeight: 700, letterSpacing: '.30em', textTransform: 'uppercase', color: 'rgba(255,255,255,.55)', marginTop: -6 }}>Paris</div>
                <div style={{ display: 'flex', gap: 8, marginTop: 2 }}>
                  <BGlyph glyph="parfum" size={34} radius={9}/>
                  <BGlyph glyph="sun" size={34} radius={9}/>
                  <BGlyph glyph="cream" size={34} radius={9}/>
                </div>
                <div style={{ width: '100%', height: 3, borderRadius: 2, background: 'linear-gradient(90deg, rgba(201,162,75,.8), rgba(200,110,138,.8))' }}/>
              </div>
              <div style={{ fontSize: 8.5, fontWeight: 700, letterSpacing: '.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,.5)' }}>Corner in-store</div>
            </div>
          )}
          {sceneNum === 10 && (
            <div style={{
              position: 'absolute', right: 34, top: 104, zIndex: 1, pointerEvents: 'none',
              padding: '12px 16px', borderRadius: 14,
              background: 'rgba(255,255,255,.07)', backdropFilter: 'blur(8px)',
              border: '1px solid rgba(255,255,255,.14)',
              display: 'flex', alignItems: 'center', gap: 10, opacity: .9,
            }}>
              <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--gold)', color: '#fff', display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 800 }}>RC</div>
              <div>
                <div style={{ fontSize: 12, fontWeight: 800, color: '#fff' }}>Resp. commerciale</div>
                <div style={{ fontSize: 9.5, fontWeight: 600, color: 'rgba(255,255,255,.6)' }}>Beauty & Parfum · admin</div>
              </div>
            </div>
          )}

          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 'auto', position: 'relative', zIndex: 2 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <MiPaghiMark size={32}/>
              <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.1 }}>
                <span style={{ fontWeight: 800, fontSize: 16, letterSpacing: '-0.01em', color: '#fff' }}>MiPaghi <span style={{ opacity: .55, fontWeight: 600 }}>×</span> <span style={{ letterSpacing: '.14em', color: '#F2D8E1' }}>LUMÉA</span></span>
                <span style={{ fontSize: 11, color: 'rgba(255,255,255,.65)', fontWeight: 600, letterSpacing: '.04em' }}>Beauty Corner · iniziativa co-marketing</span>
              </div>
            </div>
            <div style={{
              padding: '6px 12px', borderRadius: 999,
              background: 'rgba(255,255,255,.14)', backdropFilter: 'blur(10px)',
              border: '1px solid rgba(255,255,255,.18)', fontSize: 11, fontWeight: 700, color: '#fff',
              fontVariantNumeric: 'tabular-nums',
            }}>
              {String(stepIndex + 1).padStart(2,'0')} / {String(SCENE_FLOW_B.length).padStart(2,'0')}
            </div>
          </div>

          <div key={scene} style={{
            animation: 'fadeIn .35s ease both', maxWidth: 390, position: 'relative', zIndex: 2,
            background: 'rgba(14,42,61,.55)', backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)',
            borderRadius: 18, padding: '20px 22px', marginLeft: -22,
            border: '1px solid rgba(255,255,255,.08)',
          }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.16em', textTransform: 'uppercase', color: '#9FC5E8', marginBottom: 14 }}>
              {copy.eyebrow}
            </div>
            <h1 style={{
              margin: 0, fontSize: 'clamp(22px, 2.2vw, 28px)', fontWeight: 800,
              lineHeight: 1.1, letterSpacing: '-0.025em', color: '#fff',
              textWrap: 'pretty', textShadow: '0 2px 24px rgba(0,0,0,.35)',
              maxWidth: '11.7em',
            }}>
              {copy.title}
            </h1>
            <p style={{
              margin: '18px 0 0', fontSize: 'clamp(13px, 1vw, 15px)', lineHeight: 1.55,
              color: 'rgba(255,255,255,.85)', fontWeight: 500, maxWidth: 440,
              textShadow: '0 1px 12px rgba(0,0,0,.30)',
            }}>
              {copy.body}
            </p>
          </div>

          <div style={{ marginTop: 36, position: 'relative', zIndex: 2 }}>
            <div style={{ display: 'flex', gap: 4, marginBottom: 14 }}>
              {SCENE_FLOW_B.map((s, i) => (
                <div key={s.id} style={{
                  flex: 1, height: 3, borderRadius: 2,
                  background: i <= stepIndex ? '#fff' : 'rgba(255,255,255,.18)',
                  transition: 'background .3s',
                }}/>
              ))}
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
              {SCENE_FLOW_B.map((s, i) => (
                <button key={s.id} onClick={() => actions.jumpTo(s.id)} style={{
                  cursor: 'pointer', fontFamily: 'inherit',
                  background: s.id === scene ? '#fff' : 'rgba(255,255,255,.10)',
                  color: s.id === scene ? 'var(--navy)' : 'rgba(255,255,255,.85)',
                  padding: '5px 9px', borderRadius: 999, fontSize: 10.5, fontWeight: 700,
                  border: '1px solid', borderColor: s.id === scene ? '#fff' : 'rgba(255,255,255,.20)',
                  backdropFilter: 'blur(6px)',
                  transition: 'all .15s', fontVariantNumeric: 'tabular-nums',
                }} title={s.label}>
                  <span style={{ opacity: .55, marginRight: 5 }}>{String(i+1).padStart(2,'0')}</span>
                  {s.short}
                </button>
              ))}
            </div>
          </div>
        </aside>
      )}

      <main style={{
        position: 'relative', display: 'grid', placeItems: 'center', minWidth: 0,
        padding: '40px 24px',
        background: '#0E2A3D',
        overflow: 'hidden',
      }}>
        {t.showBackdrop && <BeautyBackdrop bg={asideBg}/>}

        <div style={{ position: 'relative', zIndex: 2, transform: 'scale(.92)' }}>
          <IOSDevice width={390} height={780}>
            {(() => {
              const fullBleed = scene === 'livephoto';
              return (
                <div style={{
                  width: '100%', height: '100%',
                  background: '#fff',
                  display: 'flex', flexDirection: 'column',
                  position: 'relative', overflow: 'hidden',
                  fontFamily: 'inherit',
                  paddingTop: fullBleed ? 0 : 48,
                }}>
                  <div key={scene} style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}
                       data-screen-label={`${String(stepIndex+1).padStart(2,'0')} ${SCENE_FLOW_B[stepIndex]?.short || scene}`}>
                    {SceneEl}
                  </div>
                </div>
              );
            })()}
          </IOSDevice>
        </div>

        <div style={{
          position: 'absolute', bottom: 20, left: '50%', transform: 'translateX(-50%)',
          padding: '6px 12px', borderRadius: 999, background: 'rgba(255,255,255,.85)',
          backdropFilter: 'blur(8px)', border: '1px solid rgba(14,42,61,.08)',
          fontSize: 10, fontWeight: 700, color: 'var(--ink-2)',
          letterSpacing: '.1em', textTransform: 'uppercase',
          display: 'flex', alignItems: 'center', gap: 6, zIndex: 3,
        }}>
          <div style={{ width: 6, height: 6, borderRadius: 3, background: isCustomer ? '#25D366' : 'var(--blue)' }}/>
          {isCustomer ? 'Smartphone cliente' : 'Smartphone addetta'}
        </div>
      </main>

      <TweaksPanel title="Demo · Tweaks">
        <TweakSection label="Aspetto">
          <TweakToggle label="Sfondo contesto" value={t.showBackdrop} onChange={v => setTweak('showBackdrop', v)}/>
          <TweakToggle label="Pannello narrativo" value={t.showSidePanel} onChange={v => setTweak('showSidePanel', v)}/>
        </TweakSection>
        <TweakSection label="Navigazione demo">
          <TweakSelect
            label="Vai a scena"
            value={scene}
            options={SCENE_FLOW_B.map((s, i) => ({ value: s.id, label: `${String(i+1).padStart(2,'0')} · ${s.short}` }))}
            onChange={v => actions.jumpTo(v)}
          />
          <TweakButton label="Ricomincia demo" onClick={actions.restart}/>
          <TweakButton label="Pre-popola → Pagamento" secondary onClick={() => {
            actions.jumpTo('payment');
          }}/>
          <TweakButton label="Pre-popola → Backoffice" secondary onClick={() => {
            actions.jumpTo('backoffice');
          }}/>
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

// Backdrop sfumato dietro al telefono (stessa ambientazione del pannello)
function BeautyBackdrop({ bg }) {
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 1, pointerEvents: 'none', overflow: 'hidden' }}>
      <div style={{
        position: 'absolute', inset: -20,
        background: bg,
        transform: 'scale(1.1)',
        opacity: 0.95,
        transition: 'background .4s',
      }}/>
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(14,42,61,.35), rgba(14,42,61,.15) 50%, rgba(14,42,61,.45))' }}/>
      <div style={{
        position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%, -50%)',
        width: 520, height: 520, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(255,255,255,.18), transparent 60%)',
      }}/>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<AppBeauty/>);
