// SATMELI — Dashboard con 3 variantes de tarjeta: monitor / ticket / radar.

// ── Radar scope animado (panel oscuro embebido) ───────────────────────────
function RadarScope({ count, active, size = 124, blips = [] }) {
  const cx = size / 2, r = size / 2 - 6;
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%', position: 'relative', flexShrink: 0,
      background: 'radial-gradient(circle at 50% 50%, #11331f 0%, #0a1410 75%)',
      boxShadow: 'inset 0 0 0 1px rgba(198,242,78,0.18), inset 0 2px 18px rgba(0,0,0,0.6)',
      overflow: 'hidden',
    }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ position: 'absolute', inset: 0 }}>
        {[1, 0.66, 0.33].map((f, i) => (
          <circle key={i} cx={cx} cy={cx} r={r * f} fill="none" stroke="rgba(198,242,78,0.16)" strokeWidth="1" />
        ))}
        <line x1={cx} y1={cx - r} x2={cx} y2={cx + r} stroke="rgba(198,242,78,0.12)" strokeWidth="1" />
        <line x1={cx - r} y1={cx} x2={cx + r} y2={cx} stroke="rgba(198,242,78,0.12)" strokeWidth="1" />
        {/* blips */}
        {blips.map((b, i) => {
          const a = b.a * Math.PI / 180, rad = b.r * r;
          const x = cx + Math.cos(a) * rad, y = cx + Math.sin(a) * rad;
          return <circle key={i} cx={x} cy={y} r={b.big ? 3 : 2} fill="#C6F24E"
            className={b.big ? 'sat-blip' : ''} style={{ opacity: b.big ? 1 : 0.55 }} />;
        })}
        {/* sweep */}
        {active && (
          <g className="sat-sweep" style={{ transformOrigin: `${cx}px ${cx}px` }}>
            <defs>
              <linearGradient id="rsweep" x1="0" y1="0" x2="1" y2="0">
                <stop offset="0%" stopColor="#C6F24E" stopOpacity="0" />
                <stop offset="100%" stopColor="#C6F24E" stopOpacity="0.38" />
              </linearGradient>
            </defs>
            <path d={`M${cx},${cx} L${cx + r},${cx} A${r},${r} 0 0 0 ${cx + r * Math.cos(-0.7)},${cx + r * Math.sin(-0.7)} Z`} fill="url(#rsweep)" />
            <line x1={cx} y1={cx} x2={cx + r} y2={cx} stroke="#C6F24E" strokeWidth="1.5" strokeOpacity="0.7" />
          </g>
        )}
      </svg>
      <div style={{
        position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center', color: '#EAFBC0', pointerEvents: 'none',
      }}>
        <div style={{ fontFamily: 'var(--font)', fontSize: size * 0.26, fontWeight: 700, lineHeight: 1, letterSpacing: '-0.03em' }}>{count}</div>
        <div style={{ fontFamily: 'var(--mono)', fontSize: 8.5, letterSpacing: '0.16em', opacity: 0.7, marginTop: 3 }}>HALLAZGOS</div>
      </div>
    </div>
  );
}

// blips derivados del id de búsqueda (estables)
function blipsFor(s) {
  const out = [];
  const n = Math.min(6, Math.max(2, Math.round(s.matches / 3)));
  for (let i = 0; i < n; i++) {
    out.push({ a: (i * 73 + s.id.charCodeAt(1) * 31) % 360, r: 0.3 + ((i * 0.17 + 0.2) % 0.65), big: i === 0 });
  }
  return out;
}

function CatChip({ cat }) {
  const c = SAT_CATS[cat];
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5, fontFamily: 'var(--mono)', fontSize: 11,
      letterSpacing: '-0.01em', color: c.tint, background: `color-mix(in srgb, ${c.tint} 12%, transparent)`,
      padding: '3px 8px 3px 6px', borderRadius: 'var(--r-sm)',
    }}>
      <Icon name={c.icon} size={12.5} stroke={1.9} />{c.label}
    </span>
  );
}

