/* global React, Icon, formatCOP, formatCompactCOP, LegalDot, LEGAL, EstadoPill, VENTURES, PROJECT_DETAIL, BrandLogo, MarketingCenter, VentasCenter, JuridicoCenter, ventureName, useHubAuth, LoginScreen, UsersPanel */
const { useState: useStateHub } = React;

const HUB_VIEWS = [
  { id: "general",   label: "Dashboard general", icon: "LayoutDashboard" },
  { id: "marketing", label: "Marketing",         icon: "Megaphone" },
  { id: "ventas",    label: "Ventas / CRM",      icon: "Users" },
  { id: "juridico",  label: "Jurídico",          icon: "Scale" },
];

/* --------------------------------- Sidebar -------------------------------- */
function HubSidebar({ view, setView, views, activeVentureId, scope, onVenture, onTodos, user, onLogout, open, onClose }) {
  return (
    <React.Fragment>
      {open && <div className="fixed inset-0 z-30 bg-taupe-900/50 backdrop-blur-sm lg:hidden" onClick={onClose} />}
      <aside className={`fixed inset-y-0 left-0 z-40 flex h-full w-64 shrink-0 flex-col border-r border-taupe-800/60 bg-taupe-900 text-taupe-100 transition-transform duration-200 lg:static lg:h-auto lg:translate-x-0 ${open ? "translate-x-0" : "-translate-x-full"}`}>
      <div className="flex items-start justify-between px-5 py-5">
        <div>
          <BrandLogo dark height={40} />
          <div className="mt-2.5 font-mono text-[10px] uppercase tracking-[0.2em] text-taupe-400">Hub · panel interno</div>
        </div>
        <button onClick={onClose} className="grid h-8 w-8 place-items-center rounded-lg text-taupe-300 transition hover:bg-taupe-800 hover:text-white lg:hidden" title="Cerrar menú">
          <Icon name="X" size={16} />
        </button>
      </div>

      <div className="px-5 pb-2 pt-2 font-mono text-[10px] uppercase tracking-[0.18em] text-taupe-500">Vistas</div>
      <div className="space-y-0.5 px-3">
        {views.map((vw) => {
          const active = view === vw.id;
          return (
            <button key={vw.id} onClick={() => setView(vw.id)}
              className={`flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left transition ${active ? "bg-amber-400 text-taupe-900" : "text-taupe-200 hover:bg-taupe-800/60"}`}>
              <Icon name={vw.icon} size={17} className={active ? "text-taupe-900" : "text-taupe-400"} />
              <span className="flex-1 text-sm font-semibold">{vw.label}</span>
            </button>
          );
        })}
      </div>

      <div className="flex items-center justify-between px-5 pb-2 pt-5 font-mono text-[10px] uppercase tracking-[0.18em] text-taupe-500">
        <span>Ventures</span>
        {view !== "general" && (
          <button onClick={onTodos} className={`rounded px-1.5 py-0.5 text-[9px] font-bold transition ${scope === "all" ? "bg-taupe-700 text-white" : "text-taupe-400 hover:text-taupe-200"}`}>TODOS</button>
        )}
      </div>
      <nav className="flex-1 space-y-0.5 overflow-y-auto px-3 hide-scrollbar">
        {VENTURES.map((v) => {
          const active = v.id === activeVentureId;
          return (
            <button key={v.id} onClick={() => onVenture(v.id)}
              className={`flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left transition ${active ? "bg-taupe-800 text-white ring-1 ring-amber-400/40" : "text-taupe-200 hover:bg-taupe-800/60"}`}>
              <Icon name={v.icon} size={17} className={active ? "text-amber-300" : "text-taupe-400"} />
              <span className="flex-1 truncate text-sm font-medium">{v.name}</span>
              <LegalDot level={v.legal} />
            </button>
          );
        })}
      </nav>

      <div className="border-t border-taupe-800/60 p-4">
        <div className="mb-2 font-mono text-[10px] uppercase tracking-[0.16em] text-taupe-500">Semáforo legal</div>
        <div className="space-y-1.5">
          {Object.entries(LEGAL).map(([k, l]) => (
            <div key={k} className="flex items-center gap-2 text-xs text-taupe-300">
              <span className="h-2 w-2 rounded-full" style={{ background: l.color }} />
              {l.label}
            </div>
          ))}
        </div>
      </div>

      <div className="flex items-center gap-3 border-t border-taupe-800/60 p-4">
        <span className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-amber-400 text-xs font-bold text-taupe-900">{user.usuario.slice(0, 2).toUpperCase()}</span>
        <div className="min-w-0 flex-1">
          <div className="truncate text-sm font-semibold text-white">{user.usuario}</div>
          <div className="truncate text-[11px] text-taupe-400">{user.rol}</div>
        </div>
        <button onClick={onLogout} title="Cerrar sesión" className="grid h-8 w-8 place-items-center rounded-lg text-taupe-300 transition hover:bg-taupe-800 hover:text-white">
          <Icon name="LogOut" size={16} />
        </button>
      </div>
      </aside>
    </React.Fragment>
  );
}

