// SATMELI — Detalle de búsqueda: historial + gráfico de actividad.

function ActivityChart({ data, mode }) {
  const [hover, setHover] = React.useState(null);
  const max = Math.max(1, ...data);
  const desktop = mode === 'desktop';
  const h = desktop ? 150 : 120;
  const n = data.length;
  // etiquetas de día relativas (14 -> hoy)
  const dayName = (i) => {
    const back = n - 1 - i;
    if (back === 0) return 'hoy';
    if (back === 1) return 'ayer';
    return `-${back}d`;
  };
  const total = data.reduce((a, b) => a + b, 0);
  return (
    <div style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', padding: desktop ? 22 : 16 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 18 }}>
        <div>
          <div style={{ fontFamily: 'var(--font)', fontSize: 15, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.01em' }}>Actividad</div>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)', marginTop: 3 }}>coincidencias · últimos 14 días</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontFamily: 'var(--font)', fontSize: 24, fontWeight: 700, color: 'var(--ink)', letterSpacing: '-0.03em', lineHeight: 1 }}>{total}</div>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 10.5, color: 'var(--muted)', marginTop: 3 }}>en el período</div>
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: desktop ? 7 : 4, height: h, position: 'relative' }}>
        {data.map((v, i) => {
          const bh = (v / max) * (h - 22) + 3;
          const on = hover === i;
          return (
            <div key={i} onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}
              style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-end', height: '100%', cursor: 'default', position: 'relative' }}>
              {on && (
                <div style={{ position: 'absolute', bottom: bh + 8, fontFamily: 'var(--mono)', fontSize: 10.5, whiteSpace: 'nowrap',
                  background: 'var(--ink)', color: 'var(--bg)', padding: '3px 7px', borderRadius: 6, zIndex: 2 }}>
                  {v} · {dayName(i)}
                </div>
              )}
              <div className="sat-bar" style={{ width: '100%', maxWidth: 22, height: bh, borderRadius: 5,
                background: v === 0 ? 'var(--surface-2)' : (on ? 'var(--signal-ink-2)' : 'var(--signal)'),
                transition: 'background 140ms var(--ease), height 400ms var(--ease)' }} />
              <span style={{ fontFamily: 'var(--mono)', fontSize: 8.5, color: on ? 'var(--ink)' : 'var(--muted-3)', marginTop: 6,
                opacity: (i % 2 === 0 || desktop) ? 1 : 0 }}>{dayName(i)}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function StatCell({ k, v, sub, accent }) {
  return (
    <div style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', padding: '14px 15px' }}>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.06em', color: 'var(--muted)', marginBottom: 8 }}>{k}</div>
      <div style={{ fontFamily: 'var(--font)', fontSize: 21, fontWeight: 700, letterSpacing: '-0.025em', lineHeight: 1,
        color: accent ? 'var(--signal-ink-2)' : 'var(--ink)' }}>{v}</div>
      {sub && <div style={{ fontFamily: 'var(--mono)', fontSize: 10.5, color: 'var(--muted-3)', marginTop: 6 }}>{sub}</div>}
    </div>
  );
}

function HistoryRow({ n, cat, onGoMeli }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 4px', borderBottom: '1px solid var(--line)' }}>
      <ProductThumb cat={cat} size={52} radius="var(--r-sm)" tag={false} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: 'var(--font)', fontSize: 13.5, fontWeight: 500, color: 'var(--ink)', lineHeight: 1.35,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{n.title}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 4 }}>
          <span style={{ fontFamily: 'var(--font)', fontSize: 14, fontWeight: 700, color: 'var(--ink)', letterSpacing: '-0.02em' }}>{fmtARS(n.price)}</span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10.5, color: 'var(--muted-3)' }}>{ago(n.foundAt)}</span>
          {!n.read && <span style={{ width: 7, height: 7, borderRadius: 999, background: 'var(--alert)' }} />}
        </div>
      </div>
      <button type="button" onClick={() => onGoMeli(n)} className="sat-iconbtn"
        style={{ width: 34, height: 34, borderRadius: 'var(--r-sm)', border: '1px solid var(--line)', background: 'var(--surface)',
          color: 'var(--muted)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0 }}>
        <Icon name="upRight" size={16} />
      </button>
    </div>
  );
}

