// Pantalla MODO COMPRA (Bubblegum) — one-handed, targets gigantes
// Layouts: mega (cards enormes) y grid (2 col). Sin swipe.
// Confeti solo cuando se compra el último item, autodestruye al terminar la animación.

function ShopScreen({ app, theme }) {
  const c = theme.c;
  const t = app.t;
  if (!app.list) return <NoListEmptyState app={app} theme={theme} />;
  const isDesktop = app.isDesktop;
  const [confettiKey, setConfettiKey] = React.useState(0);
  const layout = app.shopLayout === 'grid' ? 'grid' : 'mega';
  const innerMax = isDesktop ? 1080 : '100%';
  const megaMax = isDesktop ? 720 : '100%';
  const sidePad = isDesktop ? 32 : 22;
  const bottomPad = isDesktop ? 32 : 220;

  const pending = app.pending;
  const bought  = app.bought;
  const total   = pending.length + bought.length;
  const progress = total === 0 ? 0 : bought.length / total;

  // Anima el item recién toqueado (~400ms): bounce del card + stamp del check +
  // ripple verde. Se limpia solo tras la animación. animations=false → no-op.
  const [tappedId, setTappedId] = React.useState(null);
  const tapClearRef = React.useRef(null);
  function flashTap(id) {
    if (!app.animations) return;
    setTappedId(id);
    clearTimeout(tapClearRef.current);
    tapClearRef.current = setTimeout(() => setTappedId(null), 450);
  }
  React.useEffect(() => () => clearTimeout(tapClearRef.current), []);

  // Agrupar items pendientes por categoría preservando el orden de inserción
  // (el primer item de cada categoría marca el orden de aparición del grupo).
  const pendingByCat = React.useMemo(() => {
    const groups = new Map();
    for (const it of pending) {
      const k = it.category || 'otros';
      if (!groups.has(k)) groups.set(k, []);
      groups.get(k).push(it);
    }
    return Array.from(groups.entries()); // [[catKey, items[]], ...]
  }, [pending]);

  function tap(id) {
    const wasLast = pending.length === 1 && pending[0].id === id;
    const target = (app.items || []).find(i => i.id === id);
    const becomingChecked = target && !target.is_purchased;
    app.togglePurchased(id);
    if (becomingChecked) flashTap(id);
    if (app.animations && wasLast) setConfettiKey(k => k + 1);
    if (navigator.vibrate) navigator.vibrate(8);
  }

  function MegaItem({ item }) {
    const cat = CATEGORIES[item.category] || CATEGORIES.otros;
    const checked = item.is_purchased;
    const justTapped = tappedId === item.id;
    return (
      <button
        onClick={() => tap(item.id)}
        className={justTapped ? 'sl-anim-tap-bounce' : ''}
        style={{
          width: '100%', textAlign: 'left',
          display: 'flex', alignItems: 'center', gap: 14,
          padding: '20px 18px', minHeight: 84,
          background: checked ? c.bg : c.bgCard,
          border: `1px solid ${c.border}`,
          borderRadius: theme.radius.xl,
          boxShadow: checked ? 'none' : c.shadowSoft,
          cursor: 'pointer', position: 'relative', overflow: 'hidden',
          transform: checked ? 'scale(.985)' : 'scale(1)',
          transition: 'all .22s cubic-bezier(.2,.9,.3,1)',
          fontFamily: theme.fontBody,
        }}
      >
        <div style={{
          width: 52, height: 52, borderRadius: theme.radius.lg,
          background: checked ? c.success : c.bg,
          border: `2.5px solid ${checked ? c.success : c.borderStrong}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
          transform: checked ? 'rotate(-6deg)' : 'rotate(0)',
          transition: 'all .22s cubic-bezier(.2,1.4,.4,1)',
          fontSize: 26, lineHeight: 1,
          // Asegura que los iconos (Material/line) hereden el color del
          // tema, no negro por defecto. Crítico en modo oscuro.
          color: checked ? '#fff' : c.ink,
          position: 'relative',
        }}>
          {checked
            ? <Icon key={`chk-${item.id}-${justTapped}`} className={justTapped ? 'sl-anim-stamp' : ''} name="check" size={28} stroke={3} style={{ color: '#fff' }} />
            : <CatGlyph cat={cat} size={26} stroke={2.2} />}
          {justTapped && checked && (
            <span className="sl-anim-ripple" style={{
              position: 'absolute', inset: -6, borderRadius: theme.radius.lg,
              background: c.success, pointerEvents: 'none',
            }} />
          )}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontSize: 22, fontWeight: 800, fontFamily: theme.fontDisplay,
            color: c.ink, opacity: checked ? 0.45 : 1,
            textDecoration: checked ? 'line-through' : 'none',
            textDecorationThickness: '2.5px',
            lineHeight: 1.15,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{item.name}</div>
          {item.quantity && (
            <div style={{
              fontSize: 13, color: c.inkSub, fontFamily: theme.fontMono,
              marginTop: 4, opacity: checked ? 0.5 : 1,
            }}>{item.quantity}</div>
          )}
        </div>
      </button>
    );
  }

  function GridItem({ item }) {
    const cat = CATEGORIES[item.category] || CATEGORIES.otros;
    const checked = item.is_purchased;
    const justTapped = tappedId === item.id;
    return (
      <button
        onClick={() => tap(item.id)}
        className={justTapped ? 'sl-anim-tap-bounce' : ''}
        style={{
          aspectRatio: '1', textAlign: 'left',
          display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
          padding: 16,
          background: checked ? c.bg : c.bgCard,
          border: `1px solid ${c.border}`,
          borderRadius: theme.radius.xl,
          boxShadow: checked ? 'none' : c.shadowSoft,
          cursor: 'pointer', position: 'relative',
          transform: checked ? 'scale(.96) rotate(-1deg)' : 'scale(1)',
          transition: 'all .22s',
        }}
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <CatGlyph cat={cat} size={28} stroke={2.2} style={{ color: c.ink }} />
          <div style={{
            width: 36, height: 36, borderRadius: '50%',
            background: checked ? c.success : 'transparent',
            border: `2.5px solid ${checked ? c.success : c.borderStrong}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            position: 'relative',
          }}>
            {checked && (
              <Icon key={`chk-${item.id}-${justTapped}`} className={justTapped ? 'sl-anim-stamp' : ''}
                name="check" size={20} stroke={3} style={{ color: '#fff' }} />
            )}
            {justTapped && checked && (
              <span className="sl-anim-ripple" style={{
                position: 'absolute', inset: -4, borderRadius: '50%',
                background: c.success, pointerEvents: 'none',
              }} />
            )}
          </div>
        </div>
        <div>
          <div style={{
            fontSize: 17, fontWeight: 800, fontFamily: theme.fontDisplay,
            color: c.ink, opacity: checked ? 0.45 : 1,
            textDecoration: checked ? 'line-through' : 'none',
            lineHeight: 1.15,
          }}>{item.name}</div>
          {item.quantity && <div style={{
            fontSize: 11, color: c.inkSub, fontFamily: theme.fontMono, marginTop: 4,
          }}>{item.quantity}</div>}
        </div>
      </button>
    );
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: c.bg, position: 'relative' }}>
      <div style={{
        padding: `${isDesktop ? 24 : 8}px ${sidePad}px 0`,
        maxWidth: innerMax, margin: '0 auto', width: '100%', boxSizing: 'border-box',
      }}>
        <div style={{
          fontSize: 12, fontWeight: 700, color: c.inkSub,
          textTransform: 'uppercase', letterSpacing: 1.5,
          fontFamily: theme.fontMono, marginBottom: 4,
        }}>
          {app.lang === 'es' ? 'En el súper' : 'Shopping'} · {app.list.name[app.lang]}
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, flexWrap: 'wrap' }}>
          <span style={{
            fontSize: 56, lineHeight: 0.9, fontWeight: 800,
            fontFamily: theme.fontDisplay, color: c.ink, letterSpacing: -2.5,
          }}>{bought.length}</span>
          <span style={{
            fontSize: 22, color: c.inkMuted, fontWeight: 600,
            fontFamily: theme.fontDisplay,
          }}>/ {total}</span>
          <div style={{ flex: 1 }} />
          <ChipBadge theme={theme} color={c.accent}>{Math.round(progress * 100)}%</ChipBadge>
        </div>
        <div style={{
          marginTop: 14, height: 14, background: c.border,
          borderRadius: 999, overflow: 'hidden',
        }}>
          <div style={{
            height: '100%', width: `${progress * 100}%`,
            background: c.success, borderRadius: 999,
            transition: 'width .4s cubic-bezier(.2,1.2,.3,1)',
            position: 'relative', overflow: 'hidden',
          }}>
            {progress > 0 && progress < 1 && app.animations && (
              <div style={{
                position: 'absolute', inset: 0,
                background: 'linear-gradient(90deg, transparent, rgba(255,255,255,0.5), transparent)',
                animation: 'sl-sweep 2s linear infinite',
              }} />
            )}
          </div>
        </div>
      </div>

      <div className="sl-scroll" style={{
        flex: 1, overflow: 'auto',
        padding: `20px ${sidePad}px ${bottomPad}px`,
      }}>
        <div style={{ maxWidth: innerMax, margin: '0 auto', width: '100%' }}>
          {isDesktop && (
            <div style={{ maxWidth: megaMax, margin: '0 auto 12px' }}>
              <SmartInput app={app} theme={theme} placement="inline" />
            </div>
          )}
          {pending.length === 0 && bought.length === 0 ? (
            <EmptyState theme={theme} big="🛒" title={t.emptyShop} sub={t.emptyShopSub} />
          ) : pending.length === 0 ? (
            <div style={{ display: 'flex', flexDirection: 'column', maxWidth: megaMax, margin: '0 auto' }}>
              <div style={{ paddingTop: 40, paddingBottom: 24, textAlign: 'center' }}>
                <div style={{ fontSize: 80, marginBottom: 14 }}>🎉</div>
                <div style={{ fontSize: 28, fontWeight: 800, fontFamily: theme.fontDisplay, color: c.ink, marginBottom: 8 }}>
                  {app.lang === 'es' ? '¡Todo comprado!' : 'All done!'}
                </div>
                <div style={{ fontSize: 15, color: c.inkSub, marginBottom: 24, fontFamily: theme.fontBody }}>
                  {app.lang === 'es' ? 'Buen trabajo. Limpia y a casa.' : 'Nice work. Clear and head home.'}
                </div>
                <Btn theme={theme} variant="solid" size="lg" icon="check" onClick={app.clearBought}>
                  {t.clearBought} ({bought.length})
                </Btn>
              </div>
              {/* Lista de comprados visible para poder desmarcar antes de limpiar. */}
              <div style={{
                marginTop: 4, marginBottom: 8, padding: '0 4px',
                fontSize: 11, fontWeight: 700, color: c.inkMuted,
                textTransform: 'uppercase', letterSpacing: 1.5,
                fontFamily: theme.fontMono,
                display: 'flex', alignItems: 'center', gap: 8,
              }}>
                <span style={{ textTransform: 'none' }}>✓ {t.bought_one.charAt(0).toUpperCase() + t.bought_one.slice(1)} · {bought.length}</span>
                <div style={{ flex: 1, height: 1, background: c.border }} />
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {bought.map(it => <MegaItem key={it.id} item={it} />)}
              </div>
            </div>
          ) : layout === 'mega' ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxWidth: megaMax, margin: '0 auto' }}>
              {pendingByCat.map(([catKey, items]) => {
                const cat = CATEGORIES[catKey] || CATEGORIES.otros;
                const label = (t.cats && t.cats[catKey]) || (CATEGORIES[catKey] && catKey) || (app.lang === 'es' ? 'Otros' : 'Other');
                return (
                  <React.Fragment key={catKey}>
                    <div style={{
                      marginTop: 8, marginBottom: 2, padding: '0 4px',
                      fontSize: 11, fontWeight: 700, color: c.inkMuted,
                      textTransform: 'uppercase', letterSpacing: 1.5,
                      fontFamily: theme.fontMono,
                      display: 'flex', alignItems: 'center', gap: 8,
                    }}>
                      <CatGlyph cat={cat} size={14} stroke={2.2} />
                      <span>{label}</span>
                      <div style={{ flex: 1, height: 1, background: c.border }} />
                      <span>{items.length}</span>
                    </div>
                    {items.map(it => <MegaItem key={it.id} item={it} />)}
                  </React.Fragment>
                );
              })}
              {bought.length > 0 && (
                <>
                  <div style={{
                    marginTop: 14, marginBottom: 4, padding: '0 4px',
                    fontSize: 11, fontWeight: 700, color: c.inkMuted,
                    textTransform: 'uppercase', letterSpacing: 1.5,
                    fontFamily: theme.fontMono,
                    display: 'flex', alignItems: 'center', gap: 8,
                  }}>
                    <span style={{ textTransform: 'none' }}>✓ {t.bought_one.charAt(0).toUpperCase() + t.bought_one.slice(1)} · {bought.length}</span>
                    <div style={{ flex: 1, height: 1, background: c.border }} />
                    {isDesktop && (
                      <button onClick={app.clearBought} style={{
                        background: 'transparent', border: 'none', color: c.inkSub,
                        fontFamily: theme.fontMono, fontSize: 11, fontWeight: 700,
                        letterSpacing: 1.5, cursor: 'pointer', padding: 0,
                        textTransform: 'uppercase',
                      }}>{app.lang === 'es' ? 'LIMPIAR' : 'CLEAR'}</button>
                    )}
                  </div>
                  {bought.map(it => <MegaItem key={it.id} item={it} />)}
                </>
              )}
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              {pendingByCat.map(([catKey, items]) => {
                const cat = CATEGORIES[catKey] || CATEGORIES.otros;
                const label = (t.cats && t.cats[catKey]) || (CATEGORIES[catKey] && catKey) || (app.lang === 'es' ? 'Otros' : 'Other');
                return (
                  <div key={catKey}>
                    <div style={{
                      marginBottom: 10, padding: '0 4px',
                      fontSize: 11, fontWeight: 700, color: c.inkMuted,
                      textTransform: 'uppercase', letterSpacing: 1.5,
                      fontFamily: theme.fontMono,
                      display: 'flex', alignItems: 'center', gap: 8,
                    }}>
                      <CatGlyph cat={cat} size={14} stroke={2.2} />
                      <span>{label}</span>
                      <div style={{ flex: 1, height: 1, background: c.border }} />
                      <span>{items.length}</span>
                    </div>
                    <div style={{
                      display: 'grid',
                      gridTemplateColumns: isDesktop ? 'repeat(auto-fill, minmax(220px, 1fr))' : '1fr 1fr',
                      gap: 10,
                    }}>
                      {items.map(it => <GridItem key={it.id} item={it} />)}
                    </div>
                  </div>
                );
              })}
              {bought.length > 0 && (
                <div>
                  <div style={{
                    marginBottom: 10, padding: '0 4px',
                    fontSize: 11, fontWeight: 700, color: c.inkMuted,
                    textTransform: 'uppercase', letterSpacing: 1.5,
                    fontFamily: theme.fontMono,
                    display: 'flex', alignItems: 'center', gap: 8,
                  }}>
                    <span style={{ textTransform: 'none' }}>✓ {t.bought_one.charAt(0).toUpperCase() + t.bought_one.slice(1)}</span>
                    <div style={{ flex: 1, height: 1, background: c.border }} />
                    <span>{bought.length}</span>
                  </div>
                  <div style={{
                    display: 'grid',
                    gridTemplateColumns: isDesktop ? 'repeat(auto-fill, minmax(220px, 1fr))' : '1fr 1fr',
                    gap: 10,
                  }}>
                    {bought.map(it => <GridItem key={it.id} item={it} />)}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {bought.length > 0 && pending.length > 0 && !isDesktop && (
        <div style={{
          position: 'absolute', left: 22, right: 22,
          bottom: `calc(84px + env(safe-area-inset-bottom, 0px))`,
          zIndex: 5,
        }}>
          <Btn theme={theme} variant="solid" size="lg" full icon="check" onClick={app.clearBought}>
            {t.clearBought} ({bought.length})
          </Btn>
        </div>
      )}

      {confettiKey > 0 && app.animations && (
        <Confetti key={confettiKey} theme={theme} onDone={() => setConfettiKey(0)} />
      )}
    </div>
  );
}

