// Student theme registry, frame, and shared themed atoms.
const STX_THEMES = [
  {
    key: "classic",
    label: "Classic",
    blurb: "The original EpiqMinds look",
    dark: false,
    swatch: ["#fff", "#ff6b55", "#13284b"],
  },
  {
    key: "adventure",
    label: "Adventure",
    blurb: "A bright learning journey",
    dark: false,
    swatch: ["#b9e5a0", "#139b8f", "#fdd75b"],
  },
  {
    key: "space",
    label: "Space Explorer",
    blurb: "A calm voyage through the stars",
    dark: true,
    swatch: ["#0b1026", "#4de1ff", "#ffc94d"],
  },
  {
    key: "playground",
    label: "Playground",
    blurb: "A sunny classroom with a friendly robot",
    dark: false,
    layout: "sidebar",
    swatch: ["#fdfaf2", "#f5c518", "#1b4d3e"],
  },
  {
    key: "ocean",
    label: "Ocean Explorer",
    blurb: "Dive deep beneath the waves with a sea turtle explorer",
    dark: true,
    swatch: ["#063b59", "#18c7d4", "#ff7185"],
  },
  {
    key: "dino",
    label: "Dino Discovery",
    blurb: "Roam a prehistoric jungle with a friendly dinosaur explorer",
    dark: false,
    swatch: ["#143a1e", "#598218", "#84cc16"],
  },
];

const StxThemeEvent = "stx-theme-change";

const stxProfessional = () => document.documentElement.dataset.preset === "professional";

const stxValidTheme = (value) => (
  STX_THEMES.some((item) => item.key === value) ? value : "classic"
);

const stxReadTheme = () => {
  if (stxProfessional()) return "classic";
  try {
    return stxValidTheme(localStorage.getItem("cl_student_theme"));
  } catch (_) {
    return "classic";
  }
};

const useStudentTheme = () => {
  const [key, setState] = React.useState(stxReadTheme);

  React.useEffect(() => {
    const sync = () => setState(stxReadTheme());
    window.addEventListener(StxThemeEvent, sync);
    window.addEventListener("storage", sync);
    return () => {
      window.removeEventListener(StxThemeEvent, sync);
      window.removeEventListener("storage", sync);
    };
  }, []);

  const setKey = React.useCallback((next) => {
    const value = stxProfessional() ? "classic" : stxValidTheme(next);
    try {
      localStorage.setItem("cl_student_theme", value);
    } catch (_) {}
    setState(value);
    window.dispatchEvent(new CustomEvent(StxThemeEvent, { detail: value }));
  }, []);

  return [stxProfessional() ? "classic" : key, setKey];
};

