(() => {
  const build = "2026-09-10.6";
  const routes = {
    home: "/teach/control/stream/view/id/935737536",
    notifications: "/notifications/notifications/all",
    profile: "/user/my/profile",
    logout: "/user/my/logout",
    support: "https://pharmsim.ru/#question",
  };
  const widgets = {
    support: { id: "1636423", title: "Форма поддержки" },
  };
  const normalize = (value) => (value || "").replace(/\s+/g, " ").trim();
  const setDarkChrome = () => {
    document.documentElement.style.setProperty("background-color", "#05080d", "important");
    document.documentElement.style.setProperty("overscroll-behavior-y", "none", "important");
    document.body.style.setProperty("background-color", "#05080d", "important");
    document.body.style.setProperty("overscroll-behavior-y", "none", "important");
    const menu = document.querySelector("#gcAccountUserMenu");
    menu?.classList.remove("ps-menu-light");
    menu?.classList.add("ps-menu-dark");
  };

  const setLightChrome = () => {
    document.documentElement.style.setProperty("background-color", "#f5f6f8", "important");
    document.documentElement.style.setProperty("overscroll-behavior-y", "none", "important");
    document.body.style.setProperty("background-color", "#f5f6f8", "important");
    document.body.style.setProperty("overscroll-behavior-y", "none", "important");
    const menu = document.querySelector("#gcAccountUserMenu");
    menu?.classList.remove("ps-menu-dark");
    menu?.classList.add("ps-menu-light");
  };

  const menuSymbol = (name) => {
    const icon = document.createElement("span");
    icon.className = "ps-menu-icon";
    icon.setAttribute("aria-hidden", "true");
    icon.textContent = name;
    return icon;
  };

  const menuItem = (className, href, icon, label) => {
    const item = document.createElement("a");
    item.className = `ps-menu-btn ${className}`;
    item.href = href;
    item.setAttribute("aria-label", label);
    item.dataset.psTip = label;
    item.append(menuSymbol(icon));
    return item;
  };

  const setNotificationMenuState = (item, unread) => {
    const icon = item?.querySelector(".ps-menu-icon");
    if (!item || !icon) return;
    icon.textContent = unread ? "notifications_unread" : "notifications";
    item.classList.toggle("has-unread", unread);
    const label = unread ? "Уведомления, есть непрочитанные" : "Уведомления";
    item.setAttribute("aria-label", label);
    item.dataset.psTip = label;
  };

  const refreshProfileNotificationState = async (item) => {
    try {
      const response = await fetch(routes.notifications, { credentials: "same-origin", cache: "no-store" });
      if (!response.ok) return;
      const page = new DOMParser().parseFromString(await response.text(), "text/html");
      setNotificationMenuState(item, Boolean(page.querySelector(".notification-group:not(.notification-status-viewed)")));
    } catch {}
  };

  const createProfileSupportLayer = () => {
    if (document.querySelector(".ps-support-layer")) return;
    const layer = document.createElement("div");
    layer.className = "ps-support-layer";
    layer.setAttribute("role", "dialog");
    layer.setAttribute("aria-modal", "true");
    layer.setAttribute("aria-label", widgets.support.title);
    layer.setAttribute("aria-hidden", "true");
    const dialog = document.createElement("div");
    dialog.className = "ps-support-dialog";
    const close = document.createElement("button");
    close.type = "button";
    close.className = "ps-support-close";
    close.setAttribute("aria-label", "Закрыть форму поддержки");
    const frame = document.createElement("iframe");
    frame.className = "ps-support-frame";
    frame.title = widgets.support.title;
    frame.loading = "eager";
    frame.setAttribute("scrolling", "yes");
    frame.addEventListener("load", () => {
      try {
        const frameDocument = frame.contentDocument;
        if (!frameDocument) return;
        let style = frameDocument.querySelector("#ps-widget-scroll-style");
        if (!style) {
          style = frameDocument.createElement("style");
          style.id = "ps-widget-scroll-style";
          style.textContent = "html{overflow-x:hidden!important;overflow-y:auto!important;overscroll-behavior-y:none;scrollbar-gutter:stable;scrollbar-width:thin;scrollbar-color:#68707e #05080d;background:#05080d!important;color-scheme:dark}body{min-height:100%;overflow:visible!important;padding-bottom:32px!important;box-sizing:border-box;background:#05080d!important}html::-webkit-scrollbar{width:10px}html::-webkit-scrollbar-track{background:#05080d}html::-webkit-scrollbar-thumb{border:2px solid #05080d;border-radius:100px;background:#68707e}";
          frameDocument.head?.append(style);
        }
        frameDocument.documentElement.style.setProperty("background-color", "#05080d", "important");
        frameDocument.documentElement.style.setProperty("overflow-x", "hidden", "important");
        frameDocument.documentElement.style.setProperty("overflow-y", "auto", "important");
        frameDocument.body?.style.setProperty("background-color", "#05080d", "important");
        frameDocument.body?.style.setProperty("overflow", "visible", "important");
      } catch {}
    });
    dialog.append(close, frame);
    layer.append(dialog);
    document.body.append(layer);

    let activeTrigger = null;
    const hide = () => {
      layer.classList.remove("is-open");
      layer.setAttribute("aria-hidden", "true");
      activeTrigger?.classList.remove("is-active");
      document.body.classList.remove("ps-support-open");
      activeTrigger?.focus();
      activeTrigger = null;
    };
    document.addEventListener("click", (event) => {
      const trigger = event.target.closest("[data-ps-widget-id]");
      if (!trigger) return;
      const widgetId = trigger.dataset.psWidgetId?.trim();
      if (!/^\d+$/.test(widgetId || "")) return;
      event.preventDefault();
      if (frame.dataset.psWidgetId !== widgetId) {
        frame.src = `${location.origin}/pl/lite/widget/widget?&id=${widgetId}&ref=&loc=${encodeURIComponent(location.href)}`;
        frame.dataset.psWidgetId = widgetId;
      }
      activeTrigger = trigger;
      layer.classList.add("is-open");
      layer.setAttribute("aria-hidden", "false");
      trigger.classList.add("is-active");
      document.body.classList.add("ps-support-open");
      close.focus();
    });
    close.addEventListener("click", hide);
    layer.addEventListener("click", (event) => {
      if (event.target === layer) hide();
    });
    document.addEventListener("keydown", (event) => {
      if (event.key === "Escape" && layer.classList.contains("is-open")) hide();
    });
  };

  const activateProfileMenu = () => {
    const host = document.querySelector("#gcAccountUserMenu.ps-menu-ready");
    if (!host) return;
    host.querySelectorAll("[aria-current='page'], .is-active").forEach((item) => {
      item.classList.remove("is-active");
      item.removeAttribute("aria-current");
    });
    const profile = host.querySelector(".ps-menu-profile");
    profile?.classList.add("is-active");
    profile?.setAttribute("aria-current", "page");
  };

  const ensureProfileMenu = (main) => {
    const host = document.querySelector("#gcAccountUserMenu");
    const bar = host?.querySelector(".gc-account-leftbar");
    if (!host || !bar) return;
    if (host.dataset.psMenuReady === "true") {
      activateProfileMenu();
      return;
    }
    const sourceAvatar = bar.querySelector(".menu-item-profile img");
    const avatarSrc = sourceAvatar?.src || "";
    const defaultAvatar = !avatarSrc || /default_(?:comment_)?profile/i.test(avatarSrc) || sourceAvatar?.classList.contains("user-default-profile-image");

    const nav = document.createElement("nav");
    nav.className = "ps-menu";
    nav.setAttribute("aria-label", "Основное меню");
    const profile = document.createElement("a");
    profile.className = "ps-menu-profile is-active";
    profile.href = routes.profile;
    profile.dataset.psTip = "Профиль";
    profile.setAttribute("aria-label", "Профиль");
    profile.setAttribute("aria-current", "page");
    if (defaultAvatar) profile.append(menuSymbol("person"));
    else {
      const image = document.createElement("img");
      image.src = avatarSrc;
      image.alt = "";
      profile.append(image);
    }

    const primary = document.createElement("div");
    primary.className = "ps-menu-group ps-menu-main";
    const home = menuItem("ps-menu-home", routes.home, "school", "Обучение");
    const notifications = menuItem("ps-menu-notifications", routes.notifications, "notifications", "Уведомления");
    const support = menuItem("ps-menu-support", routes.support, "support_agent", "Поддержка");
    support.dataset.psWidgetId = widgets.support.id;
    support.dataset.psWidgetTitle = widgets.support.title;
    primary.append(home, notifications, support);

    const logoutGroup = document.createElement("div");
    logoutGroup.className = "ps-menu-group ps-menu-logout";
    logoutGroup.append(menuItem("ps-menu-logout-btn", routes.logout, "logout", "Выйти"));
    nav.append(profile, primary, logoutGroup);
    bar.replaceChildren(nav);
    host.classList.add("ps-menu-ready", "ps-menu-light");
    host.dataset.psMenuReady = "true";
    host.dataset.psMenuBuild = `${build}-profile`;
    document.body.classList.add("ps-menu-installed");
    createProfileSupportLayer();
    refreshProfileNotificationState(notifications);
    main.classList.add("with-left-menu");
  };

  const insertSectionTitle = (container, text) => {
    if (!container || container.querySelector(":scope > .ps-profile-section-title")) return;
    const title = document.createElement("h2");
    title.className = "ps-profile-section-title";
    title.textContent = text;
    container.prepend(title);
  };

  const decorateProfileForm = (form, { managePassword = false } = {}) => {
    if (!form) return;
    const account = [...form.querySelectorAll(".row")].find((row) =>
      row.querySelector(".dotted-link, .change-password-form") || /e-mail/i.test(normalize(row.textContent))
    );
    account?.classList.add("ps-profile-account");
    const columns = form.querySelectorAll(".user-data > .col-md-6");
    columns.forEach((column, index) => {
      column.classList.add("ps-profile-section");
      insertSectionTitle(column, index === 0 ? "Личные данные" : "Контакты и уведомления");
    });
    const about = form.querySelector("textarea[name='user_content']")?.parentElement;
    if (about) {
      about.classList.add("ps-profile-about");
      insertSectionTitle(about, "О себе");
    }
    const password = form.querySelector(".change-password-form");
    const passwordLink = form.querySelector(".dotted-link");
    if (password && passwordLink) {
      password.id ||= "ps-profile-password";
      passwordLink.href = `#${password.id}`;
      passwordLink.setAttribute("aria-controls", password.id);
      const syncExpanded = () => {
        const hidden = password.hidden || password.style.display === "none" || getComputedStyle(password).display === "none";
        passwordLink.setAttribute("aria-expanded", String(!hidden));
      };
      syncExpanded();
      if (managePassword && passwordLink.dataset.psPasswordToggle !== "true") {
        passwordLink.dataset.psPasswordToggle = "true";
        passwordLink.addEventListener("click", (event) => {
          event.preventDefault();
          const willOpen = password.hidden || password.style.display === "none" || getComputedStyle(password).display === "none";
          password.hidden = false;
          password.style.display = willOpen ? "block" : "none";
          syncExpanded();
          if (willOpen) password.querySelector("input")?.focus();
        });
      } else if (!managePassword) {
        passwordLink.addEventListener("click", () => window.setTimeout(syncExpanded, 0));
      }
    }
  };

  const createProfileLayer = () => {
    if (document.querySelector(".ps-profile-layer")) return;

    const layer = document.createElement("section");
    layer.className = "ps-profile-layer";
    layer.setAttribute("role", "dialog");
    layer.setAttribute("aria-modal", "true");
    layer.setAttribute("aria-labelledby", "ps-profile-panel-title");
    layer.setAttribute("aria-hidden", "true");
    layer.innerHTML = `
      <div class="ps-profile-panel">
        <header class="ps-profile-panel-header">
          <h1 id="ps-profile-panel-title">Мой профиль</h1>
          <button class="ps-profile-panel-close" type="button" aria-label="Закрыть профиль">
            <span aria-hidden="true">close</span>
          </button>
        </header>
        <nav class="ps-profile-panel-nav" aria-label="Разделы профиля">
          <span class="ps-profile-panel-nav__item is-active" aria-current="page">Основное</span>
          <a class="ps-profile-panel-nav__item ps-profile-panel-settings" href="${routes.notifications.replace("/notifications/notifications/all", "/pl/notifications/settings/my")}">Уведомления</a>
          <a class="ps-profile-panel-nav__item ps-profile-panel-daily" href="/pl/notifications/every-day-notification">Ежедневные уведомления</a>
          <a class="ps-profile-panel-nav__item ps-profile-panel-public" href="#" hidden>Открытый профиль</a>
        </nav>
        <div class="ps-profile-panel-status" role="status" aria-live="polite" hidden></div>
        <div class="gc-main-content gc-user-user ps-custom-page ps-profile-page ps-profile-panel-page ps-page-ready">
          <div class="container">
            <div class="ps-profile-panel-content"></div>
          </div>
        </div>
      </div>`;
    document.body.append(layer);

    const close = layer.querySelector(".ps-profile-panel-close");
    const content = layer.querySelector(".ps-profile-panel-content");
    const status = layer.querySelector(".ps-profile-panel-status");
    const settingsLink = layer.querySelector(".ps-profile-panel-settings");
    const dailyLink = layer.querySelector(".ps-profile-panel-daily");
    const publicLink = layer.querySelector(".ps-profile-panel-public");
    let activeTrigger = null;
    let requestController = null;
    let menuSnapshot = [];
    let menuTheme = null;

    const setStatus = (message = "", type = "") => {
      status.textContent = message;
      status.hidden = !message;
      status.className = `ps-profile-panel-status${type ? ` is-${type}` : ""}`;
    };

    const extractPublicHref = (page) => {
      const direct = page.querySelector(".page-actions a[href*='/pl/']")?.getAttribute("href");
      if (direct) return direct;
      const control = page.querySelector(".page-actions [onclick*='location.href']");
      const match = control?.getAttribute("onclick")?.match(/location\.href\s*=\s*['\"]([^'\"]+)['\"]/);
      return match?.[1] || "";
    };

    const updateProfileLinks = (page) => {
      const links = [...page.querySelectorAll(".content-menu a[href]")];
      const settings = links.find((item) => item.getAttribute("href")?.includes("/pl/notifications/settings/my"));
      const daily = links.find((item) => item.getAttribute("href")?.includes("/pl/notifications/every-day-notification"));
      if (settings) settingsLink.href = settings.href;
      if (daily) dailyLink.href = daily.href;
      const publicHref = extractPublicHref(page);
      publicLink.hidden = !publicHref;
      if (publicHref) publicLink.href = new URL(publicHref, location.origin).href;
    };

    const prepareFetchedForm = (page) => {
      const source = page.querySelector("form.page-main-form");
      if (!source) return null;
      const form = document.importNode(source, true);
      form.action = routes.profile;
      form.method = "post";
      form.querySelectorAll("script, style, .select2-container").forEach((node) => node.remove());
      form.querySelectorAll("select").forEach((select) => {
        select.classList.remove("select2-hidden-accessible");
        select.removeAttribute("aria-hidden");
        select.removeAttribute("data-select2-id");
        select.style.removeProperty("display");
      });
      decorateProfileForm(form, { managePassword: true });
      return form;
    };

    const responseMessage = (page) => normalize(
      [...page.querySelectorAll(".alert-danger, .error-summary, .has-error .help-block")]
        .map((node) => node.textContent)
        .filter(Boolean)
        .join(" ")
    );

    const renderProfile = (page, saved = false) => {
      const form = prepareFetchedForm(page);
      if (!form) throw new Error("Форма профиля не найдена");
      updateProfileLinks(page);
      content.replaceChildren(form);
      const validationError = responseMessage(page);
      if (validationError) setStatus(validationError, "error");
      else if (saved) setStatus("Данные профиля сохранены.", "success");
      else setStatus();

      form.addEventListener("submit", async (event) => {
        event.preventDefault();
        if (form.getAttribute("aria-busy") === "true") return;
        form.setAttribute("aria-busy", "true");
        form.querySelectorAll("button[type='submit'], input[type='submit']").forEach((button) => { button.disabled = true; });
        setStatus("Сохраняем изменения…", "loading");
        requestController?.abort();
        requestController = new AbortController();
        try {
          const formData = new FormData(form);
          if (event.submitter?.name && !formData.has(event.submitter.name)) {
            formData.append(event.submitter.name, event.submitter.value || "1");
          }
          const response = await fetch(routes.profile, {
            method: "POST",
            body: formData,
            credentials: "same-origin",
            cache: "no-store",
            signal: requestController.signal,
          });
          if (!response.ok) throw new Error(`HTTP ${response.status}`);
          const page = new DOMParser().parseFromString(await response.text(), "text/html");
          renderProfile(page, true);
        } catch (error) {
          if (error.name === "AbortError") return;
          form.removeAttribute("aria-busy");
          form.querySelectorAll("button[type='submit'], input[type='submit']").forEach((button) => { button.disabled = false; });
          setStatus("Не удалось сохранить изменения. Попробуйте ещё раз или откройте обычную страницу профиля.", "error");
        }
      });
    };

    const loadProfile = async () => {
      requestController?.abort();
      requestController = new AbortController();
      content.innerHTML = '<div class="ps-profile-panel-loading"><span aria-hidden="true"></span><p>Загружаем профиль…</p></div>';
      setStatus();
      try {
        const response = await fetch(`${routes.profile}?ps_panel=${Date.now()}`, {
          credentials: "same-origin",
          cache: "no-store",
          signal: requestController.signal,
        });
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        const page = new DOMParser().parseFromString(await response.text(), "text/html");
        renderProfile(page);
      } catch (error) {
        if (error.name === "AbortError") return;
        content.innerHTML = `<div class="ps-profile-panel-error"><h2>Профиль не загрузился</h2><p>Обновите страницу и попробуйте снова.</p><a href="${routes.profile}">Открыть обычную страницу профиля</a></div>`;
      }
    };

    const snapshotMenu = () => {
      const host = document.querySelector("#gcAccountUserMenu.ps-menu-ready");
      menuSnapshot = host ? [...host.querySelectorAll("[aria-current='page'], .is-active")].map((item) => ({
        item,
        active: item.classList.contains("is-active"),
        current: item.getAttribute("aria-current"),
      })) : [];
      menuTheme = host ? { light: host.classList.contains("ps-menu-light"), dark: host.classList.contains("ps-menu-dark") } : null;
      host?.querySelectorAll("[aria-current='page'], .is-active").forEach((item) => {
        item.classList.remove("is-active");
        item.removeAttribute("aria-current");
      });
      host?.classList.remove("ps-menu-dark");
      host?.classList.add("ps-menu-light");
      const profile = host?.querySelector(".ps-menu-profile");
      profile?.classList.add("is-active");
      profile?.setAttribute("aria-current", "page");
    };

    const restoreMenu = () => {
      const host = document.querySelector("#gcAccountUserMenu.ps-menu-ready");
      host?.querySelectorAll("[aria-current='page'], .is-active").forEach((item) => {
        item.classList.remove("is-active");
        item.removeAttribute("aria-current");
      });
      menuSnapshot.forEach(({ item, active, current }) => {
        if (!item.isConnected) return;
        item.classList.toggle("is-active", active);
        if (current) item.setAttribute("aria-current", current);
      });
      if (host && menuTheme) {
        host.classList.toggle("ps-menu-light", menuTheme.light);
        host.classList.toggle("ps-menu-dark", menuTheme.dark);
      }
      menuSnapshot = [];
      menuTheme = null;
    };

    const show = (trigger) => {
      if (layer.classList.contains("is-open")) return;
      activeTrigger = trigger;
      snapshotMenu();
      document.body.classList.add("ps-profile-panel-open");
      layer.classList.add("is-open");
      layer.setAttribute("aria-hidden", "false");
      layer.scrollTop = 0;
      close.focus();
      loadProfile();
    };

    const hide = () => {
      if (!layer.classList.contains("is-open")) return;
      requestController?.abort();
      layer.classList.remove("is-open");
      layer.setAttribute("aria-hidden", "true");
      document.body.classList.remove("ps-profile-panel-open");
      restoreMenu();
      activeTrigger?.focus();
      activeTrigger = null;
    };

    document.addEventListener("click", (event) => {
      const trigger = event.target.closest("#gcAccountUserMenu .ps-menu-profile");
      if (!trigger || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
      event.preventDefault();
      event.stopPropagation();
      event.stopImmediatePropagation();
      show(trigger);
    }, true);
    close.addEventListener("click", hide);
    document.addEventListener("keydown", (event) => {
      if (event.key === "Escape" && layer.classList.contains("is-open")) hide();
    });
  };

  const prepareProfile = (main) => {
    document.body.classList.add("ps-profile-route");
    main.classList.add("ps-custom-page", "ps-profile-page");
    ensureProfileMenu(main);
    setLightChrome();
    decorateProfileForm(main.querySelector("form.page-main-form"));
  };

  const prepareProfileSettings = (main) => {
    document.body.classList.add("ps-profile-settings-route");
    main.classList.add("ps-custom-page", "ps-profile-settings-page");
    ensureProfileMenu(main);
    setLightChrome();
    const table = main.querySelector(".standard-page-content table.table");
    if (!table) return;
    const headers = [...table.querySelectorAll("thead th")].map((cell) => normalize(cell.textContent));
    table.querySelectorAll("tbody tr").forEach((row) => {
      row.querySelectorAll(":scope > td").forEach((cell, index) => {
        cell.dataset.label = headers[index] || "";
        if (!headers[index] && !normalize(cell.textContent)) cell.classList.add("ps-profile-empty-cell");
      });
    });
  };

  const preparePublicProfile = (main) => {
    document.body.classList.add("ps-public-profile-route");
    main.classList.add("ps-custom-page", "ps-public-profile-page");
    ensureProfileMenu(main);
    setLightChrome();
    const title = main.querySelector(".xdget-profileTitle");
    const edit = document.querySelector(".edit-profile-popup-btn");
    if (title && edit && !main.querySelector(".ps-public-profile-header")) {
      const header = document.createElement("div");
      header.className = "ps-public-profile-header";
      title.before(header);
      header.append(title, edit);
    }
  };

  const expandDate = (value) => {
    const months = {
      "Янв": "Января",
      "Фев": "Февраля",
      "Мар": "Марта",
      "Апр": "Апреля",
      "Май": "Мая",
      "Июн": "Июня",
      "Июл": "Июля",
      "Авг": "Августа",
      "Сен": "Сентября",
      "Окт": "Октября",
      "Ноя": "Ноября",
      "Дек": "Декабря",
    };
    return normalize(value).replace(/(^|\s)(Янв|Фев|Мар|Апр|Май|Июн|Июл|Авг|Сен|Окт|Ноя|Дек)(?=\s|$|[.,])/g, (_, space, month) => `${space}${months[month]}`);
  };

  const decorateNotification = (card) => {
    if (card.dataset.psNotificationReady === "true") return;
    card.dataset.psNotificationReady = "true";
    const content = card.querySelector(".notification-group-link");
    if (content) {
      const raw = content.innerText || content.textContent || "";
      const original = normalize(raw);
      const firstParagraph = raw.split(/\n\s*\n/)[0];
      const summary = normalize(firstParagraph).replace(/\s*Перейдите по ссылке\s*$/i, "").trim();
      content.textContent = summary || original;
      card.setAttribute("aria-label", summary || original);
      content.title = summary || original;
    }
    const date = card.querySelector(".date");
    if (date) date.textContent = expandDate(date.textContent);
  };

  const prepareNotifications = (main) => {
    document.body.classList.add("ps-notifications-route");
    main.classList.add("ps-custom-page", "ps-notifications-page");
    setDarkChrome();
    const list = main.querySelector(".user-notifications");
    if (!list) return;
    const decorateAll = () => list.querySelectorAll(".notification-group").forEach(decorateNotification);
    decorateAll();
    new MutationObserver(decorateAll).observe(list, { childList: true, subtree: true });
  };

  const createBackLink = (container, header) => {
    if (!container || !header || container.querySelector(".ps-answers-back")) return;
    const link = document.createElement("a");
    link.className = "ps-answers-back";
    link.href = routes.notifications;
    const icon = document.createElement("span");
    icon.className = "ps-material-symbol";
    icon.setAttribute("aria-hidden", "true");
    icon.textContent = "arrow_circle_left";
    const label = document.createElement("span");
    label.textContent = "Назад к уведомлениям";
    link.append(icon, label);
    container.insertBefore(link, header);
  };

  const prepareAnswers = (main) => {
    document.body.classList.add("ps-answers-route");
    main.classList.add("ps-custom-page", "ps-answers-page");
    setDarkChrome();
    const container = main.querySelector(".main-page-container");
    const header = container?.querySelector(".page-header");
    const pageTitle = header?.querySelector("h1");
    if (pageTitle && new URLSearchParams(location.search).has("lesson")) {
      pageTitle.textContent = "Ответ по заданию";
      document.title = "Ответ по заданию";
    }
    createBackLink(container, header);
    const hasMeaningfulContent = (root) => {
      if (!root) return false;
      const copy = root.cloneNode(true);
      copy.querySelectorAll("script, style, template, textarea, .settings, .hide").forEach((node) => node.remove());
      return Boolean(
        normalize(copy.textContent) ||
        copy.querySelector("img, audio, video, iframe, input, button, .file-block a, .file-link")
      );
    };
    const decorateAnswer = (card) => {
      const content = card.querySelector(".answer-content");
      const title = content?.querySelector(":scope > .title");
      if (card.dataset.psAnswerReady !== "true" && title && !title.querySelector(".ps-answer-author-copy")) {
        const author = title.querySelector(":scope > .user-profile-link");
        const date = title.querySelector(":scope > .answer-date");
        if (author || date) {
          const authorCopy = document.createElement("span");
          authorCopy.className = "ps-answer-author-copy";
          if (author) authorCopy.append(author);
          if (date) authorCopy.append(date);
          title.append(authorCopy);
        }
      }
      const result = title?.nextElementSibling;
      if (result && result.matches("div") && /результат/i.test(normalize(result.textContent))) {
        result.classList.add("ps-answer-result");
      }
      const details = content?.querySelector(":scope > .answer-main-content");
      const mainAnswer = details?.querySelector(":scope > .main");
      if (details) details.classList.toggle("ps-is-empty", !hasMeaningfulContent(mainAnswer));
      const comments = content?.querySelector(":scope > .comments");
      if (comments) comments.classList.toggle("ps-is-empty", !hasMeaningfulContent(comments));
      card.dataset.psAnswerReady = "true";
    };
    const answerList = container?.querySelector(".answers-list");
    const decorateAnswers = () => answerList?.querySelectorAll(".answer_wrapper").forEach(decorateAnswer);
    decorateAnswers();
    if (answerList) new MutationObserver(decorateAnswers).observe(answerList, { childList: true, subtree: true });
  };

  const installTransitions = () => {
    document.addEventListener("click", (event) => {
      if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
      if (event.target.closest("body.ps-answers-route .page-actions .btn")) {
        document.body.classList.add("ps-page-leaving");
        return;
      }
      const link = event.target.closest("a[href]");
      if (!link || link.hasAttribute("download") || link.dataset.psWidgetId || (link.target && link.target !== "_self")) return;
      let target;
      try {
        target = new URL(link.href, location.href);
      } catch {
        return;
      }
      if (target.origin !== location.origin || target.href === location.href || (target.pathname === location.pathname && target.search === location.search && target.hash)) return;
      event.preventDefault();
      document.body.classList.add("ps-page-leaving");
      window.setTimeout(() => location.assign(target.href), 180);
    });
    document.addEventListener("submit", (event) => {
      if (event.target.closest(".ps-profile-layer")) return;
      document.body.classList.add("ps-page-leaving");
    }, true);
    window.addEventListener("beforeunload", () => document.body.classList.add("ps-page-leaving"));
    window.addEventListener("pageshow", () => document.body.classList.remove("ps-page-leaving"));
  };

  const init = () => {
    document.documentElement.dataset.psSystemPagesBuild = build;
    const main = document.querySelector(".gc-main-content.gc-user-user");
    if (!main || document.body.classList.contains("gc-user-admin")) return;
    const path = location.pathname;
    if (path === "/user/my/profile") prepareProfile(main);
    if (path === "/pl/notifications/settings/my") prepareProfileSettings(main);
    if (main.querySelector(".xdget-userProfileSystemPage")) preparePublicProfile(main);
    if (path.startsWith("/notifications/notifications/")) prepareNotifications(main);
    if (path === "/teach/control/answers/my") prepareAnswers(main);
    createProfileLayer();
    installTransitions();
    requestAnimationFrame(() => main.classList.add("ps-page-ready"));
  };

  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init, { once: true });
  else init();
})();
