// Shopping flow — select products, searching animation, results grouped by store
const ShopScreen = ({ onClose }) => {
  const [phase, setPhase] = useState('select'); // select | searching | results
  const [selected, setSelected] = useState(new Set(['h1','h2','h3','h5','h6']));
  const toggle = (id) => {
    setSelected(s => {
      const n = new Set(s);
      if (n.has(id)) n.delete(id); else n.add(id);
      return n;
    });
  };
  const selectedItems = window.MOCK.habitual.filter(h => selected.has(h.id));

  if (phase === 'searching') return <SearchingAnimation onDone={() => setPhase('results')}/>;
  if (phase === 'results') return <ResultsScreen onBack={() => setPhase('select')} onClose={onClose} selectedItems={selectedItems}/>;

  return (
    <div className="fade-in" style={{ position: 'absolute', inset: 0, background: 'var(--c-bg)', zIndex: 50, display: 'flex', flexDirection: 'column' }}>
      <StatusBar/>
      <ScreenHeader onBack={onClose} title="Tu compra inteligente"/>
      <div className="screen">
        <div className="section" style={{ paddingTop: 0 }}>
          <div className="card card-pad" style={{ background: 'linear-gradient(135deg, var(--c-navy-soft), #eef3fa)', border: '1px solid #d4ddf0' }}>
            <div className="row gap-3" style={{ alignItems: 'center' }}>
              <div style={{ width: 44, height: 44, borderRadius: 14, background: 'var(--c-navy)', display: 'grid', placeItems: 'center' }}>
                <Icon name="cart" size={22} color="white"/>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 800, fontSize: 14 }}>Selecciona los productos a comprar</div>
                <div className="tiny muted" style={{ marginTop: 2 }}>Te agruparemos por tienda y mejor descuento</div>
              </div>
            </div>
          </div>
        </div>

        <div className="section section-tight">
          <div className="row between">
            <div className="small" style={{ fontWeight: 700 }}>{selected.size} de {window.MOCK.habitual.length} seleccionados</div>
            <button onClick={() => setSelected(new Set(window.MOCK.habitual.map(h => h.id)))} className="small" style={{ background: 'transparent', border: 'none', color: 'var(--c-primary)', fontWeight: 800, cursor: 'pointer', fontFamily: 'inherit' }}>Marcar todos</button>
          </div>
        </div>

        <div className="section" style={{ paddingTop: 8 }}>
          <div className="card" style={{ padding: 6 }}>
            {window.MOCK.habitual.map((p, i, a) => {
              const isSel = selected.has(p.id);
              return (
                <button key={p.id} onClick={() => toggle(p.id)} className="row gap-3" style={{ width: '100%', padding: '12px 10px', borderBottom: i < a.length - 1 ? '1px solid var(--c-line-2)' : 'none', background: 'transparent', border: 'none', cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit', alignItems: 'center' }}>
                  <span className={'checkbox ' + (isSel ? 'checked' : '')}>
                    {isSel && <Icon name="check" size={14} color="white" stroke={3}/>}
                  </span>
                  <ProductImg kind={p.img} size="sm"/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 700, fontSize: 14 }}>{p.name}</div>
                    <div className="tiny muted" style={{ marginTop: 2 }}>{p.unit} · prom. ${p.avgPrice.toFixed(2)}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div className="money" style={{ fontSize: 14, fontWeight: 900, color: 'var(--c-primary-deep)' }}>${p.bestPrice.toFixed(2)}</div>
                    <div className="tiny muted" style={{ marginTop: 2 }}>{p.bestStore.split(' ')[0]}</div>
                  </div>
                </button>
              );
            })}
          </div>
        </div>
      </div>
      <div style={{ padding: '14px 22px 22px', background: 'rgba(251,247,241,0.94)', backdropFilter: 'blur(10px)', borderTop: '1px solid var(--c-line)' }}>
        <button onClick={() => setPhase('searching')} disabled={selected.size === 0} className="btn btn-primary btn-block" style={{ opacity: selected.size === 0 ? 0.5 : 1 }}>
          <Icon name="search" size={18} color="white"/> Buscar mejores precios ({selected.size})
        </button>
      </div>
    </div>
  );
};

