/* engagement.jsx — notificações, monitoramento de produtos (watchlist), streak e toast */
const {
  Button: EBtn, Badge: EBadge, Separator: ESep, Commission: ECommission, cn: ecn, formatBRL: eBRL, formatPct: ePct,
  IconBell: EBell, IconStar: EStar, IconTrendUp: ETrendUp, IconTrendDown: ETrendDown,
  IconChart: EChart, IconBookmark: EBookmark, IconBellPlus: EBellPlus, IconFlame: EFlame,
  IconTarget: ETarget, IconBox: EBox, IconExternal: EExternal, IconX: EX, IconCheck: ECheck,
  IconBolt: EBolt, IconAlert: EAlertI, IconArrowRight: EArrow, IconTrash: ETrash, IconCheckCircle: ECheckCircle,
} = window;

/* ---------- helpers ---------- */
function relTime(min) {
  if (min < 1) return 'agora';
  if (min < 60) return `há ${Math.round(min)} min`;
  const h = min / 60;
  if (h < 24) return `há ${Math.round(h)} h`;
  return `há ${Math.round(h / 24)} d`;
}
function hashId(s) {
  let h = 2166136261;
  s = String(s || '');
  for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }
  return h >>> 0;
}
function sparkFor(id, base) {
  const seed = hashId(id);
  let a = seed;
  const rnd = () => { a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; };
  const pts = [];
  let v = base * (0.82 + rnd() * 0.12);
  for (let i = 0; i < 12; i++) { v += (rnd() - 0.45) * base * 0.06; pts.push(Math.max(base * 0.5, v)); }
  pts.push(base);
  return pts;
}

const NOTIF_META = {
  opportunity: { icon: EStar, tint: 'text-brand', bg: 'bg-brand/12' },
  commission_up: { icon: ETrendUp, tint: 'text-brand', bg: 'bg-brand/12' },
  price_drop: { icon: ETrendDown, tint: 'text-coral', bg: 'bg-coral/12' },
  report: { icon: EChart, tint: 'text-zinc-300', bg: 'bg-white/[0.06]' },
  system: { icon: EBell, tint: 'text-zinc-300', bg: 'bg-white/[0.06]' },
};

function seedNotifications() {
  return [
    { id: 'n1', type: 'opportunity', title: 'Nova oportunidade no seu nicho', desc: 'Smartwatch com 18% de comissão apareceu na Shopee — R$ 41,20 por venda.', min: 4, read: false },
    { id: 'n2', type: 'price_drop', title: 'Caiu de preço: Air Fryer 5L', desc: 'De R$ 399 para R$ 329. Bom momento para divulgar.', min: 47, read: false },
    { id: 'n3', type: 'commission_up', title: 'Comissão subiu em Beleza', desc: 'Kit skincare passou de 8% para 12% no Mercado Livre.', min: 180, read: false },
    { id: 'n4', type: 'report', title: 'Seu relatório semanal está pronto', desc: 'Você gerou R$ 1.284 em comissões potenciais nesta semana.', min: 1440, read: true },
    { id: 'n5', type: 'system', title: 'Bem-vinda ao AchaMais 🎉', desc: 'Comece monitorando seus primeiros produtos para receber alertas.', min: 2880, read: true },
  ];
}

