/* app.jsx — AchaMais */
const { useState, useCallback, useMemo, useRef, useEffect } = React;
const {
  Button, Input, Commission, Card, CardContent, CardFooter, Badge, Separator, Skeleton,
  Alert, AlertDescription, Tabs, Select, Dialog, Tooltip,
  IconSearch, IconExternal, IconStar, IconX, IconAlert, IconBox, IconGear,
  IconGrid, IconList, IconLogout, IconChart, IconLink, IconBookmark, IconFire, IconFireGradient,
  AuthScreen, Footer, Landing, LinksPage, Checkout, AccountMenu, AccountPage,
  NotificationsMenu, StreakPill, MonitorButton, Toast, MonitoredHub, buildMonitored, seedNotifications, TrendsPage,
  formatBRL, formatPct, searchMercadoLivre, searchShopee, demoResults
} = window;

const PLATFORM = {
  ml: { name: 'Mercado Livre', short: 'ML', badge: 'ml', glow: 'card-ml', text: 'text-gold', dot: 'bg-gold' },
  shopee: { name: 'Shopee', short: 'Shopee', badge: 'shopee', glow: 'card-shopee', text: 'text-coral', dot: 'bg-coral' }
};

const SORTS = [
{ value: 'comm', label: 'Maior comissão (R$)' },
{ value: 'price', label: 'Menor preço' },
{ value: 'pct', label: 'Maior comissão (%)' }];


const SUGGESTIONS = ['fone bluetooth', 'air fryer', 'tênis corrida', 'kit maquiagem', 'smartwatch', 'cafeteira'];

/* ---------- Placeholder de imagem ---------- */
function ProductImage({ item }) {
  if (item.image) {
    return <img src={item.image} alt={item.title} loading="lazy" className="h-full w-full object-cover" onError={(e) => {e.target.style.display = 'none';}} />;
  }
  const tint = item.platform === 'ml' ? 'rgba(255,208,0,0.10)' : 'rgba(249,94,46,0.10)';
  return (
    <div className="flex h-full w-full flex-col items-center justify-center gap-1.5"
    style={{ background: `repeating-linear-gradient(135deg, ${tint} 0 2px, transparent 2px 11px), #0d0d0d` }}>
      <IconBox size={22} className="text-zinc-600" />
      <span className="font-mono text-[9px] uppercase tracking-widest text-zinc-600">{item.categoryLabel || 'produto'}</span>
    </div>);

}

/* ---------- Card de resultado (grid) ---------- */
function ResultCard({ item, best, monitored, onMonitor }) {
  const p = PLATFORM[item.platform];
  return (
    <Card className={cn('result-card group relative flex flex-col', p.glow, best && 'ring-1 ring-brand/40')}>
      <div className="relative h-44 overflow-hidden border-b border-edge bg-[#0d0d0d]">
        <ProductImage item={item} />
        <div className="absolute left-3 top-3">
          <Badge variant={p.badge}><span className={cn('h-1.5 w-1.5 rounded-full', p.dot)} />{p.name}</Badge>
        </div>
        <div className="absolute right-3 top-3">
          <MonitorButton active={monitored} onClick={() => onMonitor(item)} floating />
        </div>
        {item.demo && <span className="absolute bottom-2 right-2 rounded bg-black/60 px-1.5 py-0.5 font-mono text-[9px] uppercase tracking-wider text-zinc-400">demo</span>}
      </div>

      <CardContent className="flex flex-1 flex-col gap-3">
        <h3 className="line-clamp-2 min-h-[2.6rem] text-sm font-medium leading-snug text-zinc-100">{item.title}</h3>
        <div className="flex items-center justify-between">
          <div>
            <div className="text-[11px] uppercase tracking-wide text-zinc-500">Preço</div>
            <div className="text-base font-semibold tabular-nums text-zinc-200">{formatBRL(item.price)}</div>
          </div>
          <Badge variant="neutral">{formatPct(item.rate)} comissão</Badge>
        </div>
        <Separator />
        <div className="mt-auto">
          <div className="flex items-center gap-2">
            <div className="text-[11px] uppercase tracking-wide text-zinc-500">Comissão estimada</div>
            {best &&
            <span className="best-pulse inline-flex items-center gap-1 rounded-full bg-brand px-1.5 py-0.5 text-[9px] font-bold text-ink">
                <IconStar size={9} fill="#0A0A0A" /> melhor
              </span>
            }
          </div>
          <Commission value={item.commission} className="text-2xl text-brand" />
        </div>
      </CardContent>

      <CardFooter>
        <a href={item.link} target="_blank" rel="noopener noreferrer" className="block">
          <Button variant={item.platform === 'ml' ? 'default' : 'coral'} className="w-full">
            Ver oferta <IconExternal size={16} />
          </Button>
        </a>
      </CardFooter>
    </Card>);

}