/* ----------------------------------- KPIs --------------------------------- */
function KpiCard({ icon, label, value, sub, accent }) {
  return (
    <div className="rounded-xl bg-white p-5 ring-1 ring-taupe-200/70 shadow-sm">
      <div className="flex items-center justify-between">
        <span className="font-mono text-[10px] uppercase tracking-[0.14em] text-taupe-400">{label}</span>
        <span className={`grid h-8 w-8 place-items-center rounded-lg ${accent || "bg-taupe-100 text-taupe-600"}`}>
          <Icon name={icon} size={16} />
        </span>
      </div>
      <div className="mt-3 text-[26px] font-extrabold leading-none tracking-tight text-taupe-900">{value}</div>
      {sub && <div className="mt-1.5 text-xs text-taupe-500">{sub}</div>}
    </div>
  );
}

function KpiRow() {
  const ventasMes = VENTURES.reduce((a, v) => a + v.ventasMes, 0);
  const utilidad = VENTURES.reduce((a, v) => a + v.utilidad, 0);
  const activos = VENTURES.filter((v) => v.estado === "Operando" || v.estado === "En ventas").length;
  const alertas = VENTURES.filter((v) => v.legal !== "verde").length;
  return (
    <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
      <KpiCard icon="DollarSign" label="Ventas del mes (COP)" value={formatCompactCOP(ventasMes)} sub={formatCOP(ventasMes)} accent="bg-emerald-100 text-emerald-700" />
      <KpiCard icon="TrendingUp" label="Utilidad del mes (COP)" value={formatCompactCOP(utilidad)} sub="Consolidado de los 8 ventures" accent="bg-amber-100 text-amber-700" />
      <KpiCard icon="Boxes" label="Ventures activos" value={`${activos} / ${VENTURES.length}`} sub="Operando o en ventas" accent="bg-taupe-100 text-taupe-700" />
      <KpiCard icon="TriangleAlert" label="Alertas legales" value={alertas} sub="Requieren revisión o acción" accent="bg-red-100 text-red-700" />
    </div>
  );
}

/* ---------------------------------- Table --------------------------------- */
function DevBar({ pct }) {
  return (
    <div className="flex items-center gap-2.5">
      <div className="h-1.5 w-28 overflow-hidden rounded-full bg-taupe-100">
        <div className="h-full rounded-full bg-amber-500" style={{ width: `${pct}%` }} />
      </div>
      <span className="w-9 text-right text-xs font-semibold tabular-nums text-taupe-700">{pct}%</span>
    </div>
  );
}

