/* ============================================================
   PURE SPA — AGENDA · Admin Shell
   Sidebar + header + selector de rol + ruteo de vistas.
   ============================================================ */
const NAV = [
  { to: "/admin/dashboard", label: "Dashboard", icon: "LayoutDashboard" },
  { to: "/admin/calendar", label: "Agenda", icon: "CalendarDays" },
  { to: "/admin/bookings", label: "Reservas", icon: "ClipboardList" },
  { to: "/admin/customers", label: "Clientas", icon: "Users" },
  { to: "/admin/services", label: "Servicios", icon: "Sparkles" },
  { to: "/admin/beds", label: "Camillas", icon: "BedDouble" },
  { to: "/admin/payments", label: "Pagos", icon: "Wallet", perm: "payment:view" },
  { to: "/admin/reports", label: "Reportes", icon: "BarChart3", perm: "reports:view" },
  { to: "/admin/settings", label: "Configuración", icon: "Settings", perm: "settings:view" },
];

function RoleSelector() {
  const { role, setRole } = useApp();
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => ref.current && !ref.current.contains(e.target) && setOpen(false);
    document.addEventListener("mousedown", h); return () => document.removeEventListener("mousedown", h);
  }, []);
  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button onClick={() => setOpen(!open)} style={{ display: "flex", alignItems: "center", gap: 9, background: C.white,
        border: `1px solid ${C.line}`, borderRadius: 999, padding: "8px 14px", cursor: "pointer" }}>
        <span style={{ width: 7, height: 7, borderRadius: 999, background: C.gold }} />
        <span style={{ fontFamily: "var(--font-body)", fontSize: 11, color: C.taupe, fontWeight: 400 }} className="hide-sm">Viendo como:</span>
        <span style={{ fontFamily: "var(--font-body)", fontSize: 12, color: C.espresso, fontWeight: 600 }}>{ROLE_LABELS[role]}</span>
        <Icon name="ChevronDown" size={14} color={C.taupe} />
      </button>
      {open && (
        <div style={{ position: "absolute", top: "calc(100% + 8px)", right: 0, zIndex: 60, background: C.white,
          border: `1px solid ${C.line}`, borderRadius: 12, boxShadow: "0 16px 48px rgba(43,37,32,0.16)", padding: 6, minWidth: 200 }}>
          <div style={{ fontFamily: "var(--font-body)", fontSize: 9.5, fontWeight: 600, letterSpacing: "0.12em",
            textTransform: "uppercase", color: C.taupe, padding: "8px 12px 6px" }}>Probar interfaz como</div>
          {Object.keys(ROLE_LABELS).map((r) => (
            <button key={r} onClick={() => { setRole(r); setOpen(false); }} style={{ width: "100%", textAlign: "left",
              display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", borderRadius: 8, border: "none",
              cursor: "pointer", background: role === r ? C.ivory : "transparent" }}>
              <span style={{ width: 7, height: 7, borderRadius: 999, background: role === r ? C.gold : C.line }} />
              <div>
                <div style={{ fontFamily: "var(--font-body)", fontSize: 13, color: C.espresso, fontWeight: role === r ? 600 : 400 }}>{ROLE_LABELS[r]}</div>
                <div style={{ fontFamily: "var(--font-body)", fontSize: 10.5, color: C.taupe }}>{ROLE_USER[r].role}</div>
              </div>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function Sidebar({ mobileOpen, setMobileOpen }) {
  const { route, navigate, can } = useApp();
  const items = NAV.filter((n) => !n.perm || can(n.perm));
  const content = (
    <>
      <div style={{ padding: "26px 24px 22px", display: "flex", alignItems: "center", gap: 12 }}>
        <img src="assets/isotipo-gold.png" style={{ height: 38 }} alt="" />
        <div>
          <div style={{ fontFamily: "var(--font-accent)", fontSize: 26, color: C.gold, lineHeight: 0.9 }}>Pure Spa</div>
          <div style={{ fontFamily: "var(--font-body)", fontSize: 8.5, fontWeight: 600, letterSpacing: "0.18em",
            textTransform: "uppercase", color: C.taupe, marginTop: 2 }}>Agenda · Panel interno</div>
        </div>
      </div>
      <nav style={{ padding: "6px 14px", display: "flex", flexDirection: "column", gap: 2 }}>
        {items.map((n) => {
          const active = route === n.to;
          return (
            <a key={n.to} href={"#" + n.to} onClick={() => setMobileOpen(false)}
              style={{ display: "flex", alignItems: "center", gap: 13, padding: "11px 14px", borderRadius: 10,
                textDecoration: "none", transition: "all .18s",
                background: active ? C.espresso : "transparent",
                color: active ? C.ivory : C.taupe }}
              onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = C.ivoryDeep; }}
              onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = "transparent"; }}>
              <Icon name={n.icon} size={18} color={active ? C.gold : C.taupe} />
              <span style={{ fontFamily: "var(--font-body)", fontSize: 13, fontWeight: active ? 600 : 400,
                letterSpacing: "0.02em", color: active ? C.ivory : C.espresso }}>{n.label}</span>
            </a>
          );
        })}
      </nav>
      <div style={{ marginTop: "auto", padding: 18 }}>
        <a href="#/booking" style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 14px", borderRadius: 10,
          textDecoration: "none", background: C.gold15, border: `1px solid ${C.champ30}` }}>
          <Icon name="ExternalLink" size={16} color={C.goldDeep} />
          <span style={{ fontFamily: "var(--font-body)", fontSize: 11.5, fontWeight: 600, color: C.goldDeep,
            letterSpacing: "0.04em" }}>Página pública</span>
        </a>
      </div>
    </>
  );
  return (
    <>
      <aside className="pu-sidebar" style={{ width: 248, background: C.white, borderRight: `1px solid ${C.line}`,
        display: "flex", flexDirection: "column", position: "sticky", top: 0, height: "100vh", flexShrink: 0 }}>
        {content}
      </aside>
      {mobileOpen && (
        <div className="pu-drawer-overlay" onClick={() => setMobileOpen(false)}
          style={{ position: "fixed", inset: 0, zIndex: 90, background: "rgba(43,37,32,0.42)" }}>
          <aside onClick={(e) => e.stopPropagation()} style={{ width: 264, height: "100%", background: C.white,
            display: "flex", flexDirection: "column", animation: "puSlideL .28s ease" }}>
            {content}
          </aside>
        </div>
      )}
    </>
  );
}