/* ---------- Linha de resultado (lista) ---------- */
function ResultRow({ item, best, monitored, onMonitor }) {
  const p = PLATFORM[item.platform];
  return (
    <Card className={cn('result-card group p-4', p.glow, best && 'ring-1 ring-brand/40')}>
      <div className="flex items-start gap-4">
        <div className="relative h-16 w-16 shrink-0 overflow-hidden rounded-xl border border-edge bg-[#0d0d0d]">
          <ProductImage item={item} />
          {best &&
          <span className="absolute left-1 top-1 flex h-4 w-4 items-center justify-center rounded-full bg-brand text-ink shadow" title="Melhor oportunidade">
              <IconStar size={9} fill="#0A0A0A" />
            </span>
          }
        </div>

        <div className="min-w-0 flex-1">
          <div className="mb-1.5 flex flex-wrap items-center gap-x-2 gap-y-1">
            <span className={cn('inline-flex shrink-0 items-center gap-1 whitespace-nowrap text-[11px] font-semibold', p.text)}>
              <span className={cn('h-1.5 w-1.5 rounded-full', p.dot)} />{p.name}
            </span>
            {best && <span className="inline-flex items-center gap-1 whitespace-nowrap rounded-full bg-brand/12 px-1.5 py-0.5 text-[10px] font-semibold text-brand"><IconStar size={9} fill="currentColor" /> Melhor oportunidade</span>}
            {item.demo && <span className="rounded bg-white/[0.05] px-1 py-0.5 font-mono text-[8px] uppercase tracking-wider text-zinc-600">demo</span>}
          </div>
          <h3 className="line-clamp-2 text-[15px] font-semibold leading-snug text-zinc-100">{item.title}</h3>
          <div className="mt-1.5 text-xs text-zinc-500"><span className="tabular-nums text-zinc-400">{formatBRL(item.price)}</span> · {formatPct(item.rate)} de comissão</div>
        </div>

        {/* Comissão — desktop */}
        <div className="hidden shrink-0 flex-col items-end self-center border-l border-edge pl-6 sm:flex">
          <div className="text-[10px] uppercase tracking-wide text-zinc-500">Comissão</div>
          <Commission value={item.commission} className="mt-0.5 text-xl text-brand" />
        </div>

        {/* Monitorar — desktop */}
        <div className="hidden shrink-0 self-center sm:block">
          <MonitorButton active={monitored} onClick={() => onMonitor(item)} />
        </div>

        {/* Ver oferta — desktop, sozinho */}
        <div className="hidden shrink-0 self-center sm:block">
          <a href={item.link} target="_blank" rel="noopener noreferrer">
            <Button variant={item.platform === 'ml' ? 'default' : 'coral'} className="px-5">
              Ver oferta <IconExternal size={15} />
            </Button>
          </a>
        </div>
      </div>

      {/* Comissão + ações — mobile */}
      <div className="mt-3.5 flex items-center justify-between border-t border-edge pt-3.5 sm:hidden">
        <div>
          <div className="text-[10px] uppercase tracking-wide text-zinc-500">Comissão</div>
          <Commission value={item.commission} className="text-lg text-brand" />
        </div>
        <div className="flex items-center gap-2">
          <MonitorButton active={monitored} onClick={() => onMonitor(item)} />
          <a href={item.link} target="_blank" rel="noopener noreferrer">
            <Button variant={item.platform === 'ml' ? 'default' : 'coral'} size="sm" className="px-4">
              Ver oferta <IconExternal size={14} />
            </Button>
          </a>
        </div>
      </div>
    </Card>);

}

