import React, { useState, useEffect, useCallback, useRef } from "react";
import { Film, FileText, Sparkles, Trash2, Plus, Copy, Check, Loader2, Database, ChevronRight, UploadCloud, FileWarning, Lock, LogOut } from "lucide-react";
const API = import.meta.env.VITE_API_BASE || "/api";
const TOKEN_KEY = "adapter_token";
function getToken() { return localStorage.getItem(TOKEN_KEY); }
function setStoredToken(t) { if (t) localStorage.setItem(TOKEN_KEY, t); else localStorage.removeItem(TOKEN_KEY); }
async function api(path, opts = {}) {
const headers = { ...(opts.headers || {}) };
if (opts.body && !(opts.body instanceof FormData) && !headers["Content-Type"]) {
headers["Content-Type"] = "application/json";
}
const t = getToken();
if (t) headers["Authorization"] = "Bearer " + t;
const res = await fetch(API + path, { ...opts, headers });
if (res.status === 401) {
setStoredToken(null);
window.dispatchEvent(new Event("adapter-unauth"));
}
if (!res.ok) {
let msg = "Error " + res.status;
try { msg = (await res.json()).error || msg; } catch {}
throw new Error(msg);
}
return res.json();
}
function Field({ label, value, onChange, textarea, rows = 3, placeholder }) {
const Comp = textarea ? "textarea" : "input";
return (
);
}
function DropBox({ onText, hint }) {
const [drag, setDrag] = useState(false);
const [status, setStatus] = useState(null);
const inputRef = useRef();
const handle = async (file) => {
if (!file) return;
setStatus({ type: "load", msg: `Subiendo ${file.name}…` });
try {
const fd = new FormData();
fd.append("file", file);
const { text, filename } = await api("/extract", { method: "POST", body: fd });
onText(text, filename);
setStatus({ type: "ok", msg: `${filename} cargado (${text.length} caracteres).` });
} catch (e) {
setStatus({ type: "err", msg: e.message });
}
};
return (
Soltar archivo (MD, TXT, DOCX, PDF)
{ e.preventDefault(); setDrag(true); }}
onDragLeave={() => setDrag(false)}
onDrop={(e) => { e.preventDefault(); setDrag(false); handle(e.dataTransfer.files[0]); }}
onClick={() => inputRef.current?.click()}
style={{
border: `1.5px dashed ${drag ? "var(--accent)" : "rgba(255,255,255,.25)"}`,
background: drag ? "rgba(255,255,255,.10)" : "rgba(255,255,255,.04)",
borderRadius: 14, padding: "20px 16px", textAlign: "center", cursor: "pointer",
transition: "all .15s", color: "var(--muted)",
}}>
Arrastra aquí o haz clic para subir
{hint}
handle(e.target.files[0])} />
{status && (
{status.type === "err" ? : status.type === "load" ? : }
{status.msg}
)}
);
}
function Login({ onLogged }) {
const [pwd, setPwd] = useState("");
const [busy, setBusy] = useState(false);
const [err, setErr] = useState("");
const inputRef = useRef(null);
useEffect(() => { inputRef.current?.focus(); }, []);
const submit = async (e) => {
e?.preventDefault();
if (!pwd) return;
setBusy(true); setErr("");
try {
const { token } = await api("/login", { method: "POST", body: JSON.stringify({ password: pwd }) });
if (!token) throw new Error("Respuesta del servidor sin token.");
setStoredToken(token);
onLogged();
} catch (e2) {
setErr(e2.message);
setPwd("");
inputRef.current?.focus();
} finally { setBusy(false); }
};
return (
);
}
export default function App() {
const [authed, setAuthed] = useState(() => !!getToken());
const [authChecking, setAuthChecking] = useState(() => !!getToken());
useEffect(() => {
const onUnauth = () => { setAuthed(false); setAuthChecking(false); };
window.addEventListener("adapter-unauth", onUnauth);
return () => window.removeEventListener("adapter-unauth", onUnauth);
}, []);
useEffect(() => {
if (!getToken()) { setAuthChecking(false); return; }
api("/session")
.then(() => { setAuthed(true); setAuthChecking(false); })
.catch(() => { setAuthed(false); setAuthChecking(false); });
}, []);
const logout = () => { setStoredToken(null); setAuthed(false); };
if (authChecking) {
return (
);
}
if (!authed) return setAuthed(true)} />;
return ;
}
function MainApp({ onLogout }) {
const [tab, setTab] = useState("generar");
const [reels, setReels] = useState([]);
const [exps, setExps] = useState([]);
const [loaded, setLoaded] = useState(false);
const [loadErr, setLoadErr] = useState("");
const [reelForm, setReelForm] = useState(blankReel());
const [expForm, setExpForm] = useState(blankExp());
const [selReel, setSelReel] = useState(null);
const [selExp, setSelExp] = useState(null);
const [output, setOutput] = useState("");
const [busy, setBusy] = useState(false);
const [err, setErr] = useState("");
const [copied, setCopied] = useState(false);
function blankReel() { return { titulo: "", hook: "", estructura: "", tono: "", formato: "", notas: "" }; }
function blankExp() { return { titulo: "", contenido: "" }; }
const refresh = useCallback(async () => {
try {
const [r, e] = await Promise.all([api("/reels"), api("/expedientes")]);
setReels(r); setExps(e); setLoaded(true); setLoadErr("");
} catch (e) { setLoadErr("No se pudo conectar con el backend: " + e.message); setLoaded(true); }
}, []);
useEffect(() => { refresh(); }, [refresh]);
const addReel = async () => {
if (!reelForm.titulo.trim()) return;
try { await api("/reels", { method: "POST", body: JSON.stringify(reelForm) }); setReelForm(blankReel()); refresh(); }
catch (e) { alert(e.message); }
};
const addExp = async () => {
if (!expForm.titulo.trim() || !expForm.contenido.trim()) return;
try { await api("/expedientes", { method: "POST", body: JSON.stringify(expForm) }); setExpForm(blankExp()); refresh(); }
catch (e) { alert(e.message); }
};
const delReel = async (id) => { await api("/reels/" + id, { method: "DELETE" }); if (selReel === id) setSelReel(null); refresh(); };
const delExp = async (id) => { await api("/expedientes/" + id, { method: "DELETE" }); if (selExp === id) setSelExp(null); refresh(); };
const generar = async () => {
setErr(""); setOutput(""); setCopied(false);
if (!selReel || !selExp) { setErr("Selecciona un análisis técnico y un expediente."); return; }
setBusy(true);
try {
const { brief } = await api("/generar", { method: "POST", body: JSON.stringify({ reelId: selReel, expedienteId: selExp }) });
setOutput(brief || "(Sin respuesta del modelo)");
} catch (e) { setErr(e.message); }
finally { setBusy(false); }
};
const copy = async () => {
try { await navigator.clipboard.writeText(output); setCopied(true); setTimeout(() => setCopied(false), 1500); } catch {}
};
const TABS = [
{ id: "generar", label: "Generar brief", icon: Sparkles },
{ id: "reels", label: "Análisis técnicos", icon: Film, count: reels.length },
{ id: "exp", label: "Expedientes", icon: FileText, count: exps.length },
];
return (
{loadErr &&
{loadErr}
}
{tab === "generar" && (
{err &&
{err}
}
{output && (
Brief de producción
{output}
)}
)}
{tab === "reels" && (
Nuevo análisis técnico
setReelForm((f) => ({ ...f, titulo: f.titulo || fname.replace(/\.[^.]+$/, ""), notas: (f.notas ? f.notas + "\n\n" : "") + text }))} />
setReelForm({ ...reelForm, titulo: v })} placeholder="Ej. Reel viral @creador" />
setReelForm({ ...reelForm, hook: v })} textarea rows={2} />
setReelForm({ ...reelForm, estructura: v })} textarea rows={2} />
setReelForm({ ...reelForm, tono: v })} textarea rows={2} />
setReelForm({ ...reelForm, formato: v })} textarea rows={2} />
setReelForm({ ...reelForm, notas: v })} textarea rows={3} />
(<>
{r.titulo}
{r.hook && Hook: {r.hook}
}
{r.tono && Tono: {r.tono}
}
{r.formato && Formato: {r.formato}
}
>)} />
)}
{tab === "exp" && (
Nuevo expediente comercial
setExpForm((f) => ({ ...f, titulo: f.titulo || fname.replace(/\.[^.]+$/, ""), contenido: (f.contenido ? f.contenido + "\n\n" : "") + text }))} />
setExpForm({ ...expForm, titulo: v })} placeholder="Ej. Solución CRM para pymes" />
setExpForm({ ...expForm, contenido: v })} textarea rows={9} placeholder="Pega o sube propuesta de valor, beneficios, prueba, precio, CTA…" />
(<>
{e.titulo}
{e.contenido}
>)} />
)}
);
}
function Selector({ title, icon: Icon, items, selId, onSel, empty }) {
return (
{title}
{items.length === 0 ?
{empty}
: (
{items.map((it) => {
const active = selId === it.id;
return (
);
})}
)}
);
}
function RecordList({ items, onDel, render, empty }) {
if (items.length === 0)
return {empty}
;
return (
{items.map((it) => (
{render(it)}
))}
);
}
const rootStyle = {
"--ink": "#f3f0ff", "--muted": "#b9b4d6", "--accent": "#9cff8f", "--accent2": "#ff7eb6",
minHeight: "100vh", color: "var(--ink)", position: "relative", overflow: "hidden",
fontFamily: "'DM Sans', ui-sans-serif, system-ui, sans-serif",
background: "linear-gradient(135deg, #1a1040 0%, #2d1b69 45%, #0f2057 100%)",
};
const bgBlobs = { background: "radial-gradient(40% 40% at 15% 20%, rgba(156,255,143,.22), transparent 70%), radial-gradient(45% 45% at 85% 15%, rgba(255,126,182,.20), transparent 70%), radial-gradient(50% 50% at 70% 85%, rgba(120,140,255,.22), transparent 70%)", filter: "blur(8px)" };
const glassCard = { background: "rgba(255,255,255,.07)", backdropFilter: "blur(18px)", WebkitBackdropFilter: "blur(18px)", border: "1px solid rgba(255,255,255,.14)", borderRadius: 18, padding: 18, boxShadow: "0 8px 32px rgba(0,0,0,.25), inset 0 1px 0 rgba(255,255,255,.12)" };
const headerStyle = { padding: "28px 24px 18px", display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 12, borderBottom: "1px solid rgba(255,255,255,.10)" };
const h1Style = { margin: 0, fontFamily: "'Syne', sans-serif", fontSize: 27, fontWeight: 800, letterSpacing: "-0.02em", lineHeight: 1 };
const pill = { display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--muted)", border: "1px solid rgba(255,255,255,.16)", background: "rgba(255,255,255,.06)", backdropFilter: "blur(10px)", padding: "6px 12px", borderRadius: 20 };
const lblStyle = { display: "block", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 6, fontWeight: 600 };
const inputStyle = { width: "100%", background: "rgba(255,255,255,.06)", border: "1px solid rgba(255,255,255,.16)", borderRadius: 10, padding: "10px 12px", color: "var(--ink)", fontSize: 14, fontFamily: "inherit", resize: "vertical", outline: "none", boxSizing: "border-box" };
const twoCol = { display: "grid", gridTemplateColumns: "minmax(300px,400px) 1fr", gap: 18 };
const cardTitle = { margin: "0 0 14px", fontFamily: "'Syne',sans-serif", fontSize: 18 };
const metaP = { margin: "6px 0 0", fontSize: 13, color: "var(--muted)", lineHeight: 1.5 };
const metaB = { color: "var(--ink)" };
const tabStyle = (a) => ({ display: "flex", alignItems: "center", gap: 7, padding: "10px 16px", background: a ? "var(--accent)" : "rgba(255,255,255,.06)", color: a ? "#13123a" : "var(--ink)", backdropFilter: "blur(10px)", border: `1px solid ${a ? "var(--accent)" : "rgba(255,255,255,.14)"}`, borderRadius: 11, fontWeight: 600, fontSize: 13.5, transition: "all .15s" });
const countBadge = (a) => ({ background: a ? "rgba(0,0,0,.16)" : "rgba(255,255,255,.10)", borderRadius: 6, padding: "1px 7px", fontSize: 11.5 });
const genBtn = (b) => ({ width: "100%", padding: "14px", borderRadius: 12, border: "none", background: b ? "rgba(255,255,255,.15)" : "var(--accent)", color: b ? "var(--muted)" : "#13123a", fontWeight: 700, fontSize: 15, display: "flex", alignItems: "center", justifyContent: "center", gap: 8 });
const copyBtn = { display: "flex", alignItems: "center", gap: 6, padding: "7px 12px", background: "rgba(255,255,255,.08)", border: "1px solid rgba(255,255,255,.16)", borderRadius: 9, color: "var(--ink)", fontSize: 13 };
const addBtn = { width: "100%", marginTop: 6, padding: "12px", borderRadius: 11, border: "none", background: "var(--accent)", color: "#13123a", fontWeight: 700, fontSize: 14, display: "flex", alignItems: "center", justifyContent: "center", gap: 7 };
const delBtn = { flexShrink: 0, width: 34, height: 34, borderRadius: 9, border: "1px solid rgba(255,255,255,.16)", background: "rgba(255,255,255,.06)", color: "var(--accent2)", display: "flex", alignItems: "center", justifyContent: "center" };
const logoutBtn = { display: "flex", alignItems: "center", gap: 6, padding: "6px 12px", fontSize: 12, color: "var(--muted)", border: "1px solid rgba(255,255,255,.16)", background: "rgba(255,255,255,.06)", backdropFilter: "blur(10px)", borderRadius: 20 };
const selItem = (a) => ({ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, textAlign: "left", padding: "10px 12px", borderRadius: 10, background: a ? "rgba(156,255,143,.12)" : "rgba(255,255,255,.05)", border: `1px solid ${a ? "var(--accent)" : "rgba(255,255,255,.14)"}`, color: "var(--ink)", fontSize: 13.5, fontWeight: 500 });
const GLOBAL_CSS = `@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Syne:wght@700;800&display=swap');
*::-webkit-scrollbar{width:8px;height:8px}*::-webkit-scrollbar-thumb{background:rgba(255,255,255,.18);border-radius:8px}
button{cursor:pointer;font-family:inherit}@keyframes spin{to{transform:rotate(360deg)}}
::placeholder{color:rgba(185,180,214,.55)}body{margin:0}`;