function Confetti({ theme, onDone }) {
  const c = theme.c;
  const colors = [c.accent, c.accent2, c.accent3 || c.accent, c.success];
  const pieces = React.useMemo(() => Array.from({ length: 22 }, (_, i) => ({
    i,
    color: colors[i % colors.length],
    tx: (Math.random() - 0.5) * 260,
    ty: -80 - Math.random() * 180,
    tr: (Math.random() - 0.5) * 720,
    delay: Math.random() * 80,
  })), []);
  React.useEffect(() => {
    const t = setTimeout(() => onDone && onDone(), 1100);
    return () => clearTimeout(t);
  }, []);
  return (
    <div style={{
      position: 'absolute', left: '50%', top: '50%',
      pointerEvents: 'none', zIndex: 100,
    }}>
      {pieces.map(p => (
        <span key={p.i} style={{
          position: 'absolute', width: 8, height: 8, borderRadius: 2,
          background: p.color,
          ['--tx']: `${p.tx}px`, ['--ty']: `${p.ty}px`, ['--tr']: `${p.tr}deg`,
          animation: `sl-confetti .9s cubic-bezier(.2,.6,.4,1) forwards`,
          animationDelay: `${p.delay}ms`,
        }} />
      ))}
    </div>
  );
}

window.ShopScreen = ShopScreen;