function ProjectsTable({ selectedId, onSelect }) {
  return (
    <div className="overflow-hidden rounded-xl bg-white ring-1 ring-taupe-200/70 shadow-sm">
      <div className="flex items-center justify-between border-b border-taupe-100 px-5 py-3.5">
        <h3 className="font-bold tracking-tight text-taupe-900">Proyectos</h3>
        <span className="font-mono text-[11px] text-taupe-400">junio 2026</span>
      </div>
      <div className="overflow-x-auto hide-scrollbar">
        <table className="w-full min-w-[680px] text-sm">
          <thead>
            <tr className="border-b border-taupe-100 text-left font-mono text-[10px] uppercase tracking-[0.1em] text-taupe-400">
              <th className="px-5 py-2.5 font-medium">Venture</th>
              <th className="px-3 py-2.5 font-medium">Desarrollo</th>
              <th className="px-3 py-2.5 font-medium text-right">Ventas mes</th>
              <th className="px-3 py-2.5 font-medium text-right">Utilidad</th>
              <th className="px-3 py-2.5 font-medium">Estado</th>
              <th className="px-5 py-2.5 font-medium">Legal</th>
            </tr>
          </thead>
          <tbody>
            {VENTURES.map((v) => {
              const active = v.id === selectedId;
              return (
                <tr key={v.id} onClick={() => onSelect(v.id)}
                  className={`cursor-pointer border-b border-taupe-50 transition ${active ? "bg-amber-50/60" : "hover:bg-taupe-50/60"}`}>
                  <td className="px-5 py-3">
                    <div className="flex items-center gap-3">
                      <span className="grid h-8 w-8 place-items-center rounded-lg bg-taupe-100 text-taupe-600">
                        <Icon name={v.icon} size={16} />
                      </span>
                      <div>
                        <div className="font-semibold text-taupe-900">{v.name}</div>
                        <div className="text-xs text-taupe-400">{v.sector}</div>
                      </div>
                    </div>
                  </td>
                  <td className="px-3 py-3"><DevBar pct={v.desarrollo} /></td>
                  <td className="px-3 py-3 text-right font-medium tabular-nums text-taupe-800">
                    {v.ventasMes > 0 ? formatCompactCOP(v.ventasMes) : <span className="text-taupe-300">—</span>}
                  </td>
                  <td className={`px-3 py-3 text-right font-medium tabular-nums ${v.utilidad < 0 ? "text-red-600" : "text-emerald-700"}`}>
                    {formatCompactCOP(v.utilidad)}
                  </td>
                  <td className="px-3 py-3"><EstadoPill estado={v.estado} /></td>
                  <td className="px-5 py-3"><LegalDot level={v.legal} withLabel /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* -------------------------------- Bar chart ------------------------------- */
function VentasChart() {
  const data = VENTURES.filter((v) => v.ventasMes > 0).sort((a, b) => b.ventasMes - a.ventasMes);
  const max = Math.max(...data.map((d) => d.ventasMes));
  return (
    <div className="rounded-xl bg-white p-5 ring-1 ring-taupe-200/70 shadow-sm">
      <div className="flex items-center justify-between">
        <h3 className="font-bold tracking-tight text-taupe-900">Ventas por venture</h3>
        <span className="font-mono text-[11px] text-taupe-400">COP · mes</span>
      </div>
      <div className="mt-5 space-y-3.5">
        {data.map((d) => (
          <div key={d.id} className="flex items-center gap-3">
            <div className="w-28 shrink-0 truncate text-xs font-medium text-taupe-600">{d.name}</div>
            <div className="relative h-6 flex-1 overflow-hidden rounded-md bg-taupe-50">
              <div className="flex h-full items-center justify-end rounded-md bg-gradient-to-r from-amber-400 to-amber-500 pr-2 transition-all"
                style={{ width: `${Math.max(18, (d.ventasMes / max) * 100)}%` }}>
                <span className="font-mono text-[10px] font-bold text-taupe-900">{formatCompactCOP(d.ventasMes)}</span>
              </div>
            </div>
          </div>
        ))}
      </div>
      <div className="mt-4 border-t border-taupe-100 pt-3 text-xs text-taupe-400">
        Solo se muestran ventures con ventas registradas este mes.
      </div>
    </div>
  );
}

/* ------------------------------ Project panel ----------------------------- */
function ModuleCard({ icon, title, accent, children }) {
  return (
    <div className="rounded-xl bg-white p-5 ring-1 ring-taupe-200/70 shadow-sm">
      <div className="mb-4 flex items-center gap-2.5">
        <span className={`grid h-8 w-8 place-items-center rounded-lg ${accent}`}>
          <Icon name={icon} size={16} />
        </span>
        <h4 className="font-bold tracking-tight text-taupe-900">{title}</h4>
      </div>
      {children}
    </div>
  );
}
function MiniStat({ label, value, tone = "text-taupe-900" }) {
  return (
    <div className="rounded-lg bg-taupe-50 px-3 py-2.5 ring-1 ring-taupe-100">
      <div className="font-mono text-[9px] uppercase tracking-[0.12em] text-taupe-400">{label}</div>
      <div className={`mt-0.5 text-lg font-extrabold leading-none tracking-tight tabular-nums ${tone}`}>{value}</div>
    </div>
  );
}

function VentureEditModal({ venture, onClose }) {
  const [f, setF] = useStateHub({
    ventasMes: venture.ventasMes, utilidad: venture.utilidad, desarrollo: venture.desarrollo,
    estado: venture.estado, legal: venture.legal, url: venture.url || "", blurb: venture.blurb || "",
  });
  const [busy, setBusy] = useStateHub(false);
  const [err, setErr] = useStateHub("");
  const set = (k) => (e) => setF((p) => ({ ...p, [k]: e.target.value }));
  const inputCls = "w-full rounded-lg bg-taupe-50 px-3.5 py-2.5 text-sm ring-1 ring-taupe-200 outline-none focus:ring-taupe-400";
  const save = async () => {
    setBusy(true); setErr("");
    try {
      const res = await fetch(`/api/ventures/${venture.id}`, {
        method: "PUT", credentials: "include", headers: { "content-type": "application/json" },
        body: JSON.stringify({ ...f, ventasMes: Number(f.ventasMes), utilidad: Number(f.utilidad), desarrollo: Number(f.desarrollo) }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) { setErr(data.error || "No se pudo guardar."); setBusy(false); return; }
      if (window.__refreshVentures) await window.__refreshVentures();
      onClose();
    } catch (e) { setErr("Sin conexión con el backend."); setBusy(false); }
  };
  return (
    <div className="fixed inset-0 z-50 grid place-items-center bg-taupe-900/60 p-4 backdrop-blur-sm" onClick={onClose}>
      <div className="hide-scrollbar max-h-[90vh] w-full max-w-lg overflow-y-auto rounded-2xl bg-white p-5 shadow-2xl shadow-black/30 sm:p-6" onClick={(e) => e.stopPropagation()}>
        <div className="mb-4 flex items-start justify-between gap-3">
          <div>
            <h3 className="text-lg font-extrabold tracking-tight text-taupe-900">Editar datos reales</h3>
            <p className="text-xs text-taupe-500">{venture.name} · los cambios quedan guardados para todo el equipo</p>
          </div>
          <button onClick={onClose} className="grid h-8 w-8 shrink-0 place-items-center rounded-lg text-taupe-400 transition hover:bg-taupe-50 hover:text-taupe-700"><Icon name="X" size={16} /></button>
        </div>
        <div className="grid gap-3 sm:grid-cols-2">
          <div>
            <label className="mb-1 block text-xs font-semibold text-taupe-600">Ventas del mes (COP)</label>
            <input type="number" value={f.ventasMes} onChange={set("ventasMes")} className={inputCls} />
          </div>
          <div>
            <label className="mb-1 block text-xs font-semibold text-taupe-600">Utilidad del mes (COP)</label>
            <input type="number" value={f.utilidad} onChange={set("utilidad")} className={inputCls} />
          </div>
          <div>
            <label className="mb-1 block text-xs font-semibold text-taupe-600">Desarrollo (%)</label>
            <input type="number" min="0" max="100" value={f.desarrollo} onChange={set("desarrollo")} className={inputCls} />
          </div>
          <div>
            <label className="mb-1 block text-xs font-semibold text-taupe-600">Estado</label>
            <select value={f.estado} onChange={set("estado")} className={inputCls}>
              {["Operando", "En ventas", "En desarrollo", "MVP"].map((s) => <option key={s} value={s}>{s}</option>)}
            </select>
          </div>
          <div>
            <label className="mb-1 block text-xs font-semibold text-taupe-600">Semáforo legal</label>
            <select value={f.legal} onChange={set("legal")} className={inputCls}>
              <option value="verde">Verde · Al día</option>
              <option value="amarillo">Amarillo · En revisión</option>
              <option value="rojo">Rojo · Acción requerida</option>
            </select>
          </div>
          <div>
            <label className="mb-1 block text-xs font-semibold text-taupe-600">Sitio web</label>
            <input value={f.url} onChange={set("url")} placeholder="dominio.com" className={inputCls} />
          </div>
          <div className="sm:col-span-2">
            <label className="mb-1 block text-xs font-semibold text-taupe-600">Descripción</label>
            <textarea value={f.blurb} onChange={set("blurb")} rows={3} className={inputCls} />
          </div>
        </div>
        {err && <div className="mt-3 rounded-lg bg-red-50 px-3 py-2 text-xs font-medium text-red-700 ring-1 ring-red-200">{err}</div>}
        <div className="mt-5 flex items-center justify-end gap-2.5">
          <button onClick={onClose} className="rounded-lg px-4 py-2.5 text-sm font-semibold text-taupe-600 transition hover:bg-taupe-50">Cancelar</button>
          <button onClick={save} disabled={busy} className="rounded-lg bg-taupe-900 px-5 py-2.5 text-sm font-bold text-amber-300 transition hover:bg-taupe-800 disabled:opacity-60">{busy ? "Guardando…" : "Guardar cambios"}</button>
        </div>
      </div>
    </div>
  );
}

function ProjectPanel({ venture, canEdit }) {
  const d = PROJECT_DETAIL[venture.id];
  const [editing, setEditing] = useStateHub(false);
  return (
    <div>
      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-3">
          <span className="grid h-11 w-11 place-items-center rounded-xl bg-taupe-900 text-amber-300">
            <Icon name={venture.icon} size={22} />
          </span>
          <div>
            <div className="flex items-center gap-2.5">
              <h2 className="text-xl font-extrabold tracking-tight text-taupe-900">{venture.name}</h2>
              <EstadoPill estado={venture.estado} />
            </div>
            <div className="text-xs text-taupe-500">{venture.sector} · {venture.blurb}</div>
            <div className="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1">
              {venture.page && (
                <a href={venture.page} className="inline-flex items-center gap-1 text-[11px] font-bold text-amber-600 hover:text-amber-700 transition">
                  Ver sitio del proyecto <Icon name="ArrowUpRight" size={12} />
                </a>
              )}
              {venture.url && (
                <a href={`https://${venture.url}`} target="_blank" rel="noopener noreferrer"
                  className="inline-flex items-center gap-1 text-[11px] font-semibold text-taupe-700 hover:text-amber-600 transition">
                  <Icon name="Globe" size={12} /> {venture.url}
                </a>
              )}
            </div>
          </div>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          {canEdit && (
            <button onClick={() => setEditing(true)}
              className="inline-flex items-center gap-1.5 rounded-full bg-taupe-900 px-3.5 py-2 text-xs font-bold text-amber-300 transition hover:bg-taupe-800">
              <Icon name="Pencil" size={13} /> Editar datos
            </button>
          )}
          <div className="flex items-center gap-2 rounded-full bg-white px-3.5 py-2 ring-1 ring-taupe-200">
            <LegalDot level={venture.legal} withLabel />
          </div>
        </div>
      </div>
      {editing && <VentureEditModal venture={venture} onClose={() => setEditing(false)} />}

      <div className="grid gap-4 lg:grid-cols-3">
        <ModuleCard icon="Megaphone" title="Marketing" accent="bg-amber-100 text-amber-700">
          <div className="grid grid-cols-2 gap-2.5">
            <MiniStat label="Campañas activas" value={d.marketing.campañas} />
            <MiniStat label="Leads del mes" value={d.marketing.leads} />
            <MiniStat label="Costo por lead" value={d.marketing.cpl ? formatCompactCOP(d.marketing.cpl) : "—"} />
            <MiniStat label="Alcance" value={d.marketing.alcance} />
          </div>
        </ModuleCard>

        <ModuleCard icon="Users" title="Ventas / CRM" accent="bg-emerald-100 text-emerald-700">
          <div className="grid grid-cols-2 gap-2.5">
            <MiniStat label="Pipeline" value={d.ventas.pipeline ? formatCompactCOP(d.ventas.pipeline) : "—"} />
            <MiniStat label="Negocios abiertos" value={d.ventas.deals} />
            <MiniStat label="Cierres del mes" value={d.ventas.cierreMes} tone="text-emerald-700" />
            <MiniStat label="Conversión" value={`${d.ventas.conversion}%`} />
          </div>
        </ModuleCard>

        <ModuleCard icon="Scale" title="Legal" accent="bg-red-100 text-red-700">
          <ul className="space-y-2">
            {d.legal.items.map((it) => (
              <li key={it.doc} className="flex items-center justify-between gap-3 rounded-lg bg-taupe-50 px-3 py-2 ring-1 ring-taupe-100">
                <span className="truncate text-xs font-medium text-taupe-700">{it.doc}</span>
                <LegalDot level={it.estado} />
              </li>
            ))}
          </ul>
          <div className="mt-3 flex items-start gap-2 rounded-lg bg-taupe-900 px-3 py-2.5 text-xs text-taupe-100">
            <Icon name="CalendarClock" size={15} className="mt-0.5 shrink-0 text-amber-300" />
            <span>{d.legal.vence}</span>
          </div>
        </ModuleCard>
      </div>
    </div>
  );
}

/* ----------------------------------- Hub ---------------------------------- */
function Hub() {
  const auth = useHubAuth();
  const [view, setView] = useStateHub("general");
  const [selectedId, setSelectedId] = useStateHub(VENTURES[0].id);
  const [scope, setScope] = useStateHub("all");
  const [navOpen, setNavOpen] = useStateHub(false);

  const user = auth.user;
  const baseViews = user ? HUB_VIEWS.filter((v) => user.admin || (user.vistas || []).includes(v.id)) : [];
  const views = user ? (user.admin ? [...baseViews, { id: "usuarios", label: "Usuarios", icon: "UserCog" }] : baseViews) : [];

  React.useEffect(() => {
    if (user && views.length && !views.some((v) => v.id === view)) setView(views[0].id);
  }, [user]);

  if (!user) return <LoginScreen auth={auth} />;

  const venture = VENTURES.find((v) => v.id === selectedId) || VENTURES[0];
  const activeVentureId = view === "general" ? selectedId : (scope === "all" ? null : scope);
  const onVenture = (id) => { setSelectedId(id); setScope(id); setNavOpen(false); };
  const onView = (id) => { setView(id); setNavOpen(false); };
  const ALL_VIEWS = [...HUB_VIEWS, { id: "usuarios", label: "Usuarios", icon: "UserCog" }];
  const meta = ALL_VIEWS.find((v) => v.id === view) || ALL_VIEWS[0];

  const SUBTITLE = {
    general: window.__dataSource === "live"
      ? `Vista consolidada de los ${VENTURES.length} ventures de 3H · datos en vivo`
      : `Vista consolidada de los ${VENTURES.length} ventures de 3H · datos demo`,
    marketing: "Control de campañas, presupuestos y leads de todos los ventures",
    ventas: "Pipeline y negocios de todos los ventures en un solo tablero",
    juridico: "Pool de abogados y asuntos legales de cada área, en un solo lugar",
    usuarios: "Gestiona usuarios, contraseñas y permisos de acceso al Hub",
  };

  return (
    <div className="flex min-h-screen bg-stone-100 text-taupe-900">
      <HubSidebar view={view} setView={onView} views={views} activeVentureId={activeVentureId}
        scope={scope} onVenture={onVenture} onTodos={() => setScope("all")} user={user} onLogout={auth.logout}
        open={navOpen} onClose={() => setNavOpen(false)} />

      <div className="flex-1 overflow-x-hidden">
        <header className="sticky top-0 z-10 flex items-center justify-between gap-3 border-b border-taupe-200/70 bg-stone-100/85 px-4 py-4 backdrop-blur sm:px-7">
          <div className="flex min-w-0 items-center gap-3">
            <button onClick={() => setNavOpen(true)}
              className="grid h-9 w-9 shrink-0 place-items-center rounded-lg bg-white text-taupe-700 ring-1 ring-taupe-200 transition hover:bg-taupe-50 lg:hidden" title="Abrir menú">
              <Icon name="Menu" size={17} />
            </button>
            <div className="min-w-0">
              <h1 className="truncate text-lg font-extrabold tracking-tight text-taupe-900 sm:text-xl">{meta.label}</h1>
              <p className="truncate text-xs text-taupe-500">{SUBTITLE[view]}</p>
            </div>
          </div>
          <div className="flex shrink-0 items-center gap-2.5">
            <span className="hidden items-center gap-2 rounded-lg bg-white px-3 py-2 text-xs font-medium text-taupe-600 ring-1 ring-taupe-200 sm:flex">
              <Icon name="Calendar" size={14} className="text-taupe-400" /> Junio 2026
            </span>
            <span className="grid h-9 w-9 place-items-center rounded-full bg-taupe-900 text-sm font-bold text-amber-300">{user.usuario.slice(0, 2).toUpperCase()}</span>
          </div>
        </header>

        <main className="p-4 sm:p-7">
          {view === "general" && (
            <div className="space-y-6">
              <KpiRow />
              <div className="grid gap-6 xl:grid-cols-[1.55fr_1fr]">
                <ProjectsTable selectedId={selectedId} onSelect={setSelectedId} />
                <VentasChart />
              </div>
              <div className="rounded-2xl bg-taupe-50/70 p-4 ring-1 ring-taupe-200/60 sm:p-5">
                <div className="mb-4 font-mono text-[10px] uppercase tracking-[0.18em] text-taupe-400">Proyecto seleccionado</div>
                <ProjectPanel venture={venture} canEdit={!!user.admin && auth.mode === "api"} />
              </div>
            </div>
          )}
          {view === "marketing" && <MarketingCenter scope={scope} setScope={setScope} />}
          {view === "ventas" && <VentasCenter scope={scope} setScope={setScope} />}
          {view === "juridico" && <JuridicoCenter scope={scope} setScope={setScope} />}
          {view === "usuarios" && <UsersPanel auth={auth} />}
          <div className="h-16" />
        </main>
      </div>
    </div>
  );
}

Object.assign(window, { Hub });
