/* global React, Icons, Avatar, Badge, IconButton, Menu, Button, Input */
// AppShell: navy app bar (Blue Human pattern) + breadcrumb strip + content slot. Hash-based router.

const ROUTES = [
  { hash: "#/mi-espacio",   label: "Mi espacio",    icon: <Icons.Home size={16} />, exact: true },
  { hash: "#/cursos",       label: "Catálogo",      icon: <Icons.Compass size={16} /> },
  { hash: "#/mi-espacio/cursos",  label: "Mis cursos", icon: <Icons.Book size={16} />, count: "enrolled" },
  { hash: "#/mi-espacio/apuntes", label: "Apuntes",    icon: <Icons.Notes size={16} /> },
  { hash: "#/certificados", label: "Certificados",  icon: <Icons.Award size={16} /> },
];

/* ===== Session =====
   The public campus is browsable without an account. Accounts are real Supabase Auth
   users (see CampusAuth in course-store.jsx). Until the client has restored the session,
   a stored Supabase token on this origin counts as signed in, so private pages do not
   flash the login screen on reload. */
const SUPABASE_TOKEN_KEY = /^sb-.+-auth-token$/;

function storageKeys() {
  try { return Object.keys(window.localStorage); } catch { return []; }
}
function isSignedIn() {
  const auth = window.CampusAuth;
  if (auth?.ready) return !!auth.user;
  return storageKeys().some(k => SUPABASE_TOKEN_KEY.test(k));
}
function signOut() { return window.CampusAuth?.signOut(); }
function useSession() {
  const [signedIn, setSignedIn] = React.useState(isSignedIn);
  React.useEffect(() => {
    const sync = () => setSignedIn(isSignedIn());
    window.addEventListener("bh-session", sync);
    window.addEventListener("storage", sync);
    return () => { window.removeEventListener("bh-session", sync); window.removeEventListener("storage", sync); };
  }, []);
  return signedIn;
}
const homeHash = () => (isSignedIn() ? "#/mi-espacio" : "#/cursos");

// Routes that need an account. Everything else (catalog, course pages) is public.
const PRIVATE_ROOTS = ["mi-espacio", "dashboard", "mis-cursos", "apuntes", "perfil", "certificados"];
const PRIVATE_COURSE_SUBPAGES = ["leccion", "indice"];
function isPrivateHash(hash) {
  const [, root, , sub] = hash.split("/");
  return PRIVATE_ROOTS.includes(root) || (root === "curso" && PRIVATE_COURSE_SUBPAGES.includes(sub));
}

// Guests see courses without the signed-in student's enrolment/progress.
function asViewer(course, signedIn = isSignedIn()) {
  if (signedIn) return course;
  return { ...course, enrolled: false, completed: false, progress: 0 };
}

