// SATMELI — Feed de notificaciones (el corazón de la app).

function deltaInfo(price, target) {
  if (!target) return null;
  const pct = Math.round(((target - price) / target) * 100);
  if (pct >= 0) return { pct, under: true, label: `${pct}% bajo tu tope` };
  return { pct: -pct, under: false, label: `${-pct}% sobre tu tope` };
}

// ── Item de notificación ───────────────────────────────────────────────────
function NotifItem({ n, search, mode, onOpenSearch, onMarkRead, onGoMeli, i }) {
  const cat = search ? search.cat : 'tech';
  const c = SAT_CATS[cat];
  const delta = deltaInfo(n.price, n.target);
  const unread = !n.read;
  const desktop = mode === 'desktop';

  return (
    <div className="sat-notif sat-stagger" style={{ animationDelay: `${i * 40}ms`, position: 'relative',
      background: unread ? 'var(--alert-bg)' : 'var(--surface)',
      border: `1px solid ${unread ? 'var(--alert-line)' : 'var(--line)'}`,
      borderRadius: 'var(--r-lg)', overflow: 'hidden',
      boxShadow: unread ? 'var(--shadow-alert)' : 'var(--shadow-sm)',
      transition: 'transform 200ms var(--ease), box-shadow 200ms var(--ease)' }}>
      {/* barra de no-leído */}
      {unread && <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 4, background: 'var(--alert)' }} />}

      <div style={{ display: 'flex', gap: desktop ? 16 : 13, padding: desktop ? '16px 18px 16px 20px' : '14px 14px 14px 17px', alignItems: 'stretch' }}>
        {/* thumb */}
        <div style={{ position: 'relative' }}>
          <ProductThumb cat={cat} size={desktop ? 96 : 80} radius="var(--r-md)" />
          {unread && <span style={{ position: 'absolute', top: -5, right: -5, width: 14, height: 14, borderRadius: 999,
            background: 'var(--alert)', border: '2.5px solid var(--alert-bg)' }} />}
        </div>

        {/* contenido */}
        <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
          {/* origen + tiempo */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
            <button type="button" onClick={(e) => { e.stopPropagation(); onOpenSearch(n.searchId); }}
              style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: 'transparent', border: 'none',
                cursor: 'pointer', padding: 0, fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '-0.01em', color: c.tint }}>
              <span style={{ width: 7, height: 7, borderRadius: 999, background: c.tint }} />
              {search ? search.term : 'búsqueda'}
            </button>
            {unread && <span style={{ fontFamily: 'var(--mono)', fontSize: 9.5, fontWeight: 700, letterSpacing: '0.1em',
              color: 'var(--alert)', background: 'var(--alert-soft)', padding: '2px 6px', borderRadius: 5 }}>NUEVO</span>}
            <span style={{ flex: 1 }} />
            <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)', whiteSpace: 'nowrap' }}>{ago(n.foundAt)}</span>
          </div>

          {/* título */}
          <div style={{ fontFamily: 'var(--font)', fontSize: desktop ? 15.5 : 14.5, fontWeight: unread ? 600 : 500,
            letterSpacing: '-0.01em', lineHeight: 1.35, color: 'var(--ink)',
            display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden', marginBottom: 'auto' }}>
            {n.title}
          </div>

          {/* precio + meta */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, flexWrap: 'wrap', marginTop: 10 }}>
            <span style={{ fontFamily: 'var(--font)', fontSize: desktop ? 21 : 19, fontWeight: 700, letterSpacing: '-0.02em', color: 'var(--ink)', lineHeight: 1 }}>
              {fmtARS(n.price)}
            </span>
            {delta && (
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontFamily: 'var(--mono)', fontSize: 11, fontWeight: 700,
                color: delta.under ? 'var(--signal-ink-2)' : 'var(--alert)',
                background: delta.under ? 'var(--signal-soft)' : 'var(--alert-soft)',
                padding: '3px 8px', borderRadius: 'var(--r-sm)' }}>
                <Icon name="trendDown" size={12} stroke={2} />{delta.label}
              </span>
            )}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7, flexWrap: 'wrap', marginTop: 9 }}>
            <Chip>{condLabel(n.condition)}</Chip>
            <Chip icon="pin">{n.location}</Chip>
            {desktop && <Chip icon="shield">{n.sellerRep}</Chip>}
          </div>

          {/* acciones — mobile */}
          {!desktop && (
            <div style={{ display: 'flex', gap: 8, marginTop: 13 }}>
              <Btn variant="dark" size="sm" iconRight="upRight" onClick={(e) => { e.stopPropagation(); onGoMeli(n); }} style={{ flex: 1 }}>Ver en MELI</Btn>
              {unread && <Btn variant="soft" size="sm" icon="check" onClick={(e) => { e.stopPropagation(); onMarkRead(n.id); }}>Leída</Btn>}
            </div>
          )}
        </div>

        {/* acciones — desktop (columna derecha) */}
        {desktop && (
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', justifyContent: 'space-between', gap: 8 }}>
            <button type="button" onClick={(e) => { e.stopPropagation(); onMarkRead(n.id); }} title={unread ? 'Marcar leída' : 'Leída'} className="sat-iconbtn"
              style={{ width: 34, height: 34, borderRadius: 'var(--r-sm)', border: '1px solid var(--line)',
                background: unread ? 'var(--surface)' : 'transparent', color: unread ? 'var(--muted)' : 'var(--signal-ink-2)',
                display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0 }}>
              <Icon name={unread ? 'check' : 'checkCheck'} size={17} />
            </button>
            <Btn variant="dark" size="sm" iconRight="upRight" onClick={(e) => { e.stopPropagation(); onGoMeli(n); }}>Ver en MELI</Btn>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Feed ───────────────────────────────────────────────────────────────────
function Feed({ notifs, searches, mode, onOpenSearch, onMarkRead, onMarkAll, onGoMeli }) {
  const [filter, setFilter] = React.useState('all');
  const desktop = mode === 'desktop';
  const byId = Object.fromEntries(searches.map((s) => [s.id, s]));

  const sorted = [...notifs].sort((a, b) => a.foundAt - b.foundAt);
  const shown = filter === 'all' ? sorted : sorted.filter((n) => n.searchId === filter);
  const unread = notifs.filter((n) => !n.read).length;

  // agrupar por día
  const groups = [];
  shown.forEach((n) => {
    const lbl = dayLabel(n.foundAt);
    let g = groups.find((x) => x.lbl === lbl);
    if (!g) { g = { lbl, items: [] }; groups.push(g); }
    g.items.push(n);
  });

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: desktop ? 20 : 16 }}>
      {/* header */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
        <div>
          <Eyebrow style={{ marginBottom: 8 }}>Tiempo real</Eyebrow>
          <h1 style={{ fontFamily: 'var(--font)', fontSize: desktop ? 34 : 27, fontWeight: 700, letterSpacing: '-0.035em', color: 'var(--ink)', margin: 0, lineHeight: 1.05, display: 'flex', alignItems: 'center', gap: 12 }}>
            Alertas
            {unread > 0 && <span style={{ fontFamily: 'var(--font)', fontSize: desktop ? 15 : 13, fontWeight: 700,
              background: 'var(--alert)', color: '#fff', borderRadius: 999, padding: '3px 11px', letterSpacing: '-0.01em', alignSelf: 'center' }}>{unread} sin leer</span>}
          </h1>
        </div>
        {unread > 0 && <Btn variant="soft" size={desktop ? 'md' : 'sm'} icon="checkCheck" onClick={onMarkAll}>Marcar todas leídas</Btn>}
      </div>

      {/* filtros por búsqueda */}
      <div className="sat-hscroll" style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 2, margin: desktop ? 0 : '0 -2px' }}>
        <FilterChip active={filter === 'all'} onClick={() => setFilter('all')}>Todas</FilterChip>
        {searches.map((s) => (
          <FilterChip key={s.id} active={filter === s.id} onClick={() => setFilter(s.id)} dot={SAT_CATS[s.cat].tint}>
            {s.term}
          </FilterChip>
        ))}
      </div>

      {/* grupos */}
      {groups.map((g) => (
        <div key={g.lbl} style={{ display: 'flex', flexDirection: 'column', gap: desktop ? 12 : 10 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '2px 0' }}>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--muted-2)' }}>{g.lbl}</span>
            <span style={{ flex: 1, height: 1, background: 'var(--line)' }} />
            <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted-3)' }}>{g.items.length}</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: desktop ? 12 : 11 }}>
            {g.items.map((n, idx) => (
              <NotifItem key={n.id} n={n} search={byId[n.searchId]} mode={mode} i={idx}
                onOpenSearch={onOpenSearch} onMarkRead={onMarkRead} onGoMeli={onGoMeli} />
            ))}
          </div>
        </div>
      ))}

      {groups.length === 0 && (
        <div style={{ textAlign: 'center', padding: '48px 20px', color: 'var(--muted)' }}>
          <div style={{ display: 'inline-flex', marginBottom: 12, color: 'var(--muted-3)' }}><Icon name="inbox" size={40} stroke={1.4} /></div>
          <div style={{ fontFamily: 'var(--font)', fontSize: 15 }}>Sin alertas para este filtro todavía.</div>
        </div>
      )}
    </div>
  );
}

function FilterChip({ children, active, onClick, dot }) {
  return (
    <button type="button" onClick={onClick}
      style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 13px', borderRadius: 'var(--r-pill)',
        border: `1px solid ${active ? 'transparent' : 'var(--line-strong)'}`, cursor: 'pointer', whiteSpace: 'nowrap',
        background: active ? 'var(--ink)' : 'var(--surface)', color: active ? 'var(--bg)' : 'var(--muted-2)',
        fontFamily: 'var(--font)', fontSize: 13, fontWeight: 600, letterSpacing: '-0.01em', flexShrink: 0,
        transition: 'all 160ms var(--ease)' }}>
      {dot && <span style={{ width: 7, height: 7, borderRadius: 999, background: dot }} />}
      {children}
    </button>
  );
}

Object.assign(window, { Feed, deltaInfo });