const stxIcon = (name, size = 24) => {
  const paths = {
    home: <><path d="M3 11.5 12 4l9 7.5"/><path d="M5.5 10v10h13V10M9 20v-6h6v6"/></>,
    calendar: (
      <>
        <rect x="3" y="5" width="18" height="16" rx="2"/>
        <path d="M7 3v4m10-4v4M3 10h18"/>
      </>
    ),
    book: (
      <>
        <path d="M4 5.5A3.5 3.5 0 0 1 7.5 2H11v18H7.5A3.5 3.5 0 0 0 4 23z"/>
        <path d="M20 5.5A3.5 3.5 0 0 0 16.5 2H13v18h3.5A3.5 3.5 0 0 1 20 23z"/>
      </>
    ),
    chart: <><path d="M4 20V10m6 10V4m6 16v-7m5 7H2"/></>,
    quiz: (
      <>
        <circle cx="12" cy="12" r="9"/>
        <path d="M9.8 9a2.4 2.4 0 1 1 3.7 2c-1 .6-1.5 1.1-1.5 2.2M12 17h.01"/>
      </>
    ),
    homework: (
      <>
        <rect x="5" y="4" width="14" height="17" rx="2"/>
        <path d="M9 4V2h6v2m-6 9 2 2 4-4"/>
      </>
    ),
    forum: <><path d="M4 5h16v12H9l-5 4z"/></>,
    flame: (
      <path
        d="M13.5 3.5c.6 3-1.3 4.4-2.6 6.2-1-1.2-1.3-2.2-1-3.4
          C7 8.1 5 10.7 5 14a7 7 0 0 0 14 0c0-4.2-2.5-7.7-5.5-10.5Z"
      />
    ),
    coin: (
      <>
        <circle cx="12" cy="12" r="9"/>
        <path
          d="M14.5 8.5c-.6-.5-1.4-.8-2.5-.8-1.4 0-2.5.7-2.5 1.8
            0 3 5 1.2 5 4.1 0 1.1-1 1.9-2.6 1.9-1 0-2-.3-2.8-1M12 6v12"
        />
      </>
    ),
    star: <path d="m12 3 2.8 5.7 6.2.9-4.5 4.4 1.1 6.2-5.6-2.9-5.6 2.9 1.1-6.2L3 9.6l6.2-.9z"/>,
    menu: <path d="M4 7h16M4 12h16M4 17h16"/>,
    close: <path d="m6 6 12 12M18 6 6 18"/>,
    palette: (
      <>
        <path
          d="M12 3a9 9 0 0 0 0 18h1.4a2 2 0 0 0 1.5-3.3
            1.8 1.8 0 0 1 1.4-3h1.2A3.5 3.5 0 0 0 21 11.2 8.7 8.7 0 0 0 12 3Z"
        />
        <path d="M7.5 10h.01M10 6.5h.01M15 7h.01"/>
      </>
    ),
    video: <><rect x="3" y="6" width="13" height="12" rx="2"/><path d="m16 10 5-3v10l-5-3"/></>,
    check: <path d="m5 12 4 4L19 6"/>,
    trophy: (
      <>
        <path d="M8 4h8v4c0 4-1.7 6-4 6s-4-2-4-6zM12 14v4m-4 3h8"/>
        <path d="M8 6H4v2c0 2 1.3 3 4 3m8-5h4v2c0 2-1.3 3-4 3"/>
      </>
    ),
    user: (
      <>
        <circle cx="12" cy="8" r="4"/>
        <path d="M4 21c.8-4 3.5-6 8-6s7.2 2 8 6"/>
      </>
    ),
    shop: (
      <>
        <path d="M5 9h14l-1 12H6z"/>
        <path d="M9 9V6a3 3 0 0 1 6 0v3"/>
      </>
    ),
    mission: (
      <>
        <path d="M12 3c4 2 6 5 6 9l-6 8-6-8c0-4 2-7 6-9Z"/>
        <circle cx="12" cy="10" r="2"/>
      </>
    ),
    chevronLeft: <path d="m15 5-7 7 7 7"/>,
    chevronRight: <path d="m9 5 7 7-7 7"/>,
    dot: <circle cx="12" cy="12" r="3" fill="currentColor" stroke="none"/>,
    units: <><path d="m12 3 8 4-8 4-8-4z"/><path d="m4 12 8 4 8-4M4 17l8 4 8-4"/></>,
    lessons: <><rect x="4" y="4" width="16" height="16" rx="2"/><path d="m8 12 2.5 2.5L16 9"/></>,
  };
  return (
    <svg
      viewBox="0 0 24 24"
      width={size}
      height={size}
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      {paths[name] || paths.dot}
    </svg>
  );
};