function priceRangeLabel(s) {
  if (s.priceMin && s.priceMax) return `${fmtK(s.priceMin)}–${fmtK(s.priceMax)}`;
  if (s.priceMax) return `hasta ${fmtARS(s.priceMax)}`;
  if (s.priceMin) return `desde ${fmtARS(s.priceMin)}`;
  return 'sin tope';
}

function MenuBtn({ onClick, name = 'dots' }) {
  return (
    <button type="button" onClick={(e) => { e.stopPropagation(); onClick && onClick(); }} className="sat-iconbtn"
      style={{
        width: 32, height: 32, 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={name} size={17} />
    </button>
  );
}

// ── Variante MONITOR ───────────────────────────────────────────────────────
function CardMonitor({ s, onOpen, onToggle }) {
  return (
    <div className="sat-card sat-cardhover" onClick={onOpen}
      style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)',
        padding: 18, cursor: 'pointer', boxShadow: 'var(--shadow-sm)', display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <StatusDot active={s.active} />
        <span style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.1em',
          color: s.active ? 'var(--signal-ink-2)' : 'var(--muted-3)' }}>
          {s.active ? 'EN VIVO' : 'PAUSADA'}
        </span>
        <span style={{ flex: 1 }} />
        <CatChip cat={s.cat} />
        <button type="button" onClick={(e) => { e.stopPropagation(); onToggle(); }} className="sat-iconbtn"
          style={{ width: 32, height: 32, borderRadius: 'var(--r-sm)', border: '1px solid var(--line)',
            background: 'var(--surface)', color: 'var(--muted)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
          <Icon name={s.active ? 'pause' : 'play'} size={15} fill={s.active ? 'none' : 'currentColor'} />
        </button>
      </div>

      <div>
        <div style={{ fontFamily: 'var(--font)', fontSize: 20, fontWeight: 600, letterSpacing: '-0.025em', lineHeight: 1.15, color: 'var(--ink)' }}>{s.term}</div>
      </div>

      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
        <Chip icon="tag">{priceRangeLabel(s)}</Chip>
        <Chip icon="sliders">{condLabel(s.condition)}</Chip>
        <Chip icon="pin">{s.location}</Chip>
      </div>

      <div style={{ height: 1, background: 'var(--line)' }} />

      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12 }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
            <span style={{ fontFamily: 'var(--font)', fontSize: 30, fontWeight: 700, letterSpacing: '-0.03em', color: 'var(--ink)', lineHeight: 1 }}>{s.matches}</span>
            <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)' }}>coincid.</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginTop: 7, fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)' }}>
            <Icon name="clock" size={12} /> {s.active ? `revisado ${ago(s.lastCheck)}` : 'monitoreo en pausa'}
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4 }}>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.08em', color: 'var(--muted-3)' }}>{freqLabel(s.freq).toUpperCase()}</span>
          <Sparkline data={s.activity} w={104} h={30} color={s.active ? 'var(--signal-ink-2)' : 'var(--muted-3)'} />
        </div>
      </div>
    </div>
  );
}

// ── Variante TICKET / RECIBO ───────────────────────────────────────────────
function Perfs({ where }) {
  return (
    <div style={{ position: 'absolute', left: 0, right: 0, [where]: -6, height: 12, display: 'flex',
      justifyContent: 'space-around', alignItems: 'center', pointerEvents: 'none' }}>
      {Array.from({ length: 16 }).map((_, i) => (
        <span key={i} style={{ width: 9, height: 9, borderRadius: 999, background: 'var(--bg)' }} />
      ))}
    </div>
  );
}
function ReceiptRow({ k, v, accent }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, fontFamily: 'var(--mono)', fontSize: 11.5, lineHeight: 1.6 }}>
      <span style={{ color: 'var(--muted)', letterSpacing: '0.02em', whiteSpace: 'nowrap' }}>{k}</span>
      <span style={{ flex: 1, borderBottom: '1px dotted var(--line-strong)', marginBottom: 4 }} />
      <span style={{ color: accent ? 'var(--signal-ink-2)' : 'var(--ink)', whiteSpace: 'nowrap', fontWeight: accent ? 700 : 400 }}>{v}</span>
    </div>
  );
}
function CardTicket({ s, onOpen, onToggle }) {
  return (
    <div className="sat-card sat-cardhover" onClick={onOpen}
      style={{ background: 'var(--surface)', borderRadius: 'var(--r-md)', padding: '22px 18px 18px',
        cursor: 'pointer', boxShadow: 'var(--shadow-sm)', position: 'relative',
        border: '1px solid var(--line)' }}>
      <Perfs where="top" />
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 10.5, letterSpacing: '0.16em', color: 'var(--muted)' }}>SATMELI · MONITOR</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontFamily: 'var(--mono)', fontSize: 10.5, letterSpacing: '0.08em',
          color: s.active ? 'var(--signal-ink-2)' : 'var(--muted-3)' }}>
          <StatusDot active={s.active} size={7} />{s.active ? 'ACTIVA' : 'EN PAUSA'}
        </span>
      </div>
      <div style={{ fontFamily: 'var(--font)', fontSize: 19, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1.15, color: 'var(--ink)', marginBottom: 4 }}>{s.term}</div>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 10.5, color: 'var(--muted)', marginBottom: 14 }}>#{s.id.toUpperCase()} · alta {ago(s.createdAt * 60).replace('hace ', 'hace ')}</div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 1, marginBottom: 14 }}>
        <ReceiptRow k="PRECIO" v={priceRangeLabel(s)} />
        <ReceiptRow k="CONDICIÓN" v={condLabel(s.condition).toUpperCase()} />
        <ReceiptRow k="ZONA" v={s.location} />
        <ReceiptRow k="FRECUENCIA" v={freqLabel(s.freq)} />
        <ReceiptRow k="ÚLT. REVISIÓN" v={s.active ? ago(s.lastCheck) : '—'} />
      </div>

      {/* tear line */}
      <div style={{ position: 'relative', margin: '0 -18px 14px', height: 1 }}>
        <div style={{ position: 'absolute', left: 14, right: 14, top: 0, borderTop: '1.5px dashed var(--line-strong)' }} />
        <span style={{ position: 'absolute', left: -6, top: -6, width: 12, height: 12, borderRadius: 999, background: 'var(--bg)' }} />
        <span style={{ position: 'absolute', right: -6, top: -6, width: 12, height: 12, borderRadius: 999, background: 'var(--bg)' }} />
      </div>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.12em', color: 'var(--muted)' }}>COINCIDENCIAS</div>
          <div style={{ fontFamily: 'var(--font)', fontSize: 30, fontWeight: 700, letterSpacing: '-0.03em', color: 'var(--ink)', lineHeight: 1 }}>{s.matches}</div>
        </div>
        {/* faux barcode */}
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 1.5, height: 34 }}>
          {[3,1,2,1,3,2,1,1,3,1,2,3,1,2,1,3,1].map((w, i) => (
            <span key={i} style={{ width: w, height: i % 3 === 0 ? 34 : 28, background: 'var(--ink)', opacity: 0.82 }} />
          ))}
        </div>
        <button type="button" onClick={(e) => { e.stopPropagation(); onToggle(); }} 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' }}>
          <Icon name={s.active ? 'pause' : 'play'} size={15} fill={s.active ? 'none' : 'currentColor'} />
        </button>
      </div>
    </div>
  );
}

// ── Variante RADAR ─────────────────────────────────────────────────────────
function CardRadar({ s, onOpen, onToggle }) {
  return (
    <div className="sat-card sat-cardhover" onClick={onOpen}
      style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)',
        padding: 16, cursor: 'pointer', boxShadow: 'var(--shadow-sm)', display: 'flex', gap: 16, alignItems: 'center' }}>
      <RadarScope count={s.matches} active={s.active} size={118} blips={blipsFor(s)} />
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10.5, letterSpacing: '0.1em',
            color: s.active ? 'var(--signal-ink-2)' : 'var(--muted-3)' }}>
            {s.active ? '◈ RASTREANDO' : '◈ EN PAUSA'}
          </span>
          <span style={{ flex: 1 }} />
          <button type="button" onClick={(e) => { e.stopPropagation(); onToggle(); }} className="sat-iconbtn"
            style={{ width: 30, height: 30, borderRadius: 'var(--r-sm)', border: '1px solid var(--line)',
              background: 'var(--surface)', color: 'var(--muted)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
            <Icon name={s.active ? 'pause' : 'play'} size={14} fill={s.active ? 'none' : 'currentColor'} />
          </button>
        </div>
        <div style={{ fontFamily: 'var(--font)', fontSize: 18, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1.15, color: 'var(--ink)',
          overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>{s.term}</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
          <Chip icon="tag">{priceRangeLabel(s)}</Chip>
          <Chip>{condLabel(s.condition)}</Chip>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontFamily: 'var(--mono)', fontSize: 10.5, color: 'var(--muted)' }}>
          <Icon name="clock" size={12} />{s.active ? `revisado ${ago(s.lastCheck)}` : 'pausada'} · {freqLabel(s.freq)}
        </div>
      </div>
    </div>
  );
}

