// Shell híbrido: en móvil ocupa todo el viewport (status bar del SO + safe-area).
// En desktop (≥900px), shell centrado con sidebar a la izquierda.

const { useState, useEffect } = React;

function ShopApp() {
  const app = useAppState();
  const [sheet, setSheet] = useState(null);
  const theme = getTheme(app.dark, app.themeId);
  const c = theme.c;

  // Bloquear el rebote/refresco al hacer pull-down en iOS (sólo móvil necesita)
  useEffect(() => {
    if (app.isDesktop) return;
    const onTouchMove = (e) => {
      if (e.target.closest && e.target.closest('.sl-scroll')) return;
      if (e.touches.length > 1) return;
      e.preventDefault?.();
    };
    document.addEventListener('touchmove', onTouchMove, { passive: false });
    return () => document.removeEventListener('touchmove', onTouchMove);
  }, [app.isDesktop]);

  const screen = (() => {
    switch (app.tab) {
      case 'list':     return <ListScreen     app={app} theme={theme} openSheet={setSheet} />;
      case 'shop':     return <ShopScreen     app={app} theme={theme} />;
      case 'lists':    return <ListsScreen    app={app} theme={theme} openSheet={setSheet} />;
      case 'history':  return <HistoryScreen  app={app} theme={theme} />;
      case 'settings': return <SettingsScreen app={app} theme={theme} openSheet={setSheet} />;
      default:         return <ListScreen     app={app} theme={theme} openSheet={setSheet} />;
    }
  })();

  if (app.isDesktop) {
    // Layout web: sidebar a la izquierda, contenido scrolleable a la derecha.
    return (
      <div className={app.animations ? '' : 'sl-no-anim'} style={{
        width: '100%', height: '100%',
        background: c.bg, color: c.ink,
        fontFamily: theme.fontBody,
        display: 'flex', justifyContent: 'center',
        overflow: 'hidden',
      }}>
        <div style={{
          width: '100%', maxWidth: 1280, height: '100%',
          display: 'flex', flexDirection: 'row',
          position: 'relative',
        }}>
          <Nav mode="desktop" theme={theme} tab={app.tab} setTab={app.setTab} t={app.t} hasBought={app.bought.length > 0} />
          <div style={{
            flex: 1, minWidth: 0, height: '100%',
            position: 'relative', overflow: 'hidden',
            display: 'flex', flexDirection: 'column',
          }}>
            {screen}
          </div>
          <AppSheets app={app} theme={theme} sheet={sheet} setSheet={setSheet} />
          <UndoToast app={app} theme={theme} />
        </div>
      </div>
    );
  }

  // Padding superior: safe-area-inset-top (notch/dynamic island en iOS, status bar Android)
  // + un mínimo razonable para que el contenido respire.
  const topInset = `max(env(safe-area-inset-top, 0px), ${PLATFORM === 'ios' ? '20px' : '12px'})`;

  return (
    <div className={app.animations ? '' : 'sl-no-anim'} style={{
      width: '100%', height: '100%', position: 'relative',
      background: c.bg, color: c.ink,
      fontFamily: theme.fontBody,
      overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        paddingTop: topInset,
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ flex: 1, minHeight: 0, position: 'relative' }}>
          {screen}
        </div>
      </div>

      {(app.tab === 'list' || app.tab === 'shop') && app.list && (
        <SmartInput app={app} theme={theme} />
      )}

      <Nav theme={theme} tab={app.tab} setTab={app.setTab} t={app.t} hasBought={app.bought.length > 0} />
      <AppSheets app={app} theme={theme} sheet={sheet} setSheet={setSheet} />
      <UndoToast app={app} theme={theme} />
    </div>
  );
}

// Toast de undo: aparece cuando app.recentlyDeleted está set. Auto-cierra a los
// 5s (controlado por el timer en core.jsx). Click en "Deshacer" restaura el
// item. Posición: encima del SmartInput / BottomNav en móvil, esquina inferior
// derecha en desktop. No bloquea otras interacciones.
function UndoToast({ app, theme }) {
  if (!app.recentlyDeleted) return null;
  const c = theme.c;
  const t = app.t;
  const name = app.recentlyDeleted.item?.name || '';
  const label = (t.deletedToast || 'Deleted "{name}"').replace('{name}', name);
  const isDesktop = app.isDesktop;
  const wrapperStyle = isDesktop
    ? { position: 'absolute', right: 24, bottom: 24, zIndex: 40 }
    : { position: 'absolute', left: 16, right: 16, bottom: 'calc(80px + env(safe-area-inset-bottom, 0px))', zIndex: 40, pointerEvents: 'none' };
  return (
    <div style={wrapperStyle}>
      <div className="sl-anim-slide" style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '12px 14px',
        background: c.ink, color: c.bg,
        borderRadius: theme.radius.lg,
        boxShadow: '0 10px 30px rgba(0,0,0,0.25)',
        fontFamily: theme.fontDisplay,
        maxWidth: isDesktop ? 380 : 'none',
        pointerEvents: 'auto',
      }}>
        <Icon name="trash" size={16} stroke={2.4} style={{ flexShrink: 0, opacity: 0.7 }} />
        <span style={{
          flex: 1, minWidth: 0, fontSize: 14, fontWeight: 600,
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        }}>{label}</span>
        <button onClick={app.restoreItem} style={{
          padding: '6px 12px', borderRadius: theme.radius.pill,
          background: c.accent, color: c.accentInk, border: 'none',
          fontSize: 13, fontWeight: 800, fontFamily: theme.fontDisplay,
          cursor: 'pointer', flexShrink: 0,
        }}>{t.undo || 'Undo'}</button>
        <button onClick={app.dismissDelete} aria-label="dismiss" style={{
          width: 28, height: 28, borderRadius: '50%',
          background: 'transparent', color: c.bg, border: 'none',
          cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
          opacity: 0.6, flexShrink: 0,
        }}><Icon name="x" size={16} stroke={2.4} /></button>
      </div>
    </div>
  );
}

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

window.ShopApp = ShopApp;
window.UndoToast = UndoToast;