/* ---------- Skeletons ---------- */
function CardSkeleton() {
  return (
    <Card className="flex flex-col">
      <Skeleton className="h-44 w-full rounded-none" />
      <CardContent className="flex flex-col gap-3">
        <Skeleton className="h-4 w-5/6" /><Skeleton className="h-4 w-2/3" />
        <div className="flex justify-between pt-1"><Skeleton className="h-8 w-20" /><Skeleton className="h-5 w-16" /></div>
        <Skeleton className="h-7 w-28" />
      </CardContent>
      <CardFooter><Skeleton className="h-11 w-full" /></CardFooter>
    </Card>);

}
function RowSkeleton() {
  return (
    <Card className="flex flex-row items-center gap-4 p-3">
      <Skeleton className="h-20 w-20 shrink-0 sm:h-24 sm:w-24" />
      <div className="flex-1 space-y-2"><Skeleton className="h-4 w-24" /><Skeleton className="h-4 w-3/4" /><Skeleton className="h-3 w-1/3" /></div>
      <Skeleton className="h-11 w-28 shrink-0" />
    </Card>);

}

/* ---------- Toggle de visualização ---------- */
function ViewToggle({ view, onChange }) {
  const opts = [['card', IconGrid, 'Cards'], ['list', IconList, 'Lista']];
  return (
    <div className="inline-flex items-center rounded-xl border border-edge bg-white/[0.04] p-1">
      {opts.map(([v, Icon, label]) =>
      <Tooltip key={v} label={label}>
          <button onClick={() => onChange(v)} aria-label={label}
        className={cn('flex h-8 w-9 items-center justify-center rounded-lg transition-all', view === v ? 'bg-white/[0.1] text-white shadow-sm' : 'text-zinc-500 hover:text-zinc-300')}>
            <Icon size={17} />
          </button>
        </Tooltip>
      )}
    </div>);

}