function Detail({ search, notifs, mode, onBack, onEdit, onToggle, onDelete, onGoMeli }) {
  const desktop = mode === 'desktop';
  const c = SAT_CATS[search.cat];
  const matches = notifs.filter((n) => n.searchId === search.id).sort((a, b) => a.foundAt - b.foundAt);
  const prices = matches.map((m) => m.price);
  const best = prices.length ? Math.min(...prices) : null;
  const avg = prices.length ? Math.round(prices.reduce((a, b) => a + b, 0) / prices.length) : null;
  // chequeos estimados según frecuencia y antigüedad
  const perDay = { '5m': 288, '15m': 96, '1h': 24, '6h': 4, '1d': 1 }[search.freq] || 24;
  const checks = Math.round(perDay * Math.min(search.createdAt, 30) * (search.active ? 1 : 0.6));

  const header = (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
      <button type="button" onClick={onBack} className="sat-iconbtn"
        style={{ width: 38, height: 38, borderRadius: 'var(--r-sm)', border: '1px solid var(--line)', background: 'var(--surface)',
          color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0 }}>
        <Icon name="chevL" size={19} />
      </button>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 7 }}>
          <StatusDot active={search.active} />
          <span style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.1em', color: search.active ? 'var(--signal-ink-2)' : 'var(--muted-3)' }}>
            {search.active ? 'EN VIVO' : 'PAUSADA'}
          </span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted-3)' }}>· {freqLabel(search.freq)}</span>
        </div>
        <h1 style={{ fontFamily: 'var(--font)', fontSize: desktop ? 28 : 23, fontWeight: 700, letterSpacing: '-0.03em', color: 'var(--ink)', margin: 0, lineHeight: 1.1 }}>{search.term}</h1>
      </div>
    </div>
  );

  const actions = (
    <div style={{ display: 'flex', gap: 9, flexWrap: 'wrap' }}>
      <Btn variant={search.active ? 'soft' : 'primary'} size="md" icon={search.active ? 'pause' : 'play'} onClick={onToggle} style={{ flex: desktop ? '0 0 auto' : 1 }}>
        {search.active ? 'Pausar' : 'Reanudar'}
      </Btn>
      <Btn variant="outline" size="md" icon="edit" onClick={onEdit} style={{ flex: desktop ? '0 0 auto' : 1 }}>Editar</Btn>
      <Btn variant="danger" size="md" icon="trash" onClick={onDelete}>{desktop ? 'Eliminar' : ''}</Btn>
    </div>
  );

  const filters = (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
      <Chip icon={c.icon} tone="line">{c.label}</Chip>
      <Chip icon="tag" tone="line">{priceRangeLabel(search)}</Chip>
      <Chip icon="sliders" tone="line">{condLabel(search.condition)}</Chip>
      <Chip icon="pin" tone="line">{search.location}</Chip>
    </div>
  );

  const stats = (
    <div style={{ display: 'grid', gridTemplateColumns: desktop ? 'repeat(4, minmax(0,1fr))' : 'repeat(2, minmax(0,1fr))', gap: 10 }}>
      <StatCell k="HALLAZGOS" v={search.matches} sub="total acumulado" />
      <StatCell k="MEJOR PRECIO" v={best ? fmtARS(best) : '—'} sub={best ? 'el más barato visto' : 'sin datos'} accent />
      <StatCell k="PRECIO PROMEDIO" v={avg ? fmtARS(avg) : '—'} sub="entre los hallazgos" />
      <StatCell k="CHEQUEOS" v={fmtK(checks)} sub="revisiones a MELI" />
    </div>
  );

  const history = (
    <div style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', padding: desktop ? '8px 18px 14px' : '6px 14px 10px' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 0 6px' }}>
        <span style={{ fontFamily: 'var(--font)', fontSize: 15, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.01em' }}>Historial de coincidencias</span>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)' }}>{matches.length} guardadas</span>
      </div>
      {matches.length ? matches.map((n) => <HistoryRow key={n.id} n={n} cat={search.cat} onGoMeli={onGoMeli} />)
        : <div style={{ padding: '24px 0', textAlign: 'center', fontFamily: 'var(--font)', fontSize: 14, color: 'var(--muted)' }}>Todavía sin coincidencias.</div>}
    </div>
  );

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: desktop ? 22 : 16 }}>
      {header}
      {filters}
      {actions}
      {desktop ? (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          {stats}
          <ActivityChart data={search.activity} mode={mode} />
          {history}
        </div>
      ) : (
        <>
          {stats}
          <ActivityChart data={search.activity} mode={mode} />
          {history}
        </>
      )}
    </div>
  );
}

Object.assign(window, { Detail, ActivityChart });