const SearchingAnimation = ({ onDone }) => {
  const stores = window.MOCK.supermarkets;
  const messages = [
    'Buscando tiendas cercanas…',
    'Comparando precios en tiempo real…',
    'Calculando tu ahorro óptimo…',
    'Organizando tu plan de compras…'
  ];
  const [msgIdx, setMsgIdx] = useState(0);
  const [progress, setProgress] = useState(0);
  useEffect(() => {
    let p = 0;
    const t = setInterval(() => {
      p += 1.6;
      setProgress(Math.min(p, 100));
      if (p >= 100) { clearInterval(t); setTimeout(onDone, 320); }
    }, 60);
    const m = setInterval(() => setMsgIdx(i => (i + 1) % messages.length), 1100);
    return () => { clearInterval(t); clearInterval(m); };
  }, []);

  return (
    <div className="fade-in" style={{ position: 'absolute', inset: 0, background: 'radial-gradient(circle at 50% 40%, #fff7ed 0%, #f3ede0 100%)', zIndex: 60, display: 'flex', flexDirection: 'column' }}>
      <StatusBar/>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', padding: '0 32px' }}>
        {/* Radar with orbiting stores */}
        <div className="pulse-rings">
          <div className="ring"/>
          <div className="ring r2"/>
          <div className="ring r3"/>
          <div className="ring r4"/>
          <div style={{ position: 'absolute', inset: 0, animation: 'orbit 12s linear infinite' }}>
            {stores.slice(0, 5).map((s, i) => {
              const angle = (i / 5) * Math.PI * 2;
              const r = 90 + (i % 2) * 10;
              const left = 110 + Math.cos(angle) * r - 22;
              const top = 110 + Math.sin(angle) * r - 22;
              return (
                <div key={s.id} className="orbit-store" style={{ left, top, color: s.color, animation: `orbit 12s linear infinite reverse` }}>
                  <StoreDot color={s.color} short={s.short} size={26}/>
                </div>
              );
            })}
          </div>
          <div className="core">
            <Icon name="search" size={32} color="white"/>
          </div>
        </div>

        <h2 style={{ marginTop: 40, fontSize: 24, textAlign: 'center' }}>Buscando tu mejor precio</h2>
        <div className="muted small" style={{ marginTop: 10, textAlign: 'center', minHeight: 22, fontWeight: 600 }}>
          <span key={msgIdx} className="fade-in">{messages[msgIdx]}</span>
        </div>

        {/* Stations list */}
        <div className="stack stack-2" style={{ marginTop: 30, width: '100%', maxWidth: 320 }}>
          {stores.slice(0, 4).map((s, i) => {
            const done = progress > (i + 1) * 22;
            const active = progress > i * 22 && !done;
            return (
              <div key={s.id} className="row gap-3" style={{ padding: '10px 14px', borderRadius: 14, background: 'white', border: '1px solid var(--c-line)', boxShadow: active ? '0 6px 18px rgba(27,154,95,0.15)' : 'none', transition: 'box-shadow .25s', opacity: done || active ? 1 : 0.55 }}>
                <StoreDot color={s.color} short={s.short} size={32}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 800 }}>{s.name}</div>
                  <div className="tiny muted">{s.distance}</div>
                </div>
                {done ? <Icon name="check" size={18} color="var(--c-primary)" stroke={3}/> : active ? <div style={{ width: 16, height: 16, border: '2.5px solid var(--c-line)', borderTopColor: 'var(--c-primary)', borderRadius: '50%', animation: 'spin .8s linear infinite' }}/> : <div style={{ width: 16, height: 16, borderRadius: '50%', border: '2.5px solid var(--c-line)' }}/>}
              </div>
            );
          })}
        </div>

        <div style={{ width: '100%', maxWidth: 320, marginTop: 22 }}>
          <div className="bar-track" style={{ background: 'rgba(20,35,64,0.08)' }}>
            <div className="bar-fill" style={{ width: `${progress}%`, background: 'linear-gradient(90deg, var(--c-primary), var(--c-mint))', transition: 'width .15s linear' }}/>
          </div>
          <div className="row between" style={{ marginTop: 8 }}>
            <span className="tiny muted">{Math.round(progress)}%</span>
            <span className="tiny muted">≈ {Math.max(0, Math.ceil((100-progress)/25))} s</span>
          </div>
        </div>
      </div>
    </div>
  );
};

