var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
(function() {
  "use strict";
  const SUPABASE_URL = "https://radddwqhqhtkareelypr.supabase.co";
  const SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJhZGRkd3FocWh0a2FyZWVseXByIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzIzMDA4MDgsImV4cCI6MjA4Nzg3NjgwOH0.Juyv8Mx0PXF5PFcg0PZpoxsT_aAF8EebPSj_YFjaP1g";
  const AVATAR_ICONS = [
    '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>',
    '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M18 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM6 4h5v8l-2.5-1.5L6 12V4z"/></svg>',
    '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M9 21c0 .5.4 1 1 1h4c.6 0 1-.5 1-1v-1H9v1zm3-19C8.1 2 5 5.1 5 9c0 2.4 1.2 4.5 3 5.7V17c0 .5.4 1 1 1h6c.6 0 1-.5 1-1v-2.3c1.8-1.3 3-3.4 3-5.7 0-3.9-3.1-7-7-7z"/></svg>',
    '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm0-14c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm0 10c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm0-6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/></svg>',
    '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M19 5h-2V3H7v2H5c-1.1 0-2 .9-2 2v1c0 2.55 1.92 4.63 4.39 4.94c.63 1.5 1.98 2.63 3.61 2.96V19H8v2h8v-2h-3v-3.1c1.63-.33 2.98-1.46 3.61-2.96C19.08 12.63 21 10.55 21 8V7c0-1.1-.9-2-2-2zM5 8V7h2v3.82C5.84 10.4 5 9.3 5 8zm14 0c0 1.3-.84 2.4-2 2.82V7h2v1z"/></svg>',
    '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3L1 9l4 2.18v6L12 21l7-3.82v-6l2-1.09V17h2V9L12 3zm6.82 6L12 12.72 5.18 9 12 5.28 18.82 9zM17 15.99l-5 2.73-5-2.73v-3.72L12 15l5-2.73v3.72z"/></svg>',
    '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg>',
    '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10c.83 0 1.5-.67 1.5-1.5 0-.39-.15-.74-.39-1.01-.23-.26-.38-.61-.38-.99 0-.83.67-1.5 1.5-1.5H16c2.76 0 5-2.24 5-5 0-4.42-4.03-8-9-8zm-5.5 9c-.83 0-1.5-.67-1.5-1.5S5.67 8 6.5 8 8 8.67 8 9.5 7.33 11 6.5 11zm3-4C8.67 7 8 6.33 8 5.5S8.67 4 9.5 4s1.5.67 1.5 1.5S10.33 7 9.5 7zm5 0c-.83 0-1.5-.67-1.5-1.5S13.67 4 14.5 4s1.5.67 1.5 1.5S15.33 7 14.5 7zm3 4c-.83 0-1.5-.67-1.5-1.5S16.67 8 17.5 8s1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/></svg>'
  ];
  const AVATAR_COLORS = ["#1877F2", "#42B72A", "#F25C05", "#8B5CF6", "#EC4899", "#0891B2", "#EAB308", "#64748B"];
  const AVATAR_STORAGE_KEY_PREFIX = "guardrail_avatar_";
  class PopupController {
    constructor() {
      // Views
      __publicField(this, "welcomeView");
      __publicField(this, "createAccountView");
      __publicField(this, "signInView");
      __publicField(this, "dashboardView");
      __publicField(this, "feedbackView");
      // Create Account elements
      __publicField(this, "createAccountForm");
      __publicField(this, "createAccessCodeInput");
      __publicField(this, "createClassroomBadge");
      __publicField(this, "createStudentFields");
      __publicField(this, "createNameInput");
      __publicField(this, "createEmailInput");
      __publicField(this, "createPasswordInput");
      __publicField(this, "createSubmitBtn");
      __publicField(this, "createErrorMessage");
      // Sign In elements
      __publicField(this, "signInForm");
      __publicField(this, "signInEmailInput");
      __publicField(this, "signInPasswordInput");
      __publicField(this, "signInSubmitBtn");
      __publicField(this, "signInErrorMessage");
      // Theme elements
      __publicField(this, "themeToggle");
      __publicField(this, "themeIcon");
      // GuardRAIl disable toggle (replaces refresh button location)
      __publicField(this, "guardrailDisableToggle");
      __publicField(this, "guardrailToggleLabel");
      // Feedback
      __publicField(this, "feedbackBtn");
      __publicField(this, "feedbackForm");
      __publicField(this, "feedbackSubjectInput");
      __publicField(this, "feedbackMessageInput");
      __publicField(this, "feedbackErrorEl");
      __publicField(this, "feedbackSubmitBtn");
      __publicField(this, "lastAuthForDashboard", null);
      // State
      __publicField(this, "validatedClassroom", null);
      __publicField(this, "currentView", "welcome");
      __publicField(this, "isDarkMode", false);
      __publicField(this, "pendingOAuthUserId", null);
      __publicField(this, "currentStudentId", null);
      __publicField(this, "avatarPrefs", null);
      this.welcomeView = document.getElementById("welcome-view");
      this.createAccountView = document.getElementById("create-account-view");
      this.signInView = document.getElementById("sign-in-view");
      this.dashboardView = document.getElementById("dashboard-view");
      this.createAccountForm = document.getElementById("create-account-form");
      this.createAccessCodeInput = document.getElementById("create-access-code");
      this.createClassroomBadge = document.getElementById("create-classroom-name");
      this.createStudentFields = document.getElementById("create-student-fields");
      this.createNameInput = document.getElementById("create-student-name");
      this.createEmailInput = document.getElementById("create-student-email");
      this.createPasswordInput = document.getElementById("create-student-password");
      this.createSubmitBtn = document.getElementById("create-submit-btn");
      this.createErrorMessage = document.getElementById("create-error-message");
      this.signInForm = document.getElementById("sign-in-form");
      this.signInEmailInput = document.getElementById("signin-student-email");
      this.signInPasswordInput = document.getElementById("signin-student-password");
      this.signInSubmitBtn = document.getElementById("signin-submit-btn");
      this.signInErrorMessage = document.getElementById("signin-error-message");
      this.themeToggle = document.getElementById("theme-toggle");
      this.themeIcon = document.getElementById("theme-icon");
      this.guardrailDisableToggle = document.getElementById("guardrail-disable-toggle");
      this.guardrailToggleLabel = document.getElementById("guardrail-toggle-label");
      this.feedbackView = document.getElementById("feedback-view");
      this.feedbackBtn = document.getElementById("feedback-btn");
      this.feedbackForm = document.getElementById("feedback-form");
      this.feedbackSubjectInput = document.getElementById("feedback-subject");
      this.feedbackMessageInput = document.getElementById("feedback-message");
      this.feedbackErrorEl = document.getElementById("feedback-error");
      this.feedbackSubmitBtn = document.getElementById("feedback-submit-btn");
      this.init();
    }
    async init() {
      await this.initTheme();
      const auth = await this.sendMessage({ type: "GET_AUTH_STATUS" });
      if (auth.isAuthenticated) {
        this.showDashboard(auth);
      } else {
        this.showWelcome();
      }
      this.attachEventListeners();
    }
    async initTheme() {
      try {
        const storage = await chrome.storage.sync.get(["guardrail_theme"]);
        this.isDarkMode = storage.guardrail_theme === "dark";
      } catch {
        this.isDarkMode = false;
      }
      this.applyTheme();
    }
    applyTheme() {
      if (this.isDarkMode) {
        document.body.setAttribute("data-theme", "dark");
        this.themeIcon.textContent = "☾";
      } else {
        document.body.removeAttribute("data-theme");
        this.themeIcon.textContent = "☀";
      }
    }
    async toggleTheme() {
      this.isDarkMode = !this.isDarkMode;
      this.applyTheme();
      try {
        await chrome.storage.sync.set({ guardrail_theme: this.isDarkMode ? "dark" : "light" });
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
          if (tabs[0]?.id) {
            chrome.tabs.sendMessage(tabs[0].id, { type: "THEME_CHANGED", theme: this.isDarkMode ? "dark" : "light" });
          }
        });
      } catch {
      }
    }
    attachEventListeners() {
      this.themeToggle?.addEventListener("click", () => this.toggleTheme());
      document.getElementById("create-account-btn")?.addEventListener("click", () => this.showCreateAccount());
      document.getElementById("sign-in-btn")?.addEventListener("click", () => this.showSignIn());
      document.getElementById("create-back-btn")?.addEventListener("click", () => this.showWelcome());
      document.getElementById("signin-back-btn")?.addEventListener("click", () => this.showWelcome());
      let createDebounceTimer;
      this.createAccessCodeInput.addEventListener("input", (e) => {
        const target = e.target;
        target.value = target.value.toUpperCase();
        clearTimeout(createDebounceTimer);
        createDebounceTimer = window.setTimeout(() => this.validateCreateAccessCode(), 500);
      });
      this.createNameInput.addEventListener("input", () => this.updateCreateButton());
      this.createEmailInput.addEventListener("input", () => this.updateCreateButton());
      this.createPasswordInput.addEventListener("input", () => this.updateCreateButton());
      this.createAccountForm.addEventListener("submit", (e) => {
        if (this.pendingOAuthUserId) {
          e.preventDefault();
          this.handleGoogleAccountCreation(this.pendingOAuthUserId);
        } else {
          this.handleCreateAccount(e);
        }
      });
      this.signInEmailInput.addEventListener("input", () => this.updateSignInButton());
      this.signInPasswordInput.addEventListener("input", () => this.updateSignInButton());
      this.signInForm.addEventListener("submit", (e) => this.handleSignIn(e));
      this.guardrailDisableToggle?.addEventListener("click", () => this.toggleGuardrailDisabled());
      this.feedbackBtn?.addEventListener("click", () => this.showFeedbackView());
      document.getElementById("feedback-back-btn")?.addEventListener("click", () => this.backFromFeedback());
      this.feedbackForm?.addEventListener("submit", (e) => this.handleFeedbackSubmit(e));
      document.getElementById("signout-btn")?.addEventListener("click", () => this.signOut());
      document.getElementById("user-avatar-btn")?.addEventListener("click", () => this.openAvatarModal());
      document.getElementById("avatar-modal-backdrop")?.addEventListener("click", () => this.closeAvatarModal());
      document.getElementById("avatar-modal-done")?.addEventListener("click", () => this.saveAvatarAndClose());
      document.querySelectorAll(".avatar-icon-opt").forEach((el) => {
        el.addEventListener("click", () => this.selectAvatarIcon(Number(el.dataset.icon)));
      });
      document.querySelectorAll(".avatar-color-opt").forEach((el) => {
        el.addEventListener("click", () => this.selectAvatarColor(Number(el.dataset.color)));
      });
      document.getElementById("teacher-dashboard-btn")?.addEventListener("click", () => {
        chrome.tabs.create({ url: chrome.runtime.getURL("dashboard.html") });
      });
    }
    showWelcome() {
      this.hideAllViews();
      this.welcomeView.classList.remove("hidden");
      this.currentView = "welcome";
      this.validatedClassroom = null;
      this.guardrailDisableToggle?.classList.add("hidden");
      this.feedbackBtn?.classList.add("hidden");
    }
    showCreateAccount() {
      this.hideAllViews();
      this.createAccountView.classList.remove("hidden");
      this.currentView = "create";
      this.guardrailDisableToggle?.classList.add("hidden");
      this.feedbackBtn?.classList.add("hidden");
      this.createAccessCodeInput.focus();
    }
    showSignIn() {
      this.hideAllViews();
      this.signInView.classList.remove("hidden");
      this.currentView = "signin";
      this.guardrailDisableToggle?.classList.add("hidden");
      this.feedbackBtn?.classList.add("hidden");
      this.validatedClassroom = null;
      this.signInEmailInput.focus();
      this.updateSignInButton();
    }
    hideAllViews() {
      this.welcomeView.classList.add("hidden");
      this.createAccountView.classList.add("hidden");
      this.signInView.classList.add("hidden");
      this.dashboardView.classList.add("hidden");
      this.feedbackView.classList.add("hidden");
    }
    async showDashboard(auth) {
      this.lastAuthForDashboard = auth;
      this.hideAllViews();
      this.dashboardView.classList.remove("hidden");
      this.currentView = "dashboard";
      this.currentStudentId = auth.studentId || null;
      this.guardrailDisableToggle?.classList.remove("hidden");
      this.feedbackBtn?.classList.remove("hidden");
      document.getElementById("user-name").textContent = auth.studentName || "Student";
      const defaultLetter = (auth.studentName || "S")[0].toUpperCase();
      this.avatarPrefs = await this.getAvatarPrefs(this.currentStudentId);
      this.applyAvatar(document.getElementById("user-avatar"), this.avatarPrefs, defaultLetter);
      const schoolPillText = document.getElementById("user-school-pill-text");
      if (schoolPillText) schoolPillText.textContent = "School name";
      await this.refreshGuardrailToggleState();
      await this.refreshStats();
    }
    async refreshGuardrailToggleState() {
      try {
        const storage = await chrome.storage.sync.get(["guardrail_disabled"]);
        const disabled = storage.guardrail_disabled === true;
        const state = disabled ? "off" : "on";
        this.guardrailDisableToggle?.setAttribute("aria-checked", disabled ? "false" : "true");
        this.guardrailDisableToggle?.setAttribute("data-state", state);
        if (this.guardrailToggleLabel) this.guardrailToggleLabel.textContent = state === "on" ? "On" : "Off";
        this.guardrailDisableToggle?.setAttribute("title", disabled ? "Turn GuardRAIl on" : "Turn off to use AI without prompt guidance");
      } catch {
        this.guardrailDisableToggle?.setAttribute("aria-checked", "true");
        this.guardrailDisableToggle?.setAttribute("data-state", "on");
        if (this.guardrailToggleLabel) this.guardrailToggleLabel.textContent = "On";
      }
    }
    async toggleGuardrailDisabled() {
      try {
        const storage = await chrome.storage.sync.get(["guardrail_disabled"]);
        const currentlyDisabled = storage.guardrail_disabled === true;
        const newDisabled = !currentlyDisabled;
        await chrome.storage.sync.set({ guardrail_disabled: newDisabled });
        const state = newDisabled ? "off" : "on";
        this.guardrailDisableToggle?.setAttribute("aria-checked", newDisabled ? "false" : "true");
        this.guardrailDisableToggle?.setAttribute("data-state", state);
        if (this.guardrailToggleLabel) this.guardrailToggleLabel.textContent = state === "on" ? "On" : "Off";
        this.guardrailDisableToggle?.setAttribute("title", newDisabled ? "Turn GuardRAIl on" : "Turn off to use AI without prompt guidance");
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
          if (tabs[0]?.id) {
            chrome.tabs.sendMessage(tabs[0].id, { type: "GUARDRail_DISABLED_CHANGED", disabled: newDisabled }).catch(() => {
            });
          }
        });
      } catch (e) {
        console.error("GuardRAIl: Failed to toggle disabled state", e);
      }
    }
    showFeedbackView() {
      this.hideAllViews();
      this.feedbackView.classList.remove("hidden");
      this.currentView = "feedback";
      this.feedbackErrorEl.classList.add("hidden");
      this.feedbackSubjectInput.value = "";
      this.feedbackMessageInput.value = "";
    }
    backFromFeedback() {
      if (this.lastAuthForDashboard) {
        this.showDashboard(this.lastAuthForDashboard);
      } else {
        this.sendMessage({ type: "GET_AUTH_STATUS" }).then((auth) => {
          this.showDashboard(auth);
        });
      }
    }
    async handleFeedbackSubmit(e) {
      e.preventDefault();
      const subject = this.feedbackSubjectInput.value.trim();
      const message = this.feedbackMessageInput.value.trim();
      if (!message) {
        this.feedbackErrorEl.textContent = "Please enter your feedback.";
        this.feedbackErrorEl.classList.remove("hidden");
        return;
      }
      this.feedbackErrorEl.classList.add("hidden");
      this.feedbackSubmitBtn.disabled = true;
      this.feedbackSubmitBtn.textContent = "Sending…";
      try {
        await this.sendMessage({
          type: "SUBMIT_FEEDBACK",
          source: "student_popup",
          subject,
          message,
          studentId: this.currentStudentId ?? void 0
        });
        this.feedbackSubjectInput.value = "";
        this.feedbackMessageInput.value = "";
        this.backFromFeedback();
      } catch (err) {
        this.feedbackErrorEl.textContent = err.message || "Failed to send feedback.";
        this.feedbackErrorEl.classList.remove("hidden");
      } finally {
        this.feedbackSubmitBtn.disabled = false;
        this.feedbackSubmitBtn.textContent = "Send feedback";
      }
    }
    async getAvatarPrefs(studentId) {
      if (!studentId) return null;
      try {
        const key = AVATAR_STORAGE_KEY_PREFIX + studentId;
        const out = await chrome.storage.local.get([key]);
        const raw = out[key];
        if (raw && typeof raw.iconIndex === "number" && typeof raw.colorIndex === "number") {
          if (raw.iconIndex >= 0 && raw.iconIndex < 8 && raw.colorIndex >= 0 && raw.colorIndex < 8) {
            return { iconIndex: raw.iconIndex, colorIndex: raw.colorIndex };
          }
        }
      } catch (_) {
      }
      return null;
    }
    async setAvatarPrefs(studentId, iconIndex, colorIndex) {
      if (!studentId) return;
      await chrome.storage.local.set({
        [AVATAR_STORAGE_KEY_PREFIX + studentId]: { iconIndex, colorIndex }
      });
    }
    applyAvatar(el, prefs, defaultLetter) {
      if (prefs) {
        el.innerHTML = AVATAR_ICONS[prefs.iconIndex];
        el.style.background = AVATAR_COLORS[prefs.colorIndex];
        el.style.color = "white";
        el.classList.remove("avatar-emoji");
        el.classList.add("avatar-icon-svg");
      } else {
        el.textContent = defaultLetter;
        el.style.background = "";
        el.style.color = "";
        el.classList.remove("avatar-icon-svg");
        el.classList.remove("avatar-emoji");
      }
    }
    openAvatarModal() {
      const modal = document.getElementById("avatar-modal");
      if (!modal) return;
      const iconIndex = this.avatarPrefs?.iconIndex ?? 0;
      const colorIndex = this.avatarPrefs?.colorIndex ?? 0;
      document.querySelectorAll(".avatar-icon-opt").forEach((el, i) => {
        el.classList.toggle("selected", i === iconIndex);
      });
      document.querySelectorAll(".avatar-color-opt").forEach((el, i) => {
        el.classList.toggle("selected", i === colorIndex);
      });
      modal.classList.remove("hidden");
    }
    closeAvatarModal() {
      document.getElementById("avatar-modal")?.classList.add("hidden");
    }
    selectAvatarIcon(iconIndex) {
      document.querySelectorAll(".avatar-icon-opt").forEach((el, i) => {
        el.classList.toggle("selected", i === iconIndex);
      });
    }
    selectAvatarColor(colorIndex) {
      document.querySelectorAll(".avatar-color-opt").forEach((el, i) => {
        el.classList.toggle("selected", i === colorIndex);
      });
    }
    async saveAvatarAndClose() {
      const iconOpt = document.querySelector(".avatar-icon-opt.selected");
      const colorOpt = document.querySelector(".avatar-color-opt.selected");
      const iconIndex = iconOpt != null ? Number(iconOpt.dataset.icon) : 0;
      const colorIndex = colorOpt != null ? Number(colorOpt.dataset.color) : 0;
      if (this.currentStudentId != null) {
        await this.setAvatarPrefs(this.currentStudentId, iconIndex, colorIndex);
        this.avatarPrefs = { iconIndex, colorIndex };
        const avatarEl = document.getElementById("user-avatar");
        const nameEl = document.getElementById("user-name");
        const defaultLetter = nameEl ? (nameEl.textContent || "S")[0] : "S";
        if (avatarEl) this.applyAvatar(avatarEl, this.avatarPrefs, defaultLetter);
      }
      this.closeAvatarModal();
    }
    async validateCreateAccessCode() {
      const code = this.createAccessCodeInput.value.trim().toUpperCase();
      if (code.length < 4) {
        this.createClassroomBadge.classList.add("hidden");
        this.createStudentFields.classList.add("hidden");
        this.validatedClassroom = null;
        this.updateCreateButton();
        return;
      }
      try {
        const result = await this.sendMessage({
          type: "VALIDATE_ACCESS_CODE",
          accessCode: code
        });
        if (result.valid) {
          this.validatedClassroom = { id: result.classroomId, name: result.className };
          this.createClassroomBadge.textContent = `✓ ${result.className}`;
          this.createClassroomBadge.classList.remove("hidden");
          this.createStudentFields.classList.remove("hidden");
        } else {
          this.createClassroomBadge.classList.add("hidden");
          this.createStudentFields.classList.add("hidden");
          this.validatedClassroom = null;
        }
      } catch {
        this.createClassroomBadge.classList.add("hidden");
        this.createStudentFields.classList.add("hidden");
        this.validatedClassroom = null;
      }
      this.updateCreateButton();
    }
    updateCreateButton() {
      const hasValidCode = this.validatedClassroom !== null;
      const hasName = this.createNameInput.value.trim().length >= 2;
      const hasEmail = this.createEmailInput.value.includes("@");
      const hasPassword = this.createPasswordInput.value.trim().length >= 6;
      this.createSubmitBtn.disabled = !(hasValidCode && hasName && hasEmail && hasPassword);
    }
    updateSignInButton() {
      const hasEmail = this.signInEmailInput.value.includes("@");
      const hasPassword = this.signInPasswordInput.value.trim().length >= 6;
      this.signInSubmitBtn.disabled = !(hasEmail && hasPassword);
    }
    async handleCreateAccount(e) {
      e.preventDefault();
      if (!this.validatedClassroom) return;
      const name = this.createNameInput.value.trim();
      const email = this.createEmailInput.value.trim();
      const password = this.createPasswordInput.value.trim();
      const accessCode = this.createAccessCodeInput.value.trim().toUpperCase();
      this.createSubmitBtn.disabled = true;
      this.createErrorMessage.classList.add("hidden");
      try {
        this.createSubmitBtn.textContent = "Creating account...";
        await this.sendMessage({
          type: "CREATE_STUDENT",
          name,
          email,
          password,
          accessCode
        });
        const auth = await this.sendMessage({ type: "GET_AUTH_STATUS" });
        this.showDashboard(auth);
      } catch (error) {
        this.createErrorMessage.textContent = error.message || "Failed to create account";
        this.createErrorMessage.classList.remove("hidden");
        this.createSubmitBtn.disabled = false;
        this.createSubmitBtn.textContent = "Create Account";
      }
    }
    async handleSignIn(e) {
      e.preventDefault();
      const email = this.signInEmailInput.value.trim();
      const password = this.signInPasswordInput.value.trim();
      if (!email || !email.includes("@")) {
        this.signInErrorMessage.textContent = "Please enter a valid email address";
        this.signInErrorMessage.classList.remove("hidden");
        return;
      }
      if (!password || password.length < 6) {
        this.signInErrorMessage.textContent = "Password must be at least 6 characters";
        this.signInErrorMessage.classList.remove("hidden");
        return;
      }
      this.signInSubmitBtn.disabled = true;
      this.signInErrorMessage.classList.add("hidden");
      try {
        this.signInSubmitBtn.textContent = "Signing in...";
        await this.sendMessage({
          type: "LOGIN_STUDENT",
          email,
          password,
          accessCode: ""
          // Empty access code - backend will look up from student record
        });
        const auth = await this.sendMessage({ type: "GET_AUTH_STATUS" });
        this.showDashboard(auth);
      } catch (error) {
        this.signInErrorMessage.textContent = error.message || "Failed to sign in";
        this.signInErrorMessage.classList.remove("hidden");
        this.signInSubmitBtn.disabled = false;
        this.signInSubmitBtn.textContent = "Sign In";
      }
    }
    async refreshStats() {
      try {
        console.log("GuardRAIl: Fetching stats...");
        const result = await this.sendMessage({ type: "GET_STATS" });
        console.log("GuardRAIl: Stats response:", result);
        console.log("GuardRAIl: Stats response type:", typeof result);
        console.log("GuardRAIl: Stats response keys:", result ? Object.keys(result) : "null");
        if (!result) {
          console.error("GuardRAIl: No result returned from GET_STATS");
          throw new Error("No response from server");
        }
        if (!result.stats) {
          console.error("GuardRAIl: Invalid stats response structure:", result);
          console.error("GuardRAIl: Full result:", JSON.stringify(result, null, 2));
          throw new Error("Invalid response structure - missing stats");
        }
        const stats = result.stats;
        console.log("GuardRAIl: Parsed stats:", stats);
        console.log("GuardRAIl: learningFocus:", stats.learningFocus, typeof stats.learningFocus);
        console.log("GuardRAIl: streakDays:", stats.streakDays, typeof stats.streakDays);
        const focusElement = document.getElementById("stat-learning-focus");
        const progressElement = document.getElementById("stat-focus-progress");
        const focusValue = typeof stats.learningFocus === "number" ? stats.learningFocus : 0;
        if (focusElement) {
          focusElement.textContent = `${focusValue}`;
        }
        if (progressElement) {
          progressElement.style.width = `${focusValue}%`;
          if (focusValue >= 70) {
            progressElement.style.background = "linear-gradient(90deg, #22c55e, #4ade80)";
          } else if (focusValue >= 40) {
            progressElement.style.background = "linear-gradient(90deg, #eab308, #facc15)";
          } else {
            progressElement.style.background = "linear-gradient(90deg, #dc2626, #f87171)";
          }
        }
        const streakElement = document.getElementById("stat-streak");
        const streakIconEl = document.getElementById("stat-icon-streak");
        if (streakElement) {
          const streakValue = typeof stats.streakDays === "number" ? stats.streakDays : 0;
          streakElement.textContent = String(streakValue);
          if (streakIconEl) streakIconEl.setAttribute("data-streak", String(Math.min(streakValue, 20)));
        }
        const listEl = document.getElementById("connected-classrooms-list");
        if (listEl) {
          const raw = result.student?.classroom;
          const classrooms = Array.isArray(raw) ? raw : raw ? [raw] : [];
          const defaultColor = "#1877F2";
          const classIconSvg = '<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 3L1 9l11 6 9-4.91V17h2V9l-12-6zM5 13.18v4L12 21l7-3.82v-4L12 17l-7-3.82z" fill="currentColor"/></svg>';
          listEl.innerHTML = "";
          for (const c of classrooms) {
            const name = c && c.class_name || "Classroom";
            const color = c && c.color || defaultColor;
            const pill = document.createElement("span");
            pill.className = "connected-classroom-pill";
            pill.style.background = color;
            const iconSpan = document.createElement("span");
            iconSpan.className = "connected-classroom-icon";
            iconSpan.innerHTML = classIconSvg;
            pill.appendChild(iconSpan);
            pill.appendChild(document.createTextNode(name));
            listEl.appendChild(pill);
          }
        }
      } catch (error) {
        console.error("GuardRAIl: Error loading stats:", error);
        console.error("GuardRAIl: Error details:", {
          message: error instanceof Error ? error.message : String(error),
          stack: error instanceof Error ? error.stack : void 0
        });
        const focusElement = document.getElementById("stat-learning-focus");
        const progressElement = document.getElementById("stat-focus-progress");
        const streakElement = document.getElementById("stat-streak");
        const streakIconEl = document.getElementById("stat-icon-streak");
        if (focusElement) focusElement.textContent = "0";
        if (progressElement) {
          progressElement.style.width = "0%";
          progressElement.style.background = "linear-gradient(90deg, #dc2626, #f87171)";
        }
        if (streakElement) streakElement.textContent = "0";
        if (streakIconEl) streakIconEl.setAttribute("data-streak", "0");
        const listEl = document.getElementById("connected-classrooms-list");
        if (listEl) listEl.innerHTML = "";
      }
    }
    async handleGoogleSignIn() {
      try {
        const { createClient } = await import("https://esm.sh/@supabase/supabase-js@2");
        const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
        const { data, error } = await supabase.auth.signInWithOAuth({
          provider: "google",
          options: {
            redirectTo: chrome.identity.getRedirectURL(),
            queryParams: {
              access_type: "offline",
              prompt: "consent"
            }
          }
        });
        if (error) {
          console.error("Google OAuth error:", error);
          this.showError("Failed to start Google sign-in. Please try again.");
          return;
        }
        if (data.url) {
          chrome.identity.launchWebAuthFlow(
            {
              url: data.url,
              interactive: true
            },
            async (callbackUrl) => {
              if (chrome.runtime.lastError) {
                console.error("OAuth flow error:", chrome.runtime.lastError);
                this.showError("Google sign-in was cancelled or failed.");
                return;
              }
              if (!callbackUrl) {
                this.showError("Google sign-in failed. Please try again.");
                return;
              }
              const url = new URL(callbackUrl);
              const code = url.searchParams.get("code");
              const error2 = url.searchParams.get("error");
              if (error2) {
                this.showError("Google sign-in failed. Please try again.");
                return;
              }
              if (code) {
                const { data: sessionData, error: sessionError } = await supabase.auth.exchangeCodeForSession(code);
                if (sessionError || !sessionData.session) {
                  console.error("Session exchange error:", sessionError);
                  this.showError("Failed to complete sign-in. Please try again.");
                  return;
                }
                await this.showGoogleAccessCodeInput(sessionData.session.user.id, sessionData.session.user.email || "");
              }
            }
          );
        }
      } catch (error) {
        console.error("Google sign-in error:", error);
        this.showError("An error occurred. Please try again.");
      }
    }
    async showGoogleAccessCodeInput(authUserId, email) {
      this.pendingOAuthUserId = authUserId;
      this.showCreateAccount();
      const passwordGroup = this.createPasswordInput.closest(".form-group");
      if (passwordGroup) {
        passwordGroup.style.display = "none";
      }
      this.createEmailInput.value = email;
      this.createEmailInput.disabled = true;
    }
    async handleGoogleAccountCreation(authUserId) {
      if (!this.validatedClassroom) {
        this.showError("Please enter a valid access code.");
        return;
      }
      const name = this.createNameInput.value.trim() || this.createEmailInput.value.split("@")[0];
      const accessCode = this.createAccessCodeInput.value.trim().toUpperCase();
      if (!accessCode) {
        this.showError("Please enter an access code.");
        return;
      }
      try {
        this.createSubmitBtn.disabled = true;
        this.createSubmitBtn.textContent = "Creating...";
        const result = await this.sendMessage({
          type: "CREATE_STUDENT_FROM_OAUTH",
          authUserId,
          accessCode,
          name
        });
        if (result.error) {
          this.showError(result.error);
          this.createSubmitBtn.disabled = false;
          this.createSubmitBtn.textContent = "Create Account";
          return;
        }
        if (result.studentId) {
          this.pendingOAuthUserId = null;
          await chrome.storage.sync.set({
            guardrail_student_id: result.studentId,
            guardrail_auth_user_id: authUserId,
            guardrail_student_name: result.name || name,
            guardrail_student_email: this.createEmailInput.value,
            guardrail_classroom_id: result.classroomId,
            guardrail_classroom_name: result.className,
            guardrail_classroom_access_code: accessCode
          });
          const auth = {
            isAuthenticated: true,
            studentId: result.studentId,
            studentName: result.name || name,
            studentEmail: this.createEmailInput.value,
            classroomId: result.classroomId,
            classroomName: result.className
          };
          await this.showDashboard(auth);
        }
      } catch (error) {
        console.error("Create student from OAuth error:", error);
        this.showError(error.message || "Failed to create account. Please try again.");
        this.createSubmitBtn.disabled = false;
        this.createSubmitBtn.textContent = "Create Account";
      }
    }
    showError(message) {
      if (this.currentView === "create") {
        this.createErrorMessage.textContent = message;
        this.createErrorMessage.classList.remove("hidden");
      } else if (this.currentView === "signin") {
        this.signInErrorMessage.textContent = message;
        this.signInErrorMessage.classList.remove("hidden");
      }
    }
    async signOut() {
      await this.sendMessage({ type: "SIGN_OUT" });
      this.validatedClassroom = null;
      this.createAccessCodeInput.value = "";
      this.createNameInput.value = "";
      this.createEmailInput.value = "";
      this.createPasswordInput.value = "";
      this.signInEmailInput.value = "";
      this.signInPasswordInput.value = "";
      this.showWelcome();
    }
    sendMessage(message) {
      return new Promise((resolve, reject) => {
        chrome.runtime.sendMessage(message, (response) => {
          if (chrome.runtime.lastError) {
            reject(new Error(chrome.runtime.lastError.message));
          } else if (response?.error) {
            reject(new Error(response.error));
          } else {
            resolve(response || {});
          }
        });
      });
    }
  }
  document.addEventListener("DOMContentLoaded", () => {
    new PopupController();
  });
})();