/* ---------- Menu de notificações (sininho) ---------- */
function NotificationsMenu({ items, onMarkAll, onItem, onClear }) {
  const { useState, useRef, useEffect } = React;
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);
  const unread = items.filter((n) => !n.read).length;
  return (
    <div className="relative" ref={ref}>
      <button onClick={() => setOpen((o) => !o)} aria-label="Notificações"
        className="relative flex h-11 w-11 items-center justify-center rounded-xl border border-edge bg-white/[0.04] text-zinc-300 transition-colors hover:bg-white/[0.08] hover:text-white">
        <EBell size={19} />
        {unread > 0 && (
          <span className="absolute -right-1 -top-1 flex h-5 min-w-[20px] items-center justify-center rounded-full bg-coral px-1 text-[10px] font-bold text-white ring-2 ring-ink">
            {unread > 9 ? '9+' : unread}
          </span>
        )}
      </button>

      {open && (
        <div className="fixed left-2 right-2 top-[62px] z-50 overflow-hidden rounded-2xl border border-edge bg-[#161616] shadow-2xl shadow-black/60 sm:absolute sm:left-auto sm:right-0 sm:top-auto sm:mt-2 sm:w-[360px]">
          <div className="flex items-center justify-between border-b border-edge px-4 py-3">
            <div className="flex items-center gap-2">
              <span className="font-syne text-sm font-bold text-white">Notificações</span>
              {unread > 0 && <EBadge variant="brand">{unread} nova{unread > 1 ? 's' : ''}</EBadge>}
            </div>
            <button onClick={onMarkAll} className="text-xs text-zinc-400 transition-colors hover:text-brand">Marcar todas como lidas</button>
          </div>

          <div className="max-h-[380px] overflow-y-auto">
            {items.length === 0 ? (
              <div className="flex flex-col items-center gap-2 px-4 py-12 text-center">
                <span className="flex h-12 w-12 items-center justify-center rounded-2xl bg-white/[0.04] text-zinc-600"><EBell size={22} /></span>
                <p className="text-sm text-zinc-500">Tudo limpo por aqui.</p>
              </div>
            ) : items.map((n) => {
              const m = NOTIF_META[n.type] || NOTIF_META.system;
              return (
                <button key={n.id} onClick={() => onItem(n.id)}
                  className={ecn('flex w-full items-start gap-3 border-b border-edge/60 px-4 py-3 text-left transition-colors last:border-0 hover:bg-white/[0.03]', !n.read && 'bg-brand/[0.035]')}>
                  <span className={ecn('mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg', m.bg, m.tint)}><m.icon size={16} /></span>
                  <span className="min-w-0 flex-1">
                    <span className="flex items-center gap-2">
                      <span className="truncate text-sm font-medium text-zinc-100">{n.title}</span>
                      {!n.read && <span className="ml-auto h-2 w-2 shrink-0 rounded-full bg-coral" />}
                    </span>
                    <span className="mt-0.5 block text-xs leading-relaxed text-zinc-500">{n.desc}</span>
                    <span className="mt-1 block text-[11px] text-zinc-600">{relTime(n.min)}</span>
                  </span>
                </button>
              );
            })}
          </div>

          {items.length > 0 && (
            <div className="border-t border-edge px-4 py-2.5">
              <button onClick={onClear} className="w-full text-center text-xs text-zinc-500 transition-colors hover:text-coral">Limpar notificações</button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

/* ---------- Streak (chama de constância) ---------- */
function StreakPill({ days }) {
  return (
    <div className="hidden items-center gap-1.5 rounded-xl border border-edge bg-white/[0.04] px-2.5 py-2 sm:flex" title={`Você usa o AchaMais há ${days} dias seguidos`}>
      <EFlame size={16} className="text-coral" fill="rgba(249,94,46,0.25)" />
      <span className="text-sm font-bold tabular-nums text-white">{days}</span>
    </div>
  );
}

/* ---------- Botão monitorar (nos cards) ---------- */
function MonitorButton({ active, onClick, floating }) {
  if (floating) {
    return (
      <button onClick={onClick} aria-label={active ? 'Parar de monitorar' : 'Monitorar produto'}
        className={ecn('flex h-9 w-9 items-center justify-center rounded-full border backdrop-blur transition-all',
          active ? 'border-brand/50 bg-brand/20 text-brand' : 'border-white/15 bg-black/50 text-zinc-300 hover:bg-black/70 hover:text-white')}>
        <EBookmark size={16} fill={active ? 'currentColor' : 'none'} />
      </button>
    );
  }
  return (
    <button onClick={onClick}
      className={ecn('flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border transition-all',
        active ? 'border-brand/50 bg-brand/12 text-brand' : 'border-edge text-zinc-400 hover:text-white')}>
      <EBookmark size={16} fill={active ? 'currentColor' : 'none'} />
    </button>
  );
}

/* ---------- Mini sparkline ---------- */
function Sparkline({ points, color = '#16BFA3', w = 96, h = 30 }) {
  const min = Math.min(...points), max = Math.max(...points);
  const span = max - min || 1;
  const step = w / (points.length - 1);
  const d = points.map((p, i) => `${i === 0 ? 'M' : 'L'}${(i * step).toFixed(1)} ${(h - (p - min) / span * (h - 4) - 2).toFixed(1)}`).join(' ');
  return (
    <svg width={w} height={h} className="overflow-visible">
      <path d={d} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={w} cy={h - (points[points.length - 1] - min) / span * (h - 4) - 2} r="2.5" fill={color} />
    </svg>
  );
}

/* ---------- Toast ---------- */
function Toast({ toast }) {
  if (!toast) return null;
  return (
    <div className="pointer-events-none fixed inset-x-0 bottom-20 z-[60] flex justify-center px-4 md:bottom-6">
      <div className="pointer-events-auto flex items-center gap-3 rounded-2xl border border-edge bg-[#161616] px-4 py-3 shadow-2xl shadow-black/60 animate-[popIn_.2s_cubic-bezier(.16,1,.3,1)]">
        <span className={ecn('flex h-8 w-8 items-center justify-center rounded-lg', toast.tone === 'brand' ? 'bg-brand/15 text-brand' : 'bg-white/[0.06] text-zinc-300')}>
          {toast.tone === 'brand' ? <ECheckCircle size={17} /> : <EBell size={16} />}
        </span>
        <div className="text-sm">
          <div className="font-medium text-white">{toast.title}</div>
          {toast.desc && <div className="text-xs text-zinc-500">{toast.desc}</div>}
        </div>
        {toast.action && <button onClick={toast.action.onClick} className="ml-2 text-xs font-semibold text-brand hover:underline">{toast.action.label}</button>}
      </div>
    </div>
  );
}

/* ---------- Hub de produtos monitorados ---------- */
function MonitoredHub({ items, onRemove, onSearch }) {
  const PLAT = {
    ml: { name: 'Mercado Livre', dot: 'bg-gold', tint: 'rgba(255,208,0,0.1)' },
    shopee: { name: 'Shopee', dot: 'bg-coral', tint: 'rgba(249,94,46,0.1)' },
  };
  const totalComm = items.reduce((s, i) => s + i.commission, 0);
  const alerts = items.filter((i) => i.dir === 'up' || i.dir === 'down').length;

  return (
    <main className="mx-auto w-full max-w-6xl flex-1 px-5 py-8">
      <div className="mb-6 flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
        <div>
          <h1 className="font-syne text-2xl font-extrabold tracking-tight text-white">Produtos monitorados</h1>
          <p className="mt-1 text-sm text-zinc-500">Acompanhamos preço e comissão por você. Avisamos quando vale a pena divulgar.</p>
        </div>
        <EBtn variant="secondary" onClick={onSearch}><EBox size={16} /> Buscar para monitorar</EBtn>
      </div>

      {items.length === 0 ? (
        <div className="flex flex-col items-center justify-center gap-3 rounded-2xl border border-dashed border-edge bg-panel/50 py-20 text-center">
          <span className="flex h-16 w-16 items-center justify-center rounded-2xl bg-brand/10 text-brand"><EBookmark size={28} /></span>
          <h3 className="font-syne text-xl font-bold text-white">Você ainda não monitora nada</h3>
          <p className="max-w-sm text-sm text-zinc-500">Faça uma busca e toque no marcador de um produto para acompanhá-lo. Avisamos quando o preço cair ou a comissão subir.</p>
          <EBtn className="mt-2" onClick={onSearch}>Fazer minha primeira busca <EArrow size={16} /></EBtn>
        </div>
      ) : (
        <>
          <div className="mb-5 grid grid-cols-2 gap-3 sm:grid-cols-3">
            {[
              { label: 'Monitorados', value: items.length, icon: EBookmark },
              { label: 'Alertas ativos', value: alerts, icon: EBolt },
              { label: 'Comissão potencial', value: eBRL(totalComm), icon: ETarget },
            ].map((s) => (
              <div key={s.label} className="rounded-2xl border border-edge bg-panel p-4">
                <span className="flex h-9 w-9 items-center justify-center rounded-lg bg-brand/10 text-brand"><s.icon size={17} /></span>
                <div className="mt-3 font-num text-2xl font-extrabold text-white">{s.value}</div>
                <div className="text-xs text-zinc-500">{s.label}</div>
              </div>
            ))}
          </div>

          <div className="space-y-3">
            {items.map((it) => {
              const p = PLAT[it.platform];
              const up = it.dir === 'up', down = it.dir === 'down';
              return (
                <div key={it.id} className="result-card flex flex-col gap-3 rounded-2xl border border-edge bg-panel p-4 sm:flex-row sm:items-center sm:gap-4">
                  <div className="flex min-w-0 flex-1 items-center gap-3 sm:gap-4">
                    <div className="relative h-14 w-14 shrink-0 overflow-hidden rounded-xl border border-edge sm:h-16 sm:w-16"
                      style={{ background: `repeating-linear-gradient(135deg, ${p.tint} 0 2px, transparent 2px 11px), #0d0d0d` }}>
                      <span className="flex h-full w-full items-center justify-center"><EBox size={20} className="text-zinc-600" /></span>
                    </div>
                    <div className="min-w-0 flex-1">
                      <div className="mb-1 flex items-center gap-2">
                        <span className={ecn('inline-flex items-center gap-1 text-[11px] font-semibold', it.platform === 'ml' ? 'text-gold' : 'text-coral')}><span className={ecn('h-1.5 w-1.5 rounded-full', p.dot)} />{p.name}</span>
                        {it.demo && <span className="rounded bg-white/[0.05] px-1.5 py-0.5 font-mono text-[9px] uppercase tracking-wider text-zinc-600">demo</span>}
                      </div>
                      <h3 className="line-clamp-1 text-sm font-medium text-zinc-100">{it.title}</h3>
                      <div className="mt-1 text-xs text-zinc-500">{eBRL(it.price)} · {ePct(it.rate)} comissão</div>
                    </div>
                  </div>

                  <div className="hidden items-center gap-2 md:flex">
                    <Sparkline points={it.spark} color={down ? '#F95E2E' : '#16BFA3'} />
                    <span className={ecn('inline-flex items-center gap-0.5 rounded-md px-1.5 py-0.5 text-xs font-semibold', up ? 'bg-brand/12 text-brand' : down ? 'bg-coral/12 text-coral' : 'bg-white/[0.06] text-zinc-400')}>
                      {up ? <ETrendUp size={13} /> : down ? <ETrendDown size={13} /> : null}{it.changePct > 0 ? `${it.changePct}%` : 'estável'}
                    </span>
                  </div>

                  <div className="flex items-center justify-between gap-4 border-t border-edge/60 pt-3 sm:justify-end sm:border-0 sm:pt-0 sm:gap-5">
                    <div className="text-left sm:text-right">
                      <div className="text-[10px] uppercase tracking-wide text-zinc-500">Comissão</div>
                      <ECommission value={it.commission} className="text-lg text-brand" />
                    </div>
                    <div className="flex items-center gap-1.5">
                      <a href={it.link} target="_blank" rel="noopener noreferrer"><EBtn size="sm" variant="secondary"><EExternal size={15} /></EBtn></a>
                      <button onClick={() => onRemove(it.id)} aria-label="Remover" className="flex h-9 w-9 items-center justify-center rounded-xl border border-edge text-zinc-500 transition-colors hover:border-coral/40 hover:text-coral"><ETrash size={15} /></button>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>

          <div className="mt-5 flex items-center gap-3 rounded-2xl border border-brand/25 bg-brand/[0.05] px-4 py-3">
            <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-brand/12 text-brand"><EBell size={17} /></span>
            <p className="text-sm text-zinc-300">Você recebe um alerta sempre que um destes produtos ficar mais vantajoso. <span className="text-zinc-500">Os avisos aparecem no sininho do topo.</span></p>
          </div>
        </>
      )}
    </main>
  );
}

/* ---------- Constrói uma entrada monitorada a partir de um resultado ---------- */
function buildMonitored(item) {
  const seed = hashId(item.id);
  const dir = ['up', 'down', 'flat'][seed % 3];
  const changePct = dir === 'flat' ? 0 : (seed % 18) + 3;
  return { ...item, spark: sparkFor(item.id, item.commission), dir, changePct, addedAt: Date.now() };
}

Object.assign(window, { NotificationsMenu, StreakPill, MonitorButton, Toast, MonitoredHub, buildMonitored, seedNotifications, relTime });