function Header({ onMenu }) {
  const { user, roleLabel } = useApp();
  const now = new Date();
  const dias = ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"];
  const meses = ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"];
  const dateStr = `${dias[now.getDay()]} ${now.getDate()} de ${meses[now.getMonth()]}, ${now.getFullYear()}`;
  return (
    <header style={{ position: "sticky", top: 0, zIndex: 40, background: "rgba(248,243,234,0.88)", backdropFilter: "blur(10px)",
      borderBottom: `1px solid ${C.line}`, padding: "14px 26px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 14, minWidth: 0 }}>
        <button className="pu-burger" onClick={onMenu} style={{ background: C.white, border: `1px solid ${C.line}`,
          borderRadius: 10, width: 40, height: 40, display: "none", alignItems: "center", justifyContent: "center", cursor: "pointer" }}>
          <Icon name="Menu" size={20} color={C.espresso} />
        </button>
        <div style={{ minWidth: 0 }} className="hide-sm">
          <div style={{ fontFamily: "var(--font-body)", fontSize: 9.5, fontWeight: 600, letterSpacing: "0.14em",
            textTransform: "uppercase", color: C.taupe }}>Hoy</div>
          <div style={{ fontFamily: "var(--font-display)", fontSize: 18, color: C.espresso, lineHeight: 1.1 }}>{dateStr}</div>
        </div>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <RoleSelector />
        <div style={{ display: "flex", alignItems: "center", gap: 10 }} className="hide-sm">
          <div style={{ textAlign: "right" }}>
            <div style={{ fontFamily: "var(--font-body)", fontSize: 12.5, fontWeight: 600, color: C.espresso }}>{user.name}</div>
            <div style={{ fontFamily: "var(--font-body)", fontSize: 10, color: C.taupe }}>{user.role}</div>
          </div>
          <div style={{ width: 38, height: 38, borderRadius: 999, background: C.espresso, color: C.gold,
            display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-display)", fontSize: 17 }}>
            {user.name.split(" ").map((w) => w[0]).slice(0, 2).join("")}
          </div>
        </div>
        <button title="Cerrar sesión" style={{ background: C.white, border: `1px solid ${C.line}`, borderRadius: 999,
          width: 38, height: 38, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}>
          <Icon name="LogOut" size={17} color={C.taupe} />
        </button>
      </div>
    </header>
  );
}

function AdminShell() {
  const { route } = useApp();
  const [mobileOpen, setMobileOpen] = useState(false);
  const views = {
    "/admin/dashboard": window.Dashboard,
    "/admin/calendar": window.CalendarView,
    "/admin/bookings": window.BookingsView,
    "/admin/customers": window.CustomersView,
    "/admin/services": window.ServicesView,
    "/admin/beds": window.BedsView,
    "/admin/payments": window.PaymentsView,
    "/admin/reports": window.ReportsView,
    "/admin/settings": window.SettingsView,
  };
  const View = views[route] || window.Dashboard;
  return (
    <div style={{ display: "flex", minHeight: "100vh", background: C.ivory }}>
      <Sidebar mobileOpen={mobileOpen} setMobileOpen={setMobileOpen} />
      <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column" }}>
        <Header onMenu={() => setMobileOpen(true)} />
        <main style={{ flex: 1, padding: "28px 26px 60px", maxWidth: 1320, width: "100%", margin: "0 auto" }} className="pu-main">
          <View />
        </main>
      </div>
    </div>
  );
}

/* ---- encabezado de página reutilizable ---- */
function PageHead({ eyebrow, title, sub, children }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, marginBottom: 24, flexWrap: "wrap" }}>
      <div>
        {eyebrow && <Eyebrow color={C.gold} style={{ marginBottom: 7 }}>{eyebrow}</Eyebrow>}
        <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 400, fontSize: 32, color: C.espresso, lineHeight: 1.05 }}>{title}</h1>
        {sub && <p style={{ fontFamily: "var(--font-body)", fontWeight: 300, fontSize: 13.5, color: C.taupe, marginTop: 6 }}>{sub}</p>}
      </div>
      <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>{children}</div>
    </div>
  );
}

/* ---- card base ---- */
function Card({ children, style, pad = 20 }) {
  return <div style={{ background: C.white, border: `1px solid ${C.line}`, borderRadius: 16, padding: pad,
    boxShadow: "0 2px 16px rgba(43,37,32,0.05)", ...style }}>{children}</div>;
}

Object.assign(window, { AdminShell, PageHead, Card, NAV });