/* ====================== APP ====================== */
function App() {
  const [user, setUser] = useState(null);
  const [showAuth, setShowAuth] = useState(false);
  const [authMode, setAuthMode] = useState('login');
  const [page, setPage] = useState('search');
  const [accountSection, setAccountSection] = useState('perfil');
  const [pendingCheckout, setPendingCheckout] = useState(false);
  const [plan, setPlan] = useState('free');
  const [mlToken, setMlToken] = useState('');
  const [shopeeToken, setShopeeToken] = useState('');
  const [query, setQuery] = useState('');
  const [submitted, setSubmitted] = useState('');
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState([]);
  const [notices, setNotices] = useState({ ml: false, shopee: false });
  const [tokenMissing, setTokenMissing] = useState(false);
  const [sort, setSort] = useState('comm');
  const [tab, setTab] = useState('all');
  const [view, setView] = useState('card');
  const [hasSearched, setHasSearched] = useState(false);
  const [monitored, setMonitored] = useState([]);
  const [notifications, setNotifications] = useState(seedNotifications);
  const [toast, setToast] = useState(null);
  const toastTimer = useRef(null);
  const streak = 7;
  const inputRef = useRef(null);

  const showToast = useCallback((t) => {
    setToast(t);
    if (toastTimer.current) clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToast(null), 3400);
  }, []);

  const isMonitored = useCallback((id) => monitored.some((m) => m.id === id), [monitored]);

  const toggleMonitor = useCallback((item) => {
    const exists = monitored.some((m) => m.id === item.id);
    if (exists) {
      setMonitored((prev) => prev.filter((m) => m.id !== item.id));
      showToast({ title: 'Removido dos monitorados', desc: item.title });
    } else {
      setMonitored((prev) => [buildMonitored(item), ...prev]);
      setNotifications((ns) => [{ id: 'mon-' + item.id + '-' + Date.now(), type: 'system', title: 'Monitoramento ativado', desc: `Vamos te avisar sobre mudanças em "${item.title}".`, min: 0, read: false }, ...ns]);
      showToast({ title: 'Produto monitorado', desc: 'Avisaremos sobre preço e comissão.', tone: 'brand', action: { label: 'Ver', onClick: () => setPage('monitor') } });
    }
  }, [monitored, showToast]);

  const markAllRead = () => setNotifications((ns) => ns.map((n) => ({ ...n, read: true })));
  const markRead = (id) => setNotifications((ns) => ns.map((n) => n.id === id ? { ...n, read: true } : n));
  const clearNotifs = () => setNotifications([]);

  const runSearch = useCallback(async (rawTerm) => {
    const term = (rawTerm != null ? rawTerm : query).trim();
    if (!term) return;
    setQuery(term);
    setSubmitted(term);
    setHasSearched(true);
    setLoading(true);
    setResults([]);
    setNotices({ ml: false, shopee: false });

    const [mlRes, spRes] = await Promise.allSettled([
    searchMercadoLivre(term, mlToken),
    searchShopee(term, shopeeToken)]
    );

    let combined = [];
    const notes = { ml: false, shopee: false };

    if (mlRes.status === 'fulfilled' && mlRes.value.length) combined = combined.concat(mlRes.value);else
    {combined = combined.concat(demoResults(term, 'ml'));notes.ml = true;}

    if (spRes.status === 'fulfilled' && spRes.value.length) combined = combined.concat(spRes.value);else
    if (shopeeToken) {combined = combined.concat(demoResults(term, 'shopee'));notes.shopee = true;}

    setResults(combined);
    setNotices(notes);
    setTokenMissing(!shopeeToken);
    setLoading(false);
  }, [query, mlToken, shopeeToken]);

  const bestId = useMemo(() => {
    if (!results.length) return null;
    return results.reduce((b, r) => r.commission > b.commission ? r : b, results[0]).id;
  }, [results]);

  const visible = useMemo(() => {
    const arr = results.filter((r) => tab === 'all' || r.platform === tab);
    const cmp = {
      comm: (a, b) => b.commission - a.commission,
      price: (a, b) => a.price - b.price,
      pct: (a, b) => b.rate - a.rate
    }[sort];
    return [...arr].sort(cmp);
  }, [results, tab, sort]);

  const counts = useMemo(() => ({
    all: results.length,
    ml: results.filter((r) => r.platform === 'ml').length,
    shopee: results.filter((r) => r.platform === 'shopee').length
  }), [results]);

  const openAccount = (sec) => { setAccountSection(sec); setPage('account'); };
  const clearQuery = () => {setQuery('');if (inputRef.current) inputRef.current.focus();};
  const onSubmit = (e) => {e.preventDefault();runSearch();};

  /* ----- Landing + Gate de autenticação ----- */
  if (!user) {
    return showAuth ?
    <AuthScreen
      initialMode={authMode}
      onBack={() => setShowAuth(false)}
      onAuth={(u) => {setUser(u);setShowAuth(false);setPage(pendingCheckout ? 'checkout' : 'search');setPendingCheckout(false);}} /> :

    <Landing
      onStart={() => {setAuthMode('register');setShowAuth(true);}}
      onLogin={() => {setAuthMode('login');setShowAuth(true);}}
      onSubscribe={() => {setAuthMode('register');setPendingCheckout(true);setShowAuth(true);}} />;

  }

  const initial = (user.name || user.email || '?').trim().charAt(0).toUpperCase();
  const apiConnected = !!shopeeToken;

  return (
    <div className="flex min-h-screen flex-col">
      {/* Header */}
      <header className="sticky top-0 z-40 border-b border-edge bg-ink/80 backdrop-blur-xl">
        <div className="mx-auto flex max-w-6xl items-center justify-between gap-3 px-5 py-3">
          <div className="flex items-center gap-2.5">
            <span className="flex h-9 w-9 items-center justify-center rounded-xl bg-gradient-to-br from-brand to-coral text-ink shadow-[0_4px_18px_-4px_rgba(22,191,163,0.5)]">
              <IconSearch size={18} className="text-ink" />
            </span>
            <span className="font-syne text-xl font-extrabold tracking-tight text-white">Acha<span className="text-brand">Mais</span></span>
          </div>

          <nav className="hidden items-center gap-1 rounded-xl border border-edge bg-white/[0.04] p-1 md:flex">
            {[['search', 'Buscar', IconSearch], ['trends', 'Trends', IconFire], ['monitor', 'Monitorados', IconBookmark], ['links', 'Links', IconLink]].map(([k, label, Icon]) =>
            <button key={k} onClick={() => setPage(k)}
            className={cn('relative inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-sm font-medium transition-all lg:px-3', page === k ? 'bg-white/[0.1] text-white shadow-sm' : 'text-zinc-400 hover:text-zinc-200')}>
                {k === 'trends' ? <IconFireGradient size={16} /> : <Icon size={16} />} <span className="hidden lg:inline">{label}</span>
                {k === 'monitor' && monitored.length > 0 &&
                <span className="flex h-4 min-w-[16px] items-center justify-center rounded-full bg-brand px-1 text-[10px] font-bold text-ink">{monitored.length}</span>
                }
              </button>
            )}
          </nav>

          <div className="flex items-center gap-1.5 sm:gap-2">
            <StreakPill days={streak} />
            <NotificationsMenu items={notifications} onMarkAll={markAllRead} onItem={markRead} onClear={clearNotifs} />
            <AccountMenu
              user={user}
              plan={plan}
              apiConnected={apiConnected}
              onSelect={openAccount}
              onLogout={() => {setUser(null);setHasSearched(false);setResults([]);setQuery('');setPage('search');}} />
          </div>
        </div>
      </header>

      {page === 'checkout' ?
      <Checkout user={user} onBack={() => setPage('search')} onSuccess={() => {setPlan('pro');setPage('search');}} /> :
      page === 'account' ?
      <AccountPage
        section={accountSection}
        onSection={setAccountSection}
        user={user}
        onUpdateUser={setUser}
        plan={plan}
        onUpgrade={() => setPage('checkout')}
        onCancelPlan={() => setPlan('free')}
        mlToken={mlToken}
        shopeeToken={shopeeToken}
        onSaveTokens={({ ml, shopee }) => {setMlToken(ml);setShopeeToken(shopee);}} /> :
      page === 'dashboard' || page === 'links' ?
      <LinksPage apiMl={!!mlToken} apiShopee={!!shopeeToken} onConfigApi={() => openAccount('api')} onSearch={() => setPage('search')} /> :
      page === 'monitor' ?
      <MonitoredHub items={monitored} onRemove={(id) => setMonitored((prev) => prev.filter((m) => m.id !== id))} onSearch={() => setPage('search')} /> :
      page === 'trends' ?
      <TrendsPage onMonitor={toggleMonitor} isMonitored={isMonitored} onSearch={() => setPage('search')} /> :

      <main className="mx-auto w-full max-w-6xl flex-1 px-5">
        {/* Hero / busca */}
        <section className={cn('mx-auto text-center transition-all', hasSearched ? 'pt-10 pb-6' : 'pt-20 pb-10')}>
          {!hasSearched &&
          <>
              <Badge variant="brand" className="mb-5">Mercado Livre + Shopee em uma busca só</Badge>
              <h1 className="mx-auto max-w-2xl text-balance font-syne text-4xl font-extrabold leading-[1.05] tracking-tight text-white sm:text-5xl">
                Descubra os produtos que <span className="text-brand">mais pagam</span> comissão
              </h1>
              <p className="mx-auto mt-4 max-w-xl text-pretty text-zinc-400">
                Pesquise um produto e compare preço e comissão real das duas plataformas, lado a lado, na hora.
              </p>
            </>
          }

          <form onSubmit={onSubmit} className={cn('mx-auto mt-7 flex max-w-2xl items-center gap-2', hasSearched && 'mt-0 max-w-3xl')}>
            <div className="relative flex-1">
              <span className="pointer-events-none absolute left-4 top-1/2 -translate-y-1/2 text-zinc-500"><IconSearch size={20} /></span>
              <input
                ref={inputRef}
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="Buscar produto… ex: fone bluetooth"
                className="h-14 w-full rounded-xl border border-edge bg-white/[0.04] pl-12 pr-11 text-base text-zinc-100 placeholder:text-zinc-500 transition-all focus:border-brand/60 focus:outline-none focus:ring-2 focus:ring-brand/25" />
              
              {query &&
              <button type="button" onClick={clearQuery} aria-label="Limpar busca"
              className="absolute right-3 top-1/2 flex h-7 w-7 -translate-y-1/2 items-center justify-center rounded-full text-zinc-500 transition-colors hover:bg-white/[0.08] hover:text-white">
                  <IconX size={16} />
                </button>
              }
            </div>
            <Button type="submit" size="lg" disabled={loading}>
              {loading ? 'Buscando…' : 'Buscar'}
            </Button>
          </form>

          {!hasSearched &&
          <div className="mx-auto mt-5 flex max-w-2xl flex-wrap items-center justify-center gap-2">
              <span className="text-xs text-zinc-600">Produtos mais buscados:</span>
              {SUGGESTIONS.map((s) =>
            <button key={s} onClick={() => runSearch(s)} className="rounded-full border border-edge bg-white/[0.03] px-3 py-1 text-xs text-zinc-400 transition-colors hover:border-brand/40 hover:text-brand">{s}</button>
            )}
            </div>
          }
        </section>

        {/* Avisos */}
        {hasSearched && !loading &&
        <div className="space-y-2.5 pb-2">
            {tokenMissing &&
          <Alert tone="coral">
                <span className="mt-0.5"><IconAlert size={18} /></span>
                <AlertDescription className="flex flex-1 flex-wrap items-center justify-between gap-2">
                  <span><span className="font-semibold">Shopee não configurada.</span> <span className="text-coral/80">Adicione seu token no painel de APIs para incluir as ofertas da Shopee — a busca no Mercado Livre continua normalmente.</span></span>
                  <button onClick={() => openAccount('api')} className="shrink-0 rounded-lg border border-coral/40 px-3 py-1 text-xs font-semibold text-coral hover:bg-coral/10">Configurar agora</button>
                </AlertDescription>
              </Alert>
          }
            {(notices.ml || notices.shopee) &&
          <Alert tone="neutral">
                <span className="mt-0.5 text-zinc-500"><IconAlert size={18} /></span>
                <AlertDescription className="text-zinc-400">
                  <span className="font-medium text-zinc-300">Modo demonstração.</span> Não foi possível acessar {notices.ml && notices.shopee ? 'as APIs do Mercado Livre e da Shopee' : notices.ml ? 'a API do Mercado Livre' : 'a API da Shopee'} diretamente do navegador (bloqueio de CORS/autenticação). Exibindo dados de exemplo para você ver a experiência completa.
                </AlertDescription>
              </Alert>
          }
          </div>
        }

        {/* Controles */}
        {hasSearched &&
        <div className="flex flex-col gap-3 py-4 lg:flex-row lg:items-center lg:justify-between">
            <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-4">
              <Tabs
              value={tab}
              onValueChange={setTab}
              items={[
              { value: 'all', label: `Todas (${counts.all})` },
              { value: 'ml', label: `ML (${counts.ml})`, dot: 'bg-gold' },
              { value: 'shopee', label: `Shopee (${counts.shopee})`, dot: 'bg-coral' }]
              } />
            
              {!loading && submitted && <span className="text-sm text-zinc-500">para <span className="font-medium text-zinc-300">“{submitted}”</span></span>}
            </div>
            <div className="flex items-center gap-2.5">
              <ViewToggle view={view} onChange={setView} />
              <Select value={sort} onChange={setSort} options={SORTS} className="w-full sm:w-60" />
            </div>
          </div>
        }

        {/* Resultados */}
        {view === 'card' ?
        <section className="grid grid-cols-1 gap-4 pb-16 sm:grid-cols-2 lg:grid-cols-3">
            {loading ?
          Array.from({ length: 6 }).map((_, i) => <CardSkeleton key={i} />) :
          visible.map((item) => <ResultCard key={item.id} item={item} best={item.id === bestId} monitored={isMonitored(item.id)} onMonitor={toggleMonitor} />)}
          </section> :

        <section className="flex flex-col gap-3 pb-16">
            {loading ?
          Array.from({ length: 5 }).map((_, i) => <RowSkeleton key={i} />) :
          visible.map((item) => <ResultRow key={item.id} item={item} best={item.id === bestId} monitored={isMonitored(item.id)} onMonitor={toggleMonitor} />)}
          </section>
        }

        {/* Vazio */}
        {hasSearched && !loading && visible.length === 0 &&
        <div className="flex flex-col items-center justify-center gap-3 py-24 text-center">
            <span className="flex h-14 w-14 items-center justify-center rounded-2xl border border-edge bg-white/[0.03] text-zinc-600"><IconSearch size={26} /></span>
            <h3 className="font-syne text-xl font-bold text-white">Nenhum resultado encontrado</h3>
            <p className="max-w-sm text-sm text-zinc-500">Tente outro termo ou ajuste o filtro de plataforma acima.</p>
          </div>
        }
      </main>
      }

      <div className="h-16 md:hidden" />

      {/* Bottom nav (mobile) */}
      <nav className="fixed inset-x-0 bottom-0 z-40 grid grid-cols-4 border-t border-edge bg-ink/95 backdrop-blur-xl md:hidden">
        {[['search', 'Buscar', IconSearch], ['trends', 'Trends', IconFire], ['monitor', 'Monitor', IconBookmark], ['links', 'Links', IconLink]].map(([k, label, Icon]) =>
        <button key={k} onClick={() => setPage(k)}
        className={cn('relative flex flex-col items-center justify-center gap-1 py-2.5 text-[11px] font-medium transition-colors', page === k ? 'text-brand' : 'text-zinc-500')}>
            <span className="relative">
              {k === 'trends' ? <IconFireGradient size={20} /> : <Icon size={20} />}
              {k === 'monitor' && monitored.length > 0 &&
              <span className="absolute -right-2 -top-1.5 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-brand px-1 text-[9px] font-bold text-ink">{monitored.length}</span>
              }
            </span>
            {label}
          </button>
        )}
      </nav>

      <Footer />
      <Toast toast={toast} />
    </div>);

}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);