function useHash() {
  const [hash, setHash] = React.useState(() => window.location.hash || homeHash());
  React.useEffect(() => {
    const onHash = () => setHash(window.location.hash || homeHash());
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  return hash;
}

function navigate(hash) {
  window.location.hash = hash;
  window.scrollTo({ top: 0 });
}

// Wordmark built in code, matching the official logo: isotype + "blue human" (TWK Everett Bold) + "academy" (TWK Everett Regular).
// Size it with font-size on the parent; `inverse` for navy backgrounds.
const BrandLogo = ({ inverse = false, size, className = "" }) => (
  <span className={`bh-logo${inverse ? " bh-logo--inverse" : ""} ${className}`} style={size ? { fontSize: size } : undefined}
        role="img" aria-label="Blue Human Academy">
    <img src="/images/bluehuman-isotype.png" alt="" className="bh-logo-mark" />
    <span className="bh-logo-word"><b>blue</b><b className="bh-logo-w2">human</b><span className="bh-logo-w3">academy</span></span>
  </span>
);

const Brand = () => (
  <a href={homeHash()} className="bh-brand" aria-label="Blue Human Academy · Inicio">
    <BrandLogo inverse />
  </a>
);

const Sidebar = () => null; // kept for backwards compatibility; navigation now lives in the app bar

const Topbar = ({ active = "" }) => {
  const signedIn = useSession();
  const routes = signedIn ? ROUTES : ROUTES.filter(r => !isPrivateHash(r.hash));
  // Real enrolments only (structured courses have a backend); hidden until known.
  const enrolledCount = (window.DATA?.COURSES || []).filter(c => c.units && window.CourseStore?.isEnrolled(c.id)).length;
  const isActive = r => (r.exact ? active === r.hash : active === r.hash || active.startsWith(`${r.hash}/`) || (r.hash === "#/cursos" && active.startsWith(r.hash)));
  return (
  <header className="bh-appbar" data-screen-label="Topbar">
    <div className="bh-appbar-inner">
      <Brand />

      <nav className="bh-nav" aria-label="Principal">
        {routes.map(r => (
          <a key={r.hash} href={r.hash} className="bh-nav-item" data-active={isActive(r)}
             aria-current={isActive(r) ? "page" : undefined}>
            {r.icon}<span>{r.label}</span>
            {r.count === "enrolled" && enrolledCount > 0 && <span className="bh-nav-count">{enrolledCount}</span>}
          </a>
        ))}
      </nav>

      <div className="bh-appbar-actions">
        <label className="bh-search">
          <Icons.Search size={15} style={{ opacity: .7 }} />
          <input placeholder="Buscar cursos, lecciones…" />
          <kbd>⌘K</kbd>
        </label>
        {!signedIn && (
          <>
            <a href="#/login" className="gs-btn gs-btn--inverse gs-btn--sm">Iniciar sesión</a>
            <a href="#/registro" className="gs-btn gs-btn--sm" style={{ background: "#fff", color: "var(--bh-navy)" }}>Crear cuenta</a>
          </>
        )}
        {signedIn && (
        <>
        <button className="bh-icon-btn" aria-label="Notificaciones">
          <Icons.Bell size={18} />
        </button>

        <Menu
          trigger={
            <button className="bh-user" aria-label="Cuenta">
              <Avatar size="sm" name={window.CampusAuth?.displayName() || "Estudiante"} />
              <Icons.Chevron size={14} style={{ opacity: .7 }} />
            </button>
          }
          items={[
            { icon: <Icons.User size={16} />,     label: "Mi perfil",       onClick: () => navigate("#/perfil") },
            { icon: <Icons.Award size={16} />,    label: "Certificados",    onClick: () => navigate("#/certificados") },
            { icon: <Icons.Settings size={16} />, label: "Configuración" },
            { sep: true },
            { icon: <Icons.Logout size={16} />,   label: "Cerrar sesión",   danger: true, onClick: () => { signOut(); navigate("#/cursos"); } },
          ]}
        />
        </>
        )}
      </div>
    </div>
  </header>
  );
};

const Breadcrumbs = ({ items }) => {
  if (!items || items.length < 2) return null;
  return (
    <div className="bh-crumbs">
      <nav className="bh-crumbs-inner" aria-label="Ruta">
        {items.map((b, i) => (
          <React.Fragment key={i}>
            {i > 0 && <Icons.ChevronRight size={12} style={{ color: "var(--text-subtle)", flexShrink: 0 }} />}
            {b.href
              ? <a href={b.href} style={{ whiteSpace: "nowrap" }}>{b.label}</a>
              : <strong>{b.label}</strong>}
          </React.Fragment>
        ))}
      </nav>
    </div>
  );
};

const AppShell = ({ active, breadcrumbs, children }) => (
  <div className="app-shell">
    <Topbar active={active} />
    <main className="app-main">
      <Breadcrumbs items={breadcrumbs} />
      <div className="app-content">{children}</div>
    </main>
    <footer className="bh-footer">
      <div className="bh-footer-inner">
        <BrandLogo size={20} />
        <span>© 2026 Blue Human · Seguridad humana, derechos humanos y construcción de paz</span>
      </div>
    </footer>
  </div>
);

Object.assign(window, { ROUTES, useHash, navigate, useSession, isSignedIn, signOut, homeHash, isPrivateHash, asViewer, AppShell, Topbar, Sidebar, Brand, BrandLogo, Breadcrumbs });