const StxThemePicker = ({ variant = "themed" }) => {
  const [key, setKey] = useStudentTheme();
  const [open, setOpen] = React.useState(false);
  const [index, setIndex] = React.useState(() => (
    Math.max(0, STX_THEMES.findIndex((item) => item.key === key))
  ));
  const pickerRoot = React.useRef(null);
  const pickerButton = React.useRef(null);
  const pickerItems = React.useRef([]);

  React.useEffect(() => {
    if (!open) return;
    const outside = (event) => {
      if (!pickerRoot.current?.contains(event.target)) setOpen(false);
    };
    document.addEventListener("mousedown", outside);
    return () => document.removeEventListener("mousedown", outside);
  }, [open]);

  React.useEffect(() => {
    if (open) pickerItems.current[index]?.focus();
  }, [open, index]);

  if (stxProfessional()) return null;

  const choose = (next) => {
    setKey(next);
    setOpen(false);
    pickerButton.current?.focus();
  };

  const handleKeys = (event) => {
    if (event.key === "Escape") {
      event.preventDefault();
      setOpen(false);
      pickerButton.current?.focus();
    }
    if (event.key === "ArrowDown" || event.key === "ArrowUp") {
      event.preventDefault();
      setIndex((old) => (
        (old + (event.key === "ArrowDown" ? 1 : -1) + STX_THEMES.length)
        % STX_THEMES.length
      ));
    }
    if (event.key === "Home") {
      event.preventDefault();
      setIndex(0);
    }
    if (event.key === "End") {
      event.preventDefault();
      setIndex(STX_THEMES.length - 1);
    }
  };

  return (
    <div
      className={`stx-theme-picker stx-theme-picker-${variant}`}
      ref={pickerRoot}
    >
      <button
        ref={pickerButton}
        type="button"
        className="stx-theme-trigger"
        aria-haspopup="menu"
        aria-expanded={open}
        onClick={() => {
          setIndex(Math.max(0, STX_THEMES.findIndex((item) => item.key === key)));
          setOpen((value) => !value);
        }}
      >
        <span>{stxIcon("palette", 18)}</span>
        <span>Theme</span>
      </button>
      {open && (
        <div
          className="stx-theme-menu"
          role="menu"
          aria-label="Choose student theme"
          onKeyDown={handleKeys}
        >
          {STX_THEMES.map((item, itemIndex) => (
            <button
              key={item.key}
              ref={(node) => { pickerItems.current[itemIndex] = node; }}
              type="button"
              role="menuitemradio"
              aria-checked={item.key === key}
              tabIndex={itemIndex === index ? 0 : -1}
              className="stx-theme-option"
              onClick={() => choose(item.key)}
              onMouseEnter={() => setIndex(itemIndex)}
            >
              <span className="stx-theme-swatches" aria-hidden="true">
                {item.swatch.map((color) => (
                  <i key={color} style={{ background: color }}/>
                ))}
              </span>
              <span>
                <b>{item.label}</b>
                <small>{item.blurb}</small>
              </span>
              <span aria-hidden="true">{item.key === key ? "✓" : ""}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

const StxContext = React.createContext({ active: false, theme: "classic" });

const useStx = () => React.useContext(StxContext);

const StxCard = ({ className = "", children, ...props }) => (
  <section {...props} className={`stx-card ${className}`}>
    {children}
  </section>
);

const StxButton = ({ variant = "primary", className = "", children, ...props }) => (
  <button
    type="button"
    {...props}
    className={`stx-btn stx-btn-${variant} ${className}`}
  >
    {children}
  </button>
);

const StxChip = ({ className = "", children }) => (
  <span className={`stx-chip ${className}`}>{children}</span>
);

const StxPill = ({ tone = "success", children }) => (
  <span className={`stx-pill stx-pill-${tone}`}>{children}</span>
);

const StxProgress = ({
  value = 0,
  max = 100,
  label = "Progress",
  valueText,
}) => {
  const safeValue = Math.min(max, Math.max(0, value));
  const percentage = max ? Math.min(100, Math.max(0, safeValue / max * 100)) : 0;
  const width = safeValue > 0 ? `max(8px, ${percentage}%)` : "0";

  return (
    <div
      className="stx-progress"
      role="progressbar"
      aria-label={label}
      aria-valuemin="0"
      aria-valuemax={max}
      aria-valuenow={safeValue}
      aria-valuetext={valueText || `${safeValue} of ${max} XP`}
    >
      <i style={{ width }}/>
    </div>
  );
};

const StxDonut = ({
  value = 0,
  empty = false,
  label,
  className = "",
  style,
  ...props
}) => (
  <div
    {...props}
    className={`stx-donut ${className}`}
    role="img"
    aria-label={label || (
      empty ? "No marked classes yet" : `${Math.round(value)}% attendance`
    )}
    style={{
      ...style,
      "--stx-donut": `${Math.min(100, Math.max(0, value)) * 3.6}deg`,
    }}
  >
    <span>{empty ? "—" : `${Math.round(value)}%`}</span>
  </div>
);

const StxIconTile = ({ icon, tint = 1 }) => (
  <span className={`stx-icon-tile stx-tint-${tint}`}>{icon}</span>
);

const StxPageTitle = ({ children }) => (
  <h1 className="stx-page-title">{children}</h1>
);

const StxEmpty = ({ children }) => (
  <div className="stx-empty">{children}</div>
);

const StxSkeleton = ({ className = "" }) => (
  <span className={`stx-skeleton ${className}`} aria-hidden="true"/>
);

const stxNavIcon = {
  home: "home",
  schedule: "calendar",
  courses: "book",
  progress: "chart",
  quiz: "quiz",
  quests: "quiz",
  homework: "homework",
  forum: "forum",
  certificates: "trophy",
  shop: "shop",
  profile: "user",
  mission: "mission",
};

const stxNavItems = (nav) => {
  const seen = new Set();
  const order = ["home", "schedule", "courses", "progress", "quiz", "homework"];
  const aliases = { quests: "quiz" };
  const all = ["student", "student_home"].flatMap((name) => (
    (navMenu(nav, name) || []).flatMap((section) => section.items || [])
  ));

  return all
    .map((item) => ({ ...item, key: aliases[item.key] || item.key }))
    .filter((item) => (
      order.includes(item.key)
      && !seen.has(item.key)
      && (!item.flag || featureOn(nav, item.flag))
      && seen.add(item.key)
    ))
    .sort((a, b) => order.indexOf(a.key) - order.indexOf(b.key));
};

const StxNav = ({ placement, route, go }) => {
  const nav = useNav();
  const items = stxNavItems(nav);

  return (
    <nav
      className={`stx-nav stx-nav-${placement}`}
      aria-label="Student navigation"
    >
      {items.map((item) => {
        const active = item.key === "home"
          ? route === "/app/student"
          : route === item.path || route.startsWith(item.path + "/");
        return (
          <button
            type="button"
            key={item.key}
            className={active ? "stx-nav-active" : ""}
            aria-current={active ? "page" : undefined}
            aria-label={item.label === "Quests" ? "Quiz" : item.label}
            title={item.label === "Quests" ? "Quiz" : item.label}
            onClick={() => go(item.path)}
          >
            <span>{stxIcon(stxNavIcon[item.key] || "dot", 21)}</span>
            <b>{item.label === "Quests" ? "Quiz" : item.label}</b>
          </button>
        );
      })}
    </nav>
  );
};

const StxAccountMenu = ({
  session,
  logout,
  student,
  loading,
  route,
  go,
  compact = false,
  triggerVariant = "menu",
}) => {
  const [themeKey, setThemeKey] = useStudentTheme();
  const [open, setOpen] = React.useState(false);
  const rootRef = React.useRef(null);
  const buttonRef = React.useRef(null);
  const panelRef = React.useRef(null);
  const panelId = "stx-account-menu";
  const fullName = student.name || session?.name || "Student";
  const level = Math.floor((student.xp || 0) / 500) + 1;

  React.useEffect(() => {
    if (!open) return undefined;
    const outside = (event) => {
      if (!rootRef.current?.contains(event.target)) setOpen(false);
    };
    const escape = (event) => {
      if (event.key !== "Escape") return;
      setOpen(false);
      buttonRef.current?.focus();
    };
    document.addEventListener("mousedown", outside);
    document.addEventListener("keydown", escape);
    panelRef.current?.querySelector("button")?.focus();
    return () => {
      document.removeEventListener("mousedown", outside);
      document.removeEventListener("keydown", escape);
    };
  }, [open]);

  React.useEffect(() => setOpen(false), [route]);

  const chooseTheme = (nextTheme) => {
    setThemeKey(nextTheme);
    setOpen(false);
    buttonRef.current?.focus();
  };

  return (
    <div className="stx-account" ref={rootRef}>
      <button
        ref={buttonRef}
        type="button"
        className={triggerVariant === "avatar" ? "stxpg-account-trigger" : "stx-account-trigger"}
        aria-label={open ? "Close menu" : "Open menu"}
        aria-expanded={open}
        aria-controls={panelId}
        aria-haspopup="true"
        onClick={() => setOpen((value) => !value)}
      >
        {triggerVariant === "avatar" ? (
          <>
            <Avatar name={fullName[0]} color="var(--stx-primary)" size={32}/>
            <span className="stxpg-account-name">{fullName.split(" ")[0]}</span>
            <span className="stxpg-account-chevron" aria-hidden="true">▾</span>
          </>
        ) : (
          stxIcon(open ? "close" : "menu", 22)
        )}
      </button>
      {open && (
        <div id={panelId} className="stx-account-panel" ref={panelRef}>
          <button
            type="button"
            className="stx-account-user stx-account-user-action"
            onClick={() => {
              setOpen(false);
              go && go("/app/student/profile");
            }}
            aria-label="View profile"
            title="View profile"
          >
            <Avatar name={fullName[0]} color="var(--stx-primary)" size={42}/>
            <span>
              <b>{fullName}</b>
              <small>Level {level} • View Profile →</small>
            </span>
          </button>
          <button
            type="button"
            className="stx-account-profile-btn"
            onClick={() => {
              setOpen(false);
              go && go("/app/student/profile");
            }}
          >
            {stxIcon("user", 16)}
            <span>My Profile</span>
            <span aria-hidden="true" style={{ marginLeft: "auto", opacity: 0.6 }}>→</span>
          </button>
          {!compact && (
            <div className="stx-account-stats">
              {loading ? (
                <StxSkeleton className="stx-chip-skeleton"/>
              ) : (
                <>
                  <StxChip>{stxIcon("flame", 16)} {student.streak_days || 0} day streak</StxChip>
                  <StxChip>{stxIcon("coin", 16)} {student.coins ?? 0} coins</StxChip>
                </>
              )}
            </div>
          )}
          {!compact && typeof NotificationBell !== "undefined" && (
            <div className="stx-account-notifications">
              <span>Notifications</span>
              <NotificationBell session={session}/>
            </div>
          )}
          <div
            className="stx-account-themes"
            role="radiogroup"
            aria-label="Theme"
          >
            <b>{stxIcon("palette", 16)} Theme</b>
            {STX_THEMES.map((item) => (
              <button
                key={item.key}
                type="button"
                role="radio"
                aria-checked={item.key === themeKey}
                onClick={() => chooseTheme(item.key)}
              >
                <span className="stx-theme-swatches" aria-hidden="true">
                  {item.swatch.map((color) => (
                    <i key={color} style={{ background: color }}/>
                  ))}
                </span>
                <span>{item.label}</span>
                <span aria-hidden="true">{item.key === themeKey ? "✓" : ""}</span>
              </button>
            ))}
          </div>
          <button type="button" className="stx-account-signout" onClick={logout}>
            Sign out
          </button>
        </div>
      )}
    </div>
  );
};

const StxTopBar = ({ session, logout, student, loading, route, go }) => {
  const { theme } = useStx();
  if (theme === "ocean" && typeof StxOceanTopBar !== "undefined") {
    return (
      <StxOceanTopBar
        session={session}
        logout={logout}
        student={student}
        loading={loading}
        route={route}
        go={go}
      />
    );
  }
  if (theme === "dino" && typeof StxDinoTopBar !== "undefined") {
    return (
      <StxDinoTopBar
        session={session}
        logout={logout}
        student={student}
        loading={loading}
        route={route}
        go={go}
      />
    );
  }
  return (
    <header className="stx-topbar">
      <div className="stx-brand">
        <span className="stx-brand-tile">💡</span>
        <b>EpiqMinds</b>
        <StxChip>STUDENT</StxChip>
      </div>
      <StxNav placement="top" route={route} go={go}/>
      <StxAccountMenu
        session={session}
        logout={logout}
        student={student}
        loading={loading}
        route={route}
        go={go}
      />
    </header>
  );
};

const StxFrame = ({ session, route, go, logout, children }) => {
  const [savedTheme] = useStudentTheme();
  const sid = session?.studentId || session?.student_id;
  const { data: dashboard, loading } = useApi(
    sid ? `/student/dashboard/${sid}` : "/student/dashboard/0",
    {},
  );
  const professionalPreset = stxProfessional();
  const locked = !!(dashboard.locked || dashboard.student?.access_locked);
  const active = savedTheme !== "classic" && !professionalPreset && !locked;
  const page = route === "/app/student"
    ? "home"
    : route.split("/").filter(Boolean).pop() || "home";

  React.useEffect(() => {
    if (!active) return undefined;
    document.documentElement.dataset.stxActive = "1";
    document.documentElement.dataset.studentTheme = savedTheme;
    return () => {
      delete document.documentElement.dataset.stxActive;
      delete document.documentElement.dataset.studentTheme;
    };
  }, [active, savedTheme]);

  if (!active) return children;

  const currentTheme = STX_THEMES.find((item) => item.key === savedTheme);
  const isSidebar = currentTheme?.layout === "sidebar";

  return (
    <div className="stx" data-stx={savedTheme} data-stx-page={page}>
      <StxContext.Provider value={{ active: true, theme: savedTheme }}>
        {isSidebar && typeof StxpgShell !== "undefined" ? (
          <StxpgShell
            session={session}
            logout={logout}
            student={dashboard.student || {}}
            loading={loading}
            route={route}
            go={go}
          >
            {children}
          </StxpgShell>
        ) : (
          <>
            <StxTopBar
              session={session}
              logout={logout}
              student={dashboard.student || {}}
              loading={loading}
              route={route}
              go={go}
            />
            <main className="stx-body">
              {savedTheme === "ocean" && typeof StxOceanDecorations !== "undefined" && (
                <StxOceanDecorations/>
              )}
              {savedTheme === "dino" && typeof StxDinoDecorations !== "undefined" && (
                <StxDinoDecorations/>
              )}
              {children}
            </main>
            <StxNav placement="dock" route={route} go={go}/>
          </>
        )}
      </StxContext.Provider>
    </div>
  );
};

Object.assign(window, {
  STX_THEMES,
  useStudentTheme,
  StxThemePicker,
  StxNav,
  StxAccountMenu,
  StxContext,
  useStx,
  StxFrame,
  StxCard,
  StxButton,
  StxChip,
  StxPill,
  StxProgress,
  StxDonut,
  StxIconTile,
  StxPageTitle,
  StxEmpty,
  StxSkeleton,
});
