/* global React, ReactDOM, useSession, isPrivateHash, homeHash, AppShell, Heading, Text, Button, useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakColor, TweakToggle,
   LoginPage, PersonalSpacePage, CatalogPage, CourseDetailPage, CourseIndexPage,
   ProfilePage, CertificatesPage, useHash, CourseReaderPage, useCourseProgress, DATA */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "unBlue": "#00A3E0",
  "dark": false,
  "density": "comfy"
}/*EDITMODE-END*/;

// Map a chosen UN-blue base to a 10-step scale (oklch-blended).
function applyBlueScale(hex) {
  // Each entry is approximate; mix base with white/black to hit Tailwind-like ramps.
  const root = document.documentElement;
  const scale = buildScale(hex);
  for (const [k, v] of Object.entries(scale)) {
    root.style.setProperty(`--primary-${k}`, v);
  }
}

function buildScale(hex) {
  return {
    50:  mix(hex, "#FFFFFF", 0.92),
    100: mix(hex, "#FFFFFF", 0.80),
    200: mix(hex, "#FFFFFF", 0.60),
    300: mix(hex, "#FFFFFF", 0.40),
    400: mix(hex, "#FFFFFF", 0.20),
    500: hex,
    600: mix(hex, "#000000", 0.15),
    700: mix(hex, "#000000", 0.30),
    800: mix(hex, "#000000", 0.45),
    900: mix(hex, "#000000", 0.60),
  };
}

function mix(a, b, t) {
  const pa = hexToRgb(a), pb = hexToRgb(b);
  const r = Math.round(pa.r + (pb.r - pa.r) * t);
  const g = Math.round(pa.g + (pb.g - pa.g) * t);
  const bl = Math.round(pa.b + (pb.b - pa.b) * t);
  return `#${[r, g, bl].map(n => n.toString(16).padStart(2, "0")).join("")}`;
}

function hexToRgb(h) {
  const m = h.replace("#", "");
  return { r: parseInt(m.slice(0, 2), 16), g: parseInt(m.slice(2, 4), 16), b: parseInt(m.slice(4, 6), 16) };
}

function Router() {
  const hash = useHash();
  const signedIn = useSession();
  useCourseProgress(); // enrolment / progress changes re-render every page
  // "#/curso/<id>/<sub>".split("/") → ["#", "curso", "<id>", "<sub>"]
  const parts = hash.split("/");
  const root  = parts[1] || "";
  const seg2  = parts[2];
  const seg3  = parts[3];

  // Public by default: only personal areas ask for an account, and return here after login.
  if (!signedIn && isPrivateHash(hash)) return <LoginPage next={hash} />;
  if (root === "login")        return <LoginPage />;
  if (root === "registro")     return <LoginPage initialTab="signup" enrollCourse={seg2} />;
  if (root === "mi-espacio")   return <PersonalSpacePage tab={seg2} sub={seg3} />;
  if (root === "dashboard")    return <PersonalSpacePage />;
  if (root === "cursos")       return <CatalogPage />;
  if (root === "mis-cursos")   return <PersonalSpacePage tab="cursos" />;
  if (root === "apuntes")      return <PersonalSpacePage tab="apuntes" />;
  if (root === "perfil")       return <ProfilePage />;
  if (root === "certificados") return <CertificatesPage />;
  if (root === "curso") {
    const structured = DATA.COURSES.find(c => c.id === seg2 && c.units);
    if (seg3 === "leccion" && structured) return <CourseReaderPage courseId={seg2} itemId={parts[4]} openNotes={parts[5] === "apuntes"} />;
    if (seg3 === "indice" && DATA.COURSES.some(c => c.id === seg2 && !c.comingSoon)) return <CourseIndexPage courseId={seg2} />;
    return <CourseDetailPage courseId={seg2} />;
  }
  if (UPCOMING_SECTIONS[root]) return <UpcomingSectionPage section={UPCOMING_SECTIONS[root]} />;
  return signedIn ? <PersonalSpacePage /> : <CatalogPage />;
}

// Sections linked from the landing page that are still being built.
const UPCOMING_SECTIONS = {
  programas: { title: "Programas",         lead: "Itinerarios de especialización que agrupan varios cursos en torno a un área de práctica profesional." },
  recursos:  { title: "Recursos",          lead: "Guías, publicaciones y materiales de referencia para el trabajo en derechos humanos y acción humanitaria." },
  eventos:   { title: "Eventos",           lead: "Seminarios, webinars y encuentros con especialistas y organizaciones." },
  academia:  { title: "Sobre la Academia", lead: "La misión de Blue Human Academy, su equipo docente y su enfoque pedagógico." },
};

function UpcomingSectionPage({ section }) {
  return (
    <AppShell active="" breadcrumbs={[{ label: "Inicio", href: homeHash() }, { label: section.title }]}>
      <section className="page-header" style={{ maxWidth: 760 }}>
        <Heading size="h1" className="mb-4">{section.title}</Heading>
        <Text size="lg" muted>{section.lead}</Text>
      </section>
      <div style={{ maxWidth: 760 }}>
        <Text>Estamos preparando esta sección. Mientras tanto, puedes consultar el catálogo de cursos disponibles.</Text>
        <div className="flex gap-2 mt-6">
          <Button as="a" href="#/cursos">Ver el catálogo</Button>
        </div>
      </div>
    </AppShell>
  );
}

function CampusToast() {
  const [notice, setNotice] = React.useState(null);
  React.useEffect(() => {
    const show = e => setNotice({ ...e.detail, at: Date.now() });
    window.addEventListener("bh-toast", show);
    return () => window.removeEventListener("bh-toast", show);
  }, []);
  React.useEffect(() => {
    if (!notice) return;
    const timeout = setTimeout(() => setNotice(null), 7000);
    return () => clearTimeout(timeout);
  }, [notice]);
  return notice && <div className="rd-toast" role="alert"><span>{notice.msg}</span><button onClick={() => setNotice(null)} aria-label="Cerrar aviso"><Icons.X size={16} /></button></div>;
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  React.useEffect(() => {
    if (t.unBlue.toUpperCase() === TWEAK_DEFAULTS.unBlue) {
      for (const k of [50,100,200,300,400,500,600,700,800,900]) document.documentElement.style.removeProperty(`--primary-${k}`);
    } else {
      applyBlueScale(t.unBlue);
    }
  }, [t.unBlue]);

  React.useEffect(() => {
    document.documentElement.setAttribute("data-theme", t.dark ? "dark" : "light");
  }, [t.dark]);

  React.useEffect(() => {
    document.documentElement.setAttribute("data-density", t.density);
  }, [t.density]);

  // Visitors land on the public catalog; signed-in students on their dashboard
  React.useEffect(() => {
    if (!window.location.hash) window.location.hash = homeHash();
  }, []);

  return (
    <>
      <Router />
      <CampusToast />
      <TweaksPanel>
        <TweakSection label="Color" />
        <TweakColor
          label="Acento"
          value={t.unBlue}
          options={["#00A3E0", "#006C95", "#4B9FFF", "#0A1E33"]}
          onChange={v => setTweak("unBlue", v)}
        />
        <TweakSection label="Apariencia" />
        <TweakToggle
          label="Modo oscuro"
          value={t.dark}
          onChange={v => setTweak("dark", v)}
        />
        <TweakRadio
          label="Densidad"
          value={t.density}
          options={["comfy", "compact"]}
          onChange={v => setTweak("density", v)}
        />
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
