Clipador: subpáginas, jogos, idioma por canal e juiz com Gemini e IA reserva

- Clipador em subpáginas (Cortes, Sessões, Fontes, Jogos, Ajustes) com moldura comum, lista + diálogo
  dos cortes e submenu na barra lateral.
- Perfis de jogo (o que a IA sabe de cada jogo), parar pausa o monitor e idioma por fonte e por canal
  de publicação (migração v9: accounts.language).
- Juiz: Gemini CLI como terceiro provedor e IA reserva por chamada — se a IA escolhida cair por cota,
  login, chave ou rede, a próxima da ordem de Configurações → IA responde (com pausa da que caiu).
  Lê data/ai/settings.json e o cofre data/ai/vault.bin (DPAPI) escritos pelo painel; contrato em doc/ia.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 01:51:12 -03:00
co-authored by Claude Opus 5.5
parent 2d8b1a582d
commit 0567c7454a
55 changed files with 6514 additions and 2506 deletions
+18 -539
View File
@@ -1,17 +1,15 @@
"use client";
// Contexto do jogo e emotes do Clipador: o jogo da sessão (com correção à mão e aviso quando a tela
// diverge da categoria), o perfil que a IA pesquisou ("O que a IA sabe do jogo") e a tabela de emotes
// do canal com o peso que eles aprenderam com as suas aprovações.
import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react";
// diverge da categoria), o atalho "O que a IA sabe do jogo" (abre o modal do jogo, clipper-game-dialog.tsx) e a
// tabela de emotes do canal com o peso que eles aprenderam com as suas aprovações.
// A página Jogos (lista + modal) fica em clipper-games-page.tsx.
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
GAME_SOURCE_LABEL, clipperCall, gameIdOf, useClipperAction, type ClipperSession, type Emote, type Game, type GameProfile,
GAME_SOURCE_LABEL, clipperCall, gameIdOf, useClipperAction, type ClipperSession, type Emote, type Game,
} from "./clipper-client";
import type { ApiResult } from "./api-client";
import { AlertIcon, BookIcon, ChatIcon, CheckIcon, ChevronDownIcon, LinkIcon, PenIcon, RefreshIcon, SendIcon, SparkIcon, XIcon } from "./icons";
import {
Badge, Button, EmptyState, Feedback, Field, Input, Spinner, Switch, Table, Td, Th, THead, Textarea, Tr, cx, formatRelative, hueOf,
} from "./ui";
import { askConfirm } from "./confirm-dialog";
import { GameDialog } from "./clipper-game-dialog";
import { AlertIcon, BookIcon, ChatIcon, CheckIcon, ChevronDownIcon, PenIcon } from "./icons";
import { Badge, Button, Feedback, Input, Spinner, Table, Td, Th, THead, Tr, cx, formatRelative } from "./ui";
/* ---------- Jogo da sessão ---------- */
@@ -25,7 +23,7 @@ export function SessionGame({ session, games, onChanged, onGamesChanged }: {
const screen = session.screenGame ?? "";
const confirmed = session.gameSource === "user";
const mismatch = Boolean(game && screen && !confirmed && gameIdOf(screen) !== gameIdOf(game));
const profile = game ? games.find((g) => g.id === gameIdOf(game)) : undefined;
const profile = game ? findGame(games, game) : undefined;
/** Confirma o jogo: trava a troca automática e a IA deixa de questionar o que vê na tela. */
async function confirmGame(name: string) {
@@ -51,10 +49,9 @@ export function SessionGame({ session, games, onChanged, onGamesChanged }: {
)}
<Button variant="ghost" size="sm" onClick={() => setChoosing(true)}><PenIcon size={14} />{confirmed ? "Trocar jogo" : "Escolher o jogo"}</Button>
{game && (
<Button variant="ghost" size="sm" aria-expanded={open} onClick={() => setOpen((o) => !o)}>
<Button variant="ghost" size="sm" aria-haspopup="dialog" onClick={() => setOpen(true)}>
<BookIcon size={14} />O que a IA sabe do jogo
{profile?.status === "pending" && <Spinner className="size-3" />}
<ChevronDownIcon size={14} className={cx("transition-transform", open && "rotate-180")} />
</Button>
)}
</div>
@@ -68,14 +65,19 @@ export function SessionGame({ session, games, onChanged, onGamesChanged }: {
)}
<GameChoiceDialog open={choosing} session={session} pending={pending === "game"}
onClose={() => setChoosing(false)} onConfirm={(name) => void confirmGame(name)} />
{open && game && (
<GameCard game={profile} name={game} onGamesChanged={onGamesChanged} />
)}
{game && <GameDialog game={profile} name={game} open={open} onClose={() => setOpen(false)} onGamesChanged={onGamesChanged} />}
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
);
}
/** Jogo cadastrado com esse nome: pelo id ou por um dos outros nomes (aliases). */
function findGame(games: Game[], name: string): Game | undefined {
const id = gameIdOf(name);
return games.find((g) => g.id === id)
?? games.find((g) => [...(g.aliases ?? []), ...(g.profile?.aliases ?? []), ...(g.profileAi?.aliases ?? [])].some((a) => gameIdOf(a) === id));
}
/* ---------- Escolher/confirmar o jogo ---------- */
/** Modal nativo: o usuário confirma qual jogo está sendo jogado (categoria, o que a IA viu na tela ou outro nome). */
@@ -150,529 +152,6 @@ function GameChoiceDialog({ open, session, pending, onClose, onConfirm }: {
);
}
/* ---------- Perfil do jogo ---------- */
type GameAction = "research" | "save" | "note";
type GamesReply = { games: Game[] };
type RefineReply = GamesReply & { reply?: string };
type ListKey = Exclude<keyof GameProfile, "name" | "summary" | "genre">;
/** Seção que o chat da IA edita ("" = o perfil inteiro). */
type SectionKey = ListKey | "summary" | "";
/** Como cada seção aparece: cor, ícone, dica de edição e atalhos de pedido para o chat. */
const SECTIONS: Record<ListKey, { title: string; tone: "success" | "danger" | "info" | "violet" | "neutral"; hint: string; suggestions: string[] }> = {
clip_worthy: {
title: "O que rende corte", tone: "success", hint: "Uma situação por linha.",
suggestions: ["Reação do streamer conta (grito, risada, raiva)", "Momentos em que o chat explode de emotes", "Falha engraçada ou bug bizarro"],
},
avoid: {
title: "Evitar", tone: "danger", hint: "Uma situação por linha.",
suggestions: ["Tela de carregamento e fila", "Streamer lendo doação sem reação", "AFK ou pausa"],
},
mechanics: { title: "Mecânicas", tone: "info", hint: "Uma por linha.", suggestions: ["Explique melhor as mecânicas que aparecem nas lives", "Acrescente as mecânicas da última atualização"] },
news: { title: "Novidades", tone: "violet", hint: "Uma por linha, com mês/ano.", suggestions: ["Pesquise as novidades deste mês", "Tire as novidades com mais de 6 meses"] },
jargon: { title: "Gírias e termos", tone: "neutral", hint: "Um por linha.", suggestions: ["Acrescente as gírias que o chat usa", "Explique cada gíria em poucas palavras"] },
hashtags: {
title: "Hashtags", tone: "violet",
hint: "Uma por linha, a principal primeiro. As 3 primeiras entram em toda legenda de corte deste jogo, junto com a do canal e as do momento.",
suggestions: ["Pesquise as hashtags que o público usa para este jogo no TikTok", "Acrescente a hashtag do modo que o streamer joga"],
},
sources: { title: "Fontes", tone: "neutral", hint: "Uma URL por linha.", suggestions: [] },
};
const TONE_TEXT = { success: "text-success", danger: "text-danger", info: "text-info", violet: "text-violet", neutral: "text-fg-subtle" } as const;
const TONE_BAR = { success: "bg-success", danger: "bg-danger", info: "bg-info", violet: "bg-violet", neutral: "bg-line-strong" } as const;
/**
* Ações do perfil do jogo que não são o chat: pesquisar de novo, salvar a edição à mão, esquecer um pedido.
* Pesquisa pode levar minutos: se o painel desistir de esperar, o serviço segue.
*/
function useGameActions(onGamesChanged: (games: Game[]) => void) {
const [pending, setPending] = useState<GameAction | null>(null);
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null);
async function run(action: GameAction, call: () => Promise<ApiResult<GamesReply>>, okText: string, slow = false) {
setPending(action);
setMessage(null);
const r = await call();
setPending(null);
if (r.ok) {
onGamesChanged(r.data.games);
setMessage({ ok: true, text: okText });
return true;
}
setMessage({ ok: false, text: slow ? `${r.error} Se demorou demais, a IA pode continuar no serviço: clique em Atualizar daqui a pouco.` : r.error });
if (slow) {
const list = await clipperCall<GamesReply>("games");
if (list.ok) onGamesChanged(list.data.games);
}
return false;
}
return { pending, message, run };
}
/** Iniciais do jogo para o selo: primeira e última palavra ("Call of Duty: Warzone" → "CW"). */
function monogram(title: string): string {
const words = title.replace(/[^\p{L}\p{N} ]/gu, " ").split(/\s+/).filter(Boolean);
if (words.length === 0) return "?";
return (words.length === 1 ? words[0].slice(0, 2) : words[0][0] + words[words.length - 1][0]).toUpperCase();
}
/** Itens que entraram/saíram numa lista (para destacar o que a IA acrescentou). */
function diffList(before: string[] = [], after: string[] = []) {
const had = new Set(before.map((s) => s.toLowerCase()));
const has = new Set(after.map((s) => s.toLowerCase()));
return { added: after.filter((s) => !had.has(s.toLowerCase())), removed: before.filter((s) => !has.has(s.toLowerCase())) };
}
export function GameCard({ game, name, onGamesChanged }: { game: Game | undefined; name: string; onGamesChanged: (games: Game[]) => void }) {
const { pending, message, run } = useGameActions(onGamesChanged);
const [editing, setEditing] = useState(false);
const [chatOpen, setChatOpen] = useState<SectionKey | null>(null);
const [chatBusy, setChatBusy] = useState(false);
const [fresh, setFresh] = useState<Set<string>>(new Set()); // itens que a IA acabou de acrescentar (destaque)
const id = game?.id ?? gameIdOf(name);
const path = `games/${encodeURIComponent(id)}`;
const busy = pending !== null || chatBusy || game?.status === "pending";
const title = game?.profile?.name || game?.name || name;
const hue = hueOf(title);
async function research() {
// Pesquisar refaz o perfil do zero: a edição à mão some; os pedidos guardados entram de novo na pesquisa.
if (game?.editedAt && !(await askConfirm({ title: "Pesquisar de novo?",
message: "Refaz o perfil do zero e apaga o que você editou à mão. Os pedidos que você fez à IA são aplicados de novo.",
confirmLabel: "Pesquisar de novo", tone: "danger" }))) return;
void run("research", () => clipperCall<GamesReply>(`${path}/research`, "POST"), "Pesquisa concluída.", true);
}
/** Manda um pedido do chat; aplica o perfil novo e devolve a resposta da IA + o que mudou na seção. */
async function ask(section: SectionKey, instruction: string, search: boolean, history: ChatTurn[]): Promise<ChatTurn> {
setChatBusy(true);
const before = game?.profile;
const r = await clipperCall<RefineReply>(`${path}/refine`, "POST", {
instruction, search, section, history: history.map(({ role, text }) => ({ role, text })),
});
setChatBusy(false);
if (!r.ok) {
if (search) {
const list = await clipperCall<GamesReply>("games");
if (list.ok) onGamesChanged(list.data.games);
}
return { role: "ai", text: r.error, error: true };
}
onGamesChanged(r.data.games);
const after = r.data.games.find((g) => g.id === id)?.profile;
let added = 0, removed = 0;
const nextFresh = new Set<string>();
for (const key of Object.keys(SECTIONS) as ListKey[]) {
const d = diffList(before?.[key], after?.[key]);
added += d.added.length;
removed += d.removed.length;
for (const item of d.added) nextFresh.add(`${key}:${item.toLowerCase()}`);
}
setFresh(nextFresh);
return { role: "ai", text: r.data.reply || "Pronto, atualizei o perfil.", added, removed };
}
return (
<article className="overflow-hidden rounded-panel border border-line bg-surface/60">
{/* Cabeçalho: monograma do jogo, nome, gênero, de onde veio e ações. */}
<header className="relative flex flex-wrap items-start gap-4 border-b border-line p-4 sm:p-5"
style={{ backgroundImage: `linear-gradient(120deg, hsl(${hue} 70% 50% / 0.10), transparent 55%)` }}>
<div aria-hidden="true" className="grid size-12 shrink-0 place-items-center rounded-xl text-lg font-bold text-white shadow-sm"
style={{ background: `linear-gradient(135deg, hsl(${hue} 65% 52%), hsl(${(hue + 40) % 360} 70% 40%))` }}>
{monogram(title)}
</div>
<div className="grid min-w-0 flex-1 gap-1.5">
<div className="flex flex-wrap items-center gap-2">
<h3 className="text-lg font-semibold tracking-tight text-fg">{title}</h3>
{!game ? <Badge>não pesquisado</Badge>
: game.status === "pending" ? <Badge tone="info" pulse>pesquisando</Badge>
: game.status === "error" ? <Badge tone="danger">erro na pesquisa</Badge> : null}
</div>
{game?.profile?.genre && <p className="text-xs font-medium text-fg-muted">{game.profile.genre}</p>}
<p className="flex flex-wrap gap-x-2 text-xs text-fg-subtle">
{game?.researchedAt && <span>pesquisado {formatRelative(game.researchedAt)}</span>}
{game?.editedAt && <span>· editado {formatRelative(game.editedAt)}</span>}
{game?.model && <span className="font-mono">· {game.model}</span>}
</p>
</div>
<div className="flex flex-wrap gap-1.5">
{game?.profile && !editing && (
<Button variant="secondary" size="sm" disabled={busy} onClick={() => setChatOpen(chatOpen === "" ? null : "")}>
<SparkIcon size={14} />Conversar com a IA
</Button>
)}
{game && !editing && (
<Button variant="ghost" size="sm" disabled={busy} onClick={() => setEditing(true)}><PenIcon size={14} />Editar</Button>
)}
<Button variant="ghost" size="sm" disabled={busy || editing} onClick={research}>
{pending === "research" ? <><Spinner className="size-3.5" />Pesquisando…</> : <><RefreshIcon size={15} />{game?.profile ? "Pesquisar de novo" : "Pesquisar"}</>}
</Button>
</div>
</header>
<div className="grid gap-4 p-4 sm:p-5">
{game?.status === "error" && game.error && <Feedback ok={false}>{game.error}</Feedback>}
{chatOpen === "" && game?.profile && !editing && (
<AiChat key="general" sectionTitle="o perfil inteiro" suggestions={["Reação do streamer conta como corte", "Acrescente as gírias que o chat usa", "Deixe o resumo mais curto"]}
disabled={busy && !chatBusy} onAsk={(text, search, history) => ask("", text, search, history)} onClose={() => setChatOpen(null)} />
)}
{editing && game ? (
<ProfileEditor profile={game.profile} fallbackName={game.name} saving={pending === "save"} onCancel={() => setEditing(false)}
onSave={async (profile) => {
const ok = await run("save", () => clipperCall<GamesReply>(path, "PUT", profile), "Perfil salvo. A IA já usa a versão nova.");
if (ok) setEditing(false);
}} />
) : game?.profile ? (
<ProfileView profile={game.profile} fresh={fresh} chatOpen={chatOpen} disabled={busy && !chatBusy}
onToggleChat={(key) => setChatOpen(chatOpen === key ? null : key)}
renderChat={(key) => (
<AiChat key={key} sectionTitle={SECTIONS[key].title} suggestions={SECTIONS[key].suggestions} compact
disabled={busy && !chatBusy} onAsk={(text, search, history) => ask(key, text, search, history)} onClose={() => setChatOpen(null)} />
)} />
) : (
<EmptyState compact icon={<BookIcon size={18} />} title="Ainda sem perfil">
A IA pesquisa o jogo na web (mecânicas, gírias, o que costuma render corte) e usa isso para entender a live.
</EmptyState>
)}
{game && !editing && <SavedNotes notes={game.notes ?? []} disabled={busy}
onForget={(i) => void run("note", () => clipperCall<GamesReply>(`${path}/notes/${i}`, "DELETE"), "Pedido esquecido.")} />}
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
</article>
);
}
/* ---------- Chat com a IA ---------- */
type ChatTurn = { role: "user" | "ai"; text: string; error?: boolean; added?: number; removed?: number };
/**
* Conversa com a IA sobre uma seção do perfil: você fala ("adicione que reação do streamer conta"), ela edita a
* lista e responde o que fez. Enter envia; Shift+Enter quebra linha. A conversa vale enquanto o chat está aberto;
* cada pedido fica guardado no serviço e volta nas próximas pesquisas.
*/
function AiChat({ sectionTitle, suggestions, compact = false, disabled, onAsk, onClose }: {
sectionTitle: string; suggestions: string[]; compact?: boolean; disabled: boolean;
onAsk: (text: string, search: boolean, history: ChatTurn[]) => Promise<ChatTurn>; onClose: () => void;
}) {
const [turns, setTurns] = useState<ChatTurn[]>([]);
const [text, setText] = useState("");
const [search, setSearch] = useState(false);
const [thinking, setThinking] = useState(false);
const inputId = useId();
const logRef = useRef<HTMLOListElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => { inputRef.current?.focus(); }, []);
useEffect(() => { logRef.current?.scrollTo({ top: logRef.current.scrollHeight, behavior: "smooth" }); }, [turns, thinking]);
async function send(raw: string) {
const clean = raw.trim();
if (clean.length < 3 || thinking || disabled) return;
const history = turns.filter((t) => !t.error);
setTurns((t) => [...t, { role: "user", text: clean }]);
setText("");
setThinking(true);
const reply = await onAsk(clean, search, history);
setThinking(false);
setTurns((t) => [...t, reply]);
inputRef.current?.focus();
}
return (
<section aria-label={`Conversa com a IA sobre ${sectionTitle}`}
className={cx("grid gap-3 rounded-control border border-accent/30 bg-accent-soft/40", compact ? "p-3" : "p-4")}>
<div className="flex items-center gap-2">
<span className="grid size-6 place-items-center rounded-full bg-accent text-accent-fg"><SparkIcon size={13} /></span>
<p className="min-w-0 flex-1 text-[0.8125rem] font-medium text-fg">IA · editando <span className="text-accent">{sectionTitle}</span></p>
<button type="button" onClick={onClose} aria-label="Fechar conversa"
className="rounded-md p-1 text-fg-subtle hover:bg-overlay hover:text-fg"><XIcon size={14} /></button>
</div>
{turns.length === 0 && !thinking ? (
<div className="grid gap-2">
<p className="text-xs leading-relaxed text-fg-muted">
Diga o que acrescentar, tirar ou corrigir — a IA edita a lista e explica o que fez.
</p>
{suggestions.length > 0 && (
<ul className="flex flex-wrap gap-1.5">
{suggestions.map((s) => (
<li key={s}>
<button type="button" disabled={disabled} onClick={() => void send(s)}
className="rounded-full border border-line bg-raised/70 px-2.5 py-1 text-xs text-fg-muted transition-colors hover:border-accent/50 hover:text-fg disabled:opacity-50">
{s}
</button>
</li>
))}
</ul>
)}
</div>
) : (
<ol ref={logRef} aria-live="polite" className="grid max-h-72 gap-2 overflow-y-auto pr-1">
{turns.map((t, i) => (
<li key={i} className={cx("flex", t.role === "user" ? "justify-end" : "justify-start")}>
<div className={cx("max-w-[85%] rounded-2xl px-3 py-2 text-[0.8125rem] leading-relaxed",
t.role === "user" ? "rounded-br-md bg-accent text-accent-fg"
: t.error ? "rounded-bl-md border border-danger/30 bg-danger-soft text-danger"
: "rounded-bl-md border border-line bg-raised text-fg")}>
{t.text}
{t.role === "ai" && !t.error && (t.added || t.removed) ? (
<span className="mt-1.5 flex gap-2 text-xs font-medium">
{t.added ? <span className="text-success">+{t.added} {t.added === 1 ? "item novo" : "itens novos"}</span> : null}
{t.removed ? <span className="text-danger">−{t.removed} {t.removed === 1 ? "removido" : "removidos"}</span> : null}
</span>
) : null}
</div>
</li>
))}
{thinking && (
<li className="flex justify-start">
<div role="status" className="flex items-center gap-1.5 rounded-2xl rounded-bl-md border border-line bg-raised px-3 py-2.5 text-xs text-fg-muted">
<span className="sr-only">A IA está editando…</span>
{[0, 150, 300].map((d) => <span key={d} aria-hidden="true" className="size-1.5 animate-bounce rounded-full bg-fg-subtle" style={{ animationDelay: `${d}ms` }} />)}
{search && <span className="ml-1">pesquisando na web…</span>}
</div>
</li>
)}
</ol>
)}
<form className="grid gap-2" onSubmit={(e) => { e.preventDefault(); void send(text); }}>
<label htmlFor={inputId} className="sr-only">Pedido para a IA</label>
<div className="flex items-end gap-2 rounded-control border border-line-strong bg-canvas/70 p-1.5 focus-within:border-accent/60">
<textarea ref={inputRef} id={inputId} rows={1} maxLength={1500} value={text} disabled={thinking}
placeholder="Ex.: adicione que reação do streamer conta para corte"
className="max-h-32 min-h-9 flex-1 resize-none bg-transparent px-2 py-1.5 text-sm text-fg placeholder:text-fg-subtle focus:outline-none"
onChange={(e) => { setText(e.target.value); e.target.style.height = "auto"; e.target.style.height = `${e.target.scrollHeight}px`; }}
onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); void send(text); } }} />
<Button type="submit" size="sm" aria-label="Enviar" disabled={text.trim().length < 3 || thinking || disabled}>
{thinking ? <Spinner className="size-3.5" /> : <SendIcon size={14} />}
</Button>
</div>
<Switch label="Confirmar na web" checked={search} onChange={setSearch} disabled={thinking}
hint={search ? "Mais lento: a IA pesquisa antes (até alguns minutos)." : "Rápido: usa só o que você escreveu."} />
</form>
</section>
);
}
/** Pedidos que você fez à IA: voltam em toda pesquisa nova. Recolhido por padrão. */
function SavedNotes({ notes, disabled, onForget }: { notes: { text: string; at: string; section?: string }[]; disabled: boolean; onForget: (index: number) => void }) {
const [open, setOpen] = useState(false);
if (notes.length === 0) return null;
return (
<div className="grid gap-2 border-t border-line pt-3">
<button type="button" aria-expanded={open} onClick={() => setOpen((o) => !o)}
className="flex w-fit items-center gap-1.5 text-xs font-medium text-fg-muted hover:text-fg">
<BookIcon size={13} />Memória da IA · {notes.length} {notes.length === 1 ? "pedido seu" : "pedidos seus"}
<ChevronDownIcon size={13} className={cx("transition-transform", open && "rotate-180")} />
</button>
{open && (
<>
<p className="text-xs text-fg-subtle">Voltam em toda pesquisa nova, para “Pesquisar de novo” não apagar o que você acrescentou.</p>
<ul className="grid gap-1">
{notes.map((n, i) => (
<li key={`${n.at}-${i}`} className="flex items-start gap-2 rounded-lg border border-line bg-raised/40 px-2.5 py-1.5 text-xs text-fg-muted">
{n.section && n.section in SECTIONS && (
<span className={cx("shrink-0 font-medium", TONE_TEXT[SECTIONS[n.section as ListKey].tone])}>{SECTIONS[n.section as ListKey].title}</span>
)}
<span className="min-w-0 flex-1 leading-relaxed break-words">{n.text}</span>
<span className="shrink-0 text-fg-subtle">{formatRelative(n.at)}</span>
<button type="button" aria-label={`Esquecer o pedido “${n.text.slice(0, 40)}”`} disabled={disabled}
title="Esquecer (não volta nas próximas pesquisas; o perfil atual fica como está)"
className="shrink-0 rounded p-0.5 text-fg-subtle hover:bg-overlay hover:text-danger disabled:opacity-50"
onClick={() => onForget(i)}>
<XIcon size={13} />
</button>
</li>
))}
</ul>
</>
)}
</div>
);
}
/* ---------- Edição à mão ---------- */
const EDIT_LISTS = (Object.keys(SECTIONS) as ListKey[]).map((key) => ({ key, label: SECTIONS[key].title, hint: SECTIONS[key].hint }));
type ProfileDraft = { name: string; genre: string; summary: string; lists: Record<string, string> };
function toDraft(profile: GameProfile | null, fallbackName: string): ProfileDraft {
return {
name: profile?.name || fallbackName,
genre: profile?.genre ?? "",
summary: profile?.summary ?? "",
lists: Object.fromEntries(EDIT_LISTS.map(({ key }) => [key, (profile?.[key] ?? []).join("\n")])),
};
}
function fromDraft(draft: ProfileDraft): GameProfile {
const lines = (text: string) => text.split(/\r?\n/).map((l) => l.replace(/^\s*[-•*]\s*/, "").trim()).filter(Boolean);
const lists = Object.fromEntries(EDIT_LISTS.map(({ key }) => [key, lines(draft.lists[key] ?? "")]));
return { name: draft.name.trim(), genre: draft.genre.trim(), summary: draft.summary.trim(), ...lists } as GameProfile;
}
function ProfileEditor({ profile, fallbackName, saving, onSave, onCancel }: {
profile: GameProfile | null; fallbackName: string; saving: boolean; onSave: (profile: GameProfile) => void; onCancel: () => void;
}) {
const [draft, setDraft] = useState(() => toDraft(profile, fallbackName));
const setList = (key: string, value: string) => setDraft((d) => ({ ...d, lists: { ...d.lists, [key]: value } }));
return (
<form className="grid gap-4" onSubmit={(e) => { e.preventDefault(); onSave(fromDraft(draft)); }}>
<div className="grid gap-4 md:grid-cols-2">
<Field label="Nome do jogo">
<Input value={draft.name} maxLength={120} onChange={(e) => setDraft({ ...draft, name: e.target.value })} />
</Field>
<Field label="Gênero">
<Input value={draft.genre} maxLength={120} onChange={(e) => setDraft({ ...draft, genre: e.target.value })} />
</Field>
</div>
<Field label="Resumo" hint="O que é o jogo e como se joga (2–3 frases).">
<Textarea rows={3} maxLength={1500} value={draft.summary} onChange={(e) => setDraft({ ...draft, summary: e.target.value })} />
</Field>
<div className="grid gap-4 md:grid-cols-2">
{EDIT_LISTS.map(({ key, label, hint }) => (
<Field key={key} label={<span className={TONE_TEXT[SECTIONS[key].tone]}>{label}</span>} hint={hint}>
<Textarea rows={Math.min(10, Math.max(3, (draft.lists[key] ?? "").split("\n").length + 1))}
value={draft.lists[key] ?? ""} onChange={(e) => setList(key, e.target.value)}
className={key === "sources" ? "font-mono text-xs" : undefined} />
</Field>
))}
</div>
<div className="sticky bottom-0 flex justify-end gap-2 border-t border-line bg-surface/90 py-3 backdrop-blur">
<Button type="button" variant="ghost" size="sm" disabled={saving} onClick={onCancel}>Cancelar</Button>
<Button type="submit" size="sm" disabled={saving}>
{saving ? <Spinner className="size-3.5" /> : <CheckIcon size={15} />}Salvar perfil
</Button>
</div>
</form>
);
}
/* ---------- Leitura do perfil ---------- */
function ProfileView({ profile: p, fresh, chatOpen, disabled, onToggleChat, renderChat }: {
profile: GameProfile; fresh: Set<string>; chatOpen: SectionKey | null; disabled: boolean;
onToggleChat: (key: ListKey) => void; renderChat: (key: ListKey) => ReactNode;
}) {
const block = (key: ListKey, wide = false) => (
<SectionBlock key={key} sectionKey={key} items={p[key] ?? []} fresh={fresh} wide={wide}
chatOpen={chatOpen === key} disabled={disabled} onToggleChat={() => onToggleChat(key)} chat={chatOpen === key ? renderChat(key) : null} />
);
return (
<div className="grid gap-4 text-[0.8125rem]">
{p.summary && <p className="max-w-[95ch] text-sm leading-relaxed text-fg-muted">{p.summary}</p>}
<div className="grid gap-3 lg:grid-cols-2">
{block("clip_worthy")}
{block("avoid")}
{block("mechanics")}
{block("news")}
{block("jargon", true)}
{block("hashtags", true)}
</div>
{p.sources?.length > 0 && <Sources sources={p.sources} />}
</div>
);
}
function SectionBlock({ sectionKey, items, fresh, wide, chatOpen, disabled, onToggleChat, chat }: {
sectionKey: ListKey; items: string[]; fresh: Set<string>; wide: boolean; chatOpen: boolean; disabled: boolean;
onToggleChat: () => void; chat: ReactNode;
}) {
const { title, tone } = SECTIONS[sectionKey];
const isFresh = (item: string) => fresh.has(`${sectionKey}:${item.toLowerCase()}`);
const chips = sectionKey === "jargon" || sectionKey === "hashtags";
return (
<section className={cx("relative grid content-start gap-3 overflow-hidden rounded-control border bg-sunken/40 p-4 pl-5 transition-colors",
chatOpen ? "border-accent/40" : "border-line", wide && "lg:col-span-2")}>
<span aria-hidden="true" className={cx("absolute inset-y-0 left-0 w-1", TONE_BAR[tone])} />
<div className="flex items-center gap-2">
<h4 className={cx("text-eyebrow font-semibold uppercase", TONE_TEXT[tone])}>{title}</h4>
<span className="rounded-full bg-overlay px-1.5 text-[0.6875rem] font-medium tabular-nums text-fg-subtle">{items.length}</span>
<button type="button" disabled={disabled} aria-expanded={chatOpen} onClick={onToggleChat}
className={cx("ml-auto flex items-center gap-1 rounded-full px-2 py-1 text-xs font-medium transition-colors disabled:opacity-50",
chatOpen ? "bg-accent text-accent-fg" : "text-fg-subtle hover:bg-accent-soft hover:text-accent")}>
<SparkIcon size={12} />{chatOpen ? "Fechar IA" : "Pedir à IA"}
</button>
</div>
{items.length === 0 ? (
<p className="text-xs text-fg-subtle">Vazio. Peça à IA para preencher.</p>
) : chips ? (
<ul className="flex flex-wrap gap-1.5">
{items.map((j, i) => (
<li key={i} className={cx("rounded-lg border px-2 py-1 text-xs transition-colors",
isFresh(j) ? "border-success/50 bg-success-soft text-success" : "border-line bg-raised/60 text-fg-muted")}>{j}</li>
))}
</ul>
) : (
<ul className="grid gap-1.5 text-fg-muted">
{items.map((it, i) => (
<li key={i} className={cx("flex gap-2 rounded-md leading-relaxed transition-colors",
isFresh(it) && "-mx-2 bg-success-soft px-2 py-1 text-fg")}>
<span aria-hidden="true" className={cx("mt-2 size-1.5 shrink-0 rounded-full", TONE_BAR[tone], !isFresh(it) && "opacity-60")} />
<span className="min-w-0 flex-1">{it}</span>
{isFresh(it) && <span className="mt-0.5 h-fit shrink-0 rounded-full bg-success px-1.5 text-[0.625rem] font-semibold text-canvas uppercase">novo</span>}
</li>
))}
</ul>
)}
{chat}
</section>
);
}
function Sources({ sources }: { sources: string[] }) {
const [open, setOpen] = useState(false);
return (
<div className="grid gap-1.5">
<button type="button" aria-expanded={open} onClick={() => setOpen((o) => !o)}
className="flex w-fit items-center gap-1.5 text-xs font-medium text-fg-subtle hover:text-fg">
<LinkIcon size={13} />{sources.length} {sources.length === 1 ? "fonte" : "fontes"}
<ChevronDownIcon size={13} className={cx("transition-transform", open && "rotate-180")} />
</button>
{open && (
<ul className="grid gap-1">
{sources.map((s, i) => (
<li key={i} className="truncate text-xs">
{/^https?:\/\//.test(s)
? <a href={s} target="_blank" rel="noreferrer noopener" className="text-fg-muted hover:text-fg hover:underline">{s.replace(/^https?:\/\/(www\.)?/, "")}</a>
: <span className="text-fg-subtle">{s}</span>}
</li>
))}
</ul>
)}
</div>
);
}
/* ---------- Aba Jogos ---------- */
export function GamesPanel({ games, available, onGamesChanged }: { games: Game[]; available: boolean; onGamesChanged: (games: Game[]) => void }) {
if (!available) {
return (
<EmptyState compact icon={<BookIcon size={18} />} title="Perfis de jogo indisponíveis">
O Clipador no ar ainda é a versão antiga. Reinicie o serviço para a IA pesquisar os jogos das lives.
</EmptyState>
);
}
if (games.length === 0) {
return (
<EmptyState compact icon={<BookIcon size={18} />} title="Nenhum jogo pesquisado ainda">
Quando uma sessão identifica o jogo (pela categoria ou pela tela), a IA pesquisa o que ele tem de engraçado, as gírias e as novidades.
</EmptyState>
);
}
return (
<ul className="grid gap-5">
{games.map((g) => <li key={g.id}><GameCard game={g} name={g.name} onGamesChanged={onGamesChanged} /></li>)}
</ul>
);
}
/* ---------- Emotes do canal ---------- */
const EMOTE_SOURCE: Record<string, string> = { twitch: "Twitch", "7tv": "7TV", bttv: "BTTV", ffz: "FFZ", kick: "Kick", emoji: "emoji" };