// Group selected items by their best-discount store
const ResultsScreen = ({ onBack, onClose, selectedItems }) => {
  // Build groups using ranking — pick best store per item from ranking that store carries it
  const groups = useMemo(() => {
    const map = {};
    selectedItems.forEach(item => {
      const store = item.bestStore;
      if (!map[store]) map[store] = [];
      // synthesize price + pct
      const meta = window.MOCK.supermarkets.find(s => s.name === store) || {};
      map[store].push({
        name: item.name,
        unit: item.unit,
        img: item.img,
        price: item.bestPrice,
        avg: item.avgPrice,
        pct: Math.round(100 - (item.bestPrice / item.avgPrice) * 100),
        save: item.avgPrice - item.bestPrice,
        color: meta.color,
        short: meta.short
      });
    });
    return Object.entries(map).map(([store, items]) => {
      const meta = window.MOCK.supermarkets.find(s => s.name === store);
      return {
        store,
        meta,
        items,
        total: items.reduce((a, b) => a + b.price, 0),
        avg: items.reduce((a, b) => a + b.avg, 0),
        save: items.reduce((a, b) => a + b.save, 0),
        avgPct: Math.round((items.reduce((a, b) => a + b.pct, 0) / items.length))
      };
    }).sort((a, b) => b.save - a.save);
  }, [selectedItems]);

  const totalBest = groups.reduce((a, g) => a + g.total, 0);
  const totalAvg = groups.reduce((a, g) => a + g.avg, 0);
  const totalSave = totalAvg - totalBest;
  const avgPct = Math.round((totalSave / totalAvg) * 100);

  return (
    <div className="fade-in" style={{ position: 'absolute', inset: 0, background: 'var(--c-bg)', zIndex: 50, display: 'flex', flexDirection: 'column' }}>
      <StatusBar/>
      <ScreenHeader onBack={onBack} title="Plan de compra"/>
      <div className="screen">
        <div className="section" style={{ paddingTop: 0 }}>
          <div className="pop-in" style={{ borderRadius: 22, padding: 22, background: 'linear-gradient(135deg, var(--c-primary) 0%, var(--c-primary-deep) 100%)', color: 'white', position: 'relative', overflow: 'hidden' }}>
            <div style={{ position: 'absolute', right: -20, bottom: -30, width: 140, height: 140, borderRadius: '50%', background: 'radial-gradient(circle, rgba(255,200,69,0.28), transparent 70%)' }}/>
            <div className="tiny" style={{ opacity: 0.75, letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 800 }}>Tu ahorro estimado</div>
            <div className="row gap-3" style={{ alignItems: 'baseline', marginTop: 4 }}>
              <span style={{ fontSize: 38, fontWeight: 900, letterSpacing: '-0.03em' }}>${totalSave.toFixed(2)}</span>
              <span style={{ fontSize: 14, opacity: 0.85, fontWeight: 700 }}>· {avgPct}% prom.</span>
            </div>
            <div className="row gap-3" style={{ marginTop: 18 }}>
              <div style={{ flex: 1, padding: '10px 12px', background: 'rgba(0,0,0,0.18)', borderRadius: 12 }}>
                <div className="tiny" style={{ opacity: 0.75, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Tu plan</div>
                <div style={{ fontSize: 18, fontWeight: 900, marginTop: 2 }}>${totalBest.toFixed(2)}</div>
              </div>
              <div style={{ flex: 1, padding: '10px 12px', background: 'rgba(0,0,0,0.18)', borderRadius: 12 }}>
                <div className="tiny" style={{ opacity: 0.75, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Promedio</div>
                <div style={{ fontSize: 18, fontWeight: 700, marginTop: 2, textDecoration: 'line-through', opacity: 0.8 }}>${totalAvg.toFixed(2)}</div>
              </div>
            </div>
          </div>
        </div>

        <div className="section section-tight">
          <div className="row between">
            <h3>Por supermercado</h3>
            <div className="small muted" style={{ fontWeight: 700 }}>{groups.length} tiendas</div>
          </div>
        </div>

        <div className="section" style={{ paddingTop: 8, paddingBottom: 24 }}>
          <div className="stack stack-3">
            {groups.map((g, i) => (
              <div key={g.store} className="card pop-in" style={{ padding: 0, overflow: 'hidden', animationDelay: `${i*.06}s` }}>
                <div className="row gap-3" style={{ padding: '14px 16px', background: g.meta.color + '14', borderBottom: '1px solid var(--c-line-2)', alignItems: 'center' }}>
                  <StoreDot color={g.meta.color} short={g.meta.short} size={42}/>
                  <div style={{ flex: 1 }}>
                    <div className="row gap-2" style={{ alignItems: 'center' }}>
                      <span style={{ fontWeight: 800, fontSize: 15 }}>{g.store}</span>
                      {i === 0 && <span className="chip yellow" style={{ height: 20, fontSize: 10, padding: '0 7px' }}><Icon name="crown" size={10}/> mejor</span>}
                    </div>
                    <div className="tiny muted" style={{ marginTop: 2, display: 'flex', alignItems: 'center', gap: 6 }}>
                      <Icon name="pin" size={11}/> {g.meta.distance} · {g.items.length} productos
                    </div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div className="money" style={{ fontSize: 17, fontWeight: 900 }}>${g.total.toFixed(2)}</div>
                    <span className="chip green" style={{ height: 20, fontSize: 10, padding: '0 7px', marginTop: 4 }}>ahorra ${g.save.toFixed(2)}</span>
                  </div>
                </div>
                <div>
                  {g.items.map((it, k) => (
                    <div key={k} className="row gap-3" style={{ padding: '11px 16px', borderBottom: k < g.items.length - 1 ? '1px solid var(--c-line-2)' : 'none', alignItems: 'center' }}>
                      <ProductImg kind={it.img} size="sm"/>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontWeight: 700, fontSize: 13.5 }}>{it.name}</div>
                        <div className="tiny muted" style={{ marginTop: 2 }}>{it.unit}</div>
                      </div>
                      <div style={{ textAlign: 'right' }}>
                        <div className="row gap-2" style={{ alignItems: 'baseline', justifyContent: 'flex-end' }}>
                          <span className="money" style={{ fontSize: 14, fontWeight: 900, color: 'var(--c-primary-deep)' }}>${it.price.toFixed(2)}</span>
                          <span className="struck tiny">${it.avg.toFixed(2)}</span>
                        </div>
                        <div className="tiny" style={{ color: 'var(--c-primary)', fontWeight: 800, marginTop: 2 }}>-{it.pct}%</div>
                      </div>
                    </div>
                  ))}
                </div>
                <div className="row gap-2" style={{ padding: '12px 16px', background: '#fbf9f4', alignItems: 'center' }}>
                  <Icon name="truck" size={16} color="var(--c-ink-2)"/>
                  <span className="small" style={{ flex: 1, color: 'var(--c-ink-2)', fontWeight: 600 }}>Ruta más corta · 12 min en auto</span>
                  <button className="btn btn-sm btn-dark"><Icon name="pin" size={13} color="white"/> Ir</button>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div style={{ padding: '14px 22px 22px', background: 'rgba(251,247,241,0.94)', backdropFilter: 'blur(10px)', borderTop: '1px solid var(--c-line)' }}>
        <div className="row gap-3">
          <button onClick={onClose} className="btn btn-ghost" style={{ flex: 1 }}>
            Compartir lista
          </button>
          <button className="btn btn-primary" style={{ flex: 1.4 }}>
            Iniciar ruta <Icon name="arrow-right" size={18} color="white"/>
          </button>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { ShopScreen });