const CARD_VARIANTS = { monitor: CardMonitor, ticket: CardTicket, radar: CardRadar };

// ── Dashboard ──────────────────────────────────────────────────────────────
function Dashboard({ searches, notifs, variant, mode, onOpen, onToggle, onCreate }) {
  const Card = CARD_VARIANTS[variant] || CardMonitor;
  const active = searches.filter((s) => s.active).length;
  const unread = notifs.filter((n) => !n.read).length;
  const todayMatches = notifs.filter((n) => n.foundAt < 1440).length;
  const desktop = mode === 'desktop';

  const stats = [
    { k: 'Centinelas activos', v: `${active}/${searches.length}`, icon: 'radar' },
    { k: 'Hallazgos hoy', v: todayMatches, icon: 'zap', accent: true },
    { k: 'Sin leer', v: unread, icon: 'bell', alert: unread > 0 },
  ];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: desktop ? 24 : 18 }}>
      {/* header */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
        <div>
          <Eyebrow style={{ marginBottom: 8 }}>Panel de monitoreo</Eyebrow>
          <h1 style={{ fontFamily: 'var(--font)', fontSize: desktop ? 34 : 27, fontWeight: 700, letterSpacing: '-0.035em', color: 'var(--ink)', margin: 0, lineHeight: 1.05 }}>
            Tus centinelas
          </h1>
          <p style={{ fontFamily: 'var(--font)', fontSize: 14.5, color: 'var(--muted)', margin: '8px 0 0' }}>
            {active} {active === 1 ? 'búsqueda vigilando' : 'búsquedas vigilando'} Mercado Libre por vos.
          </p>
        </div>
        {desktop && <Btn variant="primary" icon="plus" size="lg" onClick={onCreate} style={{ boxShadow: 'var(--btn-pop)' }}>Nueva búsqueda</Btn>}
      </div>

      {/* stats strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: desktop ? 14 : 10 }}>
        {stats.map((st) => (
          <div key={st.k} style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-md)',
            padding: desktop ? '16px 18px' : '13px 13px', display: 'flex', flexDirection: 'column', gap: 8 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.06em', color: 'var(--muted)', lineHeight: 1.3 }}>{st.k}</span>
              <span style={{ color: st.alert ? 'var(--alert)' : st.accent ? 'var(--signal-ink-2)' : 'var(--muted-3)' }}><Icon name={st.icon} size={16} /></span>
            </div>
            <span style={{ fontFamily: 'var(--font)', fontSize: desktop ? 28 : 23, fontWeight: 700, letterSpacing: '-0.03em',
              color: st.alert ? 'var(--alert)' : 'var(--ink)', lineHeight: 1 }}>{st.v}</span>
          </div>
        ))}
      </div>

      {/* cards */}
      <div style={{ display: 'grid', gridTemplateColumns: desktop ? (variant === 'radar' ? '1fr 1fr' : 'repeat(2, 1fr)') : '1fr',
        gap: desktop ? 16 : 14 }}>
        {searches.map((s, i) => (
          <div key={s.id} className="sat-stagger" style={{ animationDelay: `${i * 45}ms`, gridColumn: (variant === 'radar' && desktop) ? '1 / -1' : undefined }}>
            <Card s={s} onOpen={() => onOpen(s.id)} onToggle={() => onToggle(s.id)} />
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard, RadarScope, CardMonitor, CardTicket, CardRadar, priceRangeLabel, CatChip });
