/*
 * WOW 11 ДЕМО — таймеры 24 часа (несколько демо одновременно).
 * Ответ эндпоинта (Chatium deal_timer):
 *   { "demos": [ { "productId": 4544647, "finishAt": "2026-11-09T00:49:01.000Z" } ], "serverNow": "…" }
 */
(function (window, document, location) {
  "use strict";

  // ===== НАСТРОЙКИ =====
  var CONFIG = {
    endpoint: "/chtm/demoTimer/deal_timer",
    preorderUrl: "https://wowmarketing-school.ru/profession/list?utm_source=GetCourse&utm_medium=demo1",
    preorderNewTab: false,
    cacheMs: 5 * 60 * 1000,
    barHeight: 48,
    // Каждое демо: продукт GetCourse → корневой тренинг → подпись в общей плашке → ссылка на предзапись
    // (если у демо нет своей preorderUrl, берётся общая preorderUrl выше)
    demos: [
      { productId: 4544647, root: "/teach/control/stream/view/id/935991198", label: "«Без бюджета»",
        preorderUrl: "https://wowmarketing-school.ru/profession/list?utm_source=GetCourse&utm_medium=demo1" },
      { productId: 4550510, root: "/teach/control/stream/view/id/936004537", label: "«Антикризисная стратегия»",
        preorderUrl: "https://wowmarketing-school.ru/profession/list?utm_source=GetCourse&utm_medium=demo2" }
    ]
  };
  var TEXT = {
    barLabel: "Демо-доступ закроется через",
    barLabelShort: "Демо:",
    barPrefixMany: "Демо-доступ:",
    barButton: "Предзапись на WOW 11",
    barEnded: "Демо-доступ закрыт \uD83D\uDD12",
    endedShort: "закрыт",
    endTitle: "ДЕМО-ДОСТУП ЗАКРЫТ \uD83D\uDD12",
    endText: "Этот урок был лишь 0,6% флагманской программы WOW. Всё остальное, включая систему, инструменты 2027 года и ИИ, ждёт вас в WOW 11",
    endButton: "Оставить предзапись на WOW 11"
  };
  // ===== /НАСТРОЙКИ =====

  if (window.__W11_TIMER__) return;
  window.__W11_TIMER__ = true;

  if (/(?:^|[?&])editMode=1(?:&|$)/.test(location.search) || /\/editMode\/1\/?$/.test(location.pathname)) return;

  var TEST_KEY = "w11-timer:test";
  var demos = [];        // [{ productId, root, label, deadline }]
  var ticker = null;
  var overlayShown = false;

  function userId() {
    var value = window.accountUserId;
    if (value != null && value !== "") return String(value);
    var scripts = document.scripts || [];
    for (var i = 0; i < scripts.length; i += 1) {
      var match = String(scripts[i].textContent || "").match(/window\.accountUserId\s*=\s*(-?\d+)/);
      if (match) return match[1];
    }
    return "";
  }

  function storageGet(key) { try { return window.sessionStorage.getItem(key); } catch (e) { return null; } }
  function storageSet(key, value) { try { window.sessionStorage.setItem(key, value); } catch (e) {} }
  function storageRemove(key) { try { window.sessionStorage.removeItem(key); } catch (e) {} }

  function testDeadline() {
    var match = location.search.match(/[?&]w11test=(\d+)/);
    if (match) {
      if (match[1] === "0") { storageRemove(TEST_KEY); return null; }
      var value = Date.now() + Number(match[1]) * 1000;
      storageSet(TEST_KEY, String(value));
      return value;
    }
    var saved = storageGet(TEST_KEY);
    return saved ? Number(saved) : null;
  }

  // Дедлайны по продуктам в часах клиента (с поправкой на часы сервера)
  function loadDeadlines(uid) {
    var cacheKey = "w11-timer:v2:" + uid;
    var cached = null;
    try { cached = JSON.parse(storageGet(cacheKey) || "null"); } catch (e) { cached = null; }
    if (cached && Date.now() - cached.fetchedAt < CONFIG.cacheMs) return Promise.resolve(cached.byProduct || {});
    if (typeof window.fetch !== "function") return Promise.resolve({});
    return window.fetch(CONFIG.endpoint, { credentials: "same-origin", headers: { Accept: "application/json" } })
      .then(function (response) {
        if (!response.ok) throw new Error("w11-timer-" + response.status);
        return response.json();
      })
      .then(function (data) {
        var serverNow = data && data.serverNow ? Date.parse(data.serverNow) : NaN;
        var offset = isNaN(serverNow) ? 0 : serverNow - Date.now();
        var byProduct = {};
        (data && Array.isArray(data.demos) ? data.demos : []).forEach(function (item) {
          var finish = Date.parse(item.finishAt);
          if (!isNaN(finish)) byProduct[String(item.productId)] = finish - offset;
        });
        storageSet(cacheKey, JSON.stringify({ byProduct: byProduct, fetchedAt: Date.now() }));
        return byProduct;
      })
      .catch(function () { return cached ? cached.byProduct || {} : {}; });
  }

  function pad(n) { return (n < 10 ? "0" : "") + n; }
  function format(ms) {
    var total = Math.max(0, Math.floor(ms / 1000));
    return pad(Math.floor(total / 3600)) + ":" + pad(Math.floor((total % 3600) / 60)) + ":" + pad(total % 60);
  }

  // Демо, внутри которого сейчас ученик (корень определяет загрузчик)
  function currentDemo() {
    var root = window.__GCX_NEXT_ACTIVE_ROOT__;
    if (!root) return null;
    for (var i = 0; i < demos.length; i += 1) if (demos[i].root === root) return demos[i];
    return null;
  }

  function installStyles() {
    if (document.getElementById("w11-timer-style")) return;
    var h = CONFIG.barHeight + "px";
    var style = document.createElement("style");
    style.id = "w11-timer-style";
    style.setAttribute("data-gcx-next-theme-asset", "true");
    style.textContent = [
      ".w11-bar{align-items:center;background:#8c103a;box-sizing:border-box;color:#fff;display:flex;font:400 15px/1.2 \"Geologica\",Arial,sans-serif;gap:14px;height:" + h + ";justify-content:center;left:0;padding:0 16px;position:fixed;right:0;top:0;z-index:9800}",
      ".w11-bar__text{font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}",
      ".w11-bar__text b{font-weight:500;letter-spacing:.04em}",
      ".w11-bar__cta{background:#fff;border-radius:10px;color:#8c103a!important;flex:0 0 auto;font-size:14px;padding:8px 14px;text-decoration:none!important;white-space:nowrap}",
      ".w11-bar__cta:hover,.w11-bar__cta:focus-visible{background:#f9edf1;outline:none}",
      "html.w11-has-bar body{padding-top:" + h + "!important}",
      "html.w11-has-bar .gcx-account-menu__wrap,html.w11-has-bar #redesignedNoticeTopPanel{translate:0 " + h + "!important}",
      "@media(max-width:600px){.w11-bar{font-size:13px;gap:10px;padding:0 10px}.w11-bar__cta{font-size:12px;padding:7px 10px}}",
      "[data-w11-timer]{font-variant-numeric:tabular-nums}",
      ".w11-end{align-items:center;backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);background:rgba(247,245,245,.94);box-sizing:border-box;display:flex;inset:0;justify-content:center;overflow:auto;padding:24px;position:fixed;z-index:1000000}",
      ".w11-end__dialog{background:#fff;border-radius:24px;box-shadow:0 18px 44px rgba(83,8,29,.16);box-sizing:border-box;color:#0e0e0e;font-family:\"Geologica\",Arial,sans-serif;max-width:520px;padding:44px 36px 36px;text-align:center;width:100%}",
      ".w11-end__time{color:#8c103a;font-size:44px;font-variant-numeric:tabular-nums;font-weight:300;letter-spacing:.06em;line-height:1;margin-bottom:20px}",
      ".w11-end__title{font-size:22px;font-weight:500;letter-spacing:.04em;line-height:1.3;margin:0 0 16px}",
      ".w11-end__text{color:#4a4446;font-size:16px;line-height:1.5;margin:0 0 28px}",
      ".w11-end__button{align-items:center;background:#8c103a;border-radius:12px;box-sizing:border-box;color:#fff!important;display:inline-flex;font:400 16px/1.25 \"Geologica\",Arial,sans-serif;justify-content:center;min-height:54px;padding:14px 24px;text-decoration:none!important;width:100%}",
      ".w11-end__button:hover,.w11-end__button:focus-visible{background:#6f0c2e;outline:none}",
      "html.w11-ended,html.w11-ended body{overflow:hidden!important}",
      "@media(max-width:430px){.w11-end__dialog{padding:36px 20px 24px}.w11-end__time{font-size:36px}.w11-end__title{font-size:19px}.w11-end__text{font-size:15px}}"
    ].join("");
    (document.head || document.documentElement).appendChild(style);
  }

  // Ссылка на предзапись: своя у демо этой страницы, иначе общая
  function preorderUrlHere() {
    var here = currentDemo();
    return here && here.preorderUrl ? here.preorderUrl : CONFIG.preorderUrl;
  }

  function preorderLink(className, text) {
    var link = document.createElement("a");
    link.className = className;
    link.textContent = text;
    link.href = preorderUrlHere();
    if (CONFIG.preorderNewTab) { link.target = "_blank"; link.rel = "noopener"; }
    return link;
  }

  function buildBar() {
    if (document.querySelector(".w11-bar")) return;
    var bar = document.createElement("div");
    bar.className = "w11-bar";
    bar.setAttribute("role", "status");
    var text = document.createElement("span");
    text.className = "w11-bar__text";
    bar.appendChild(text);
    bar.appendChild(preorderLink("w11-bar__cta", TEXT.barButton));
    document.body.insertBefore(bar, document.body.firstChild);
    document.documentElement.classList.add("w11-has-bar");
  }

  // Текст плашки: «подпись <b>время</b>», без innerHTML
  function setBarText(parts) {
    var node = document.querySelector(".w11-bar__text");
    if (!node) return;
    var key = JSON.stringify(parts);
    if (node.__w11Key === key) return;
    node.__w11Key = key;
    node.textContent = "";
    parts.forEach(function (part, index) {
      if (index) node.appendChild(document.createTextNode(" \u00B7 "));
      node.appendChild(document.createTextNode(part.label ? part.label + " " : ""));
      var b = document.createElement("b");
      b.textContent = part.value;
      node.appendChild(b);
    });
  }

  function stopMedia() {
    Array.prototype.forEach.call(document.querySelectorAll("video, audio"), function (media) {
      try { media.pause(); } catch (e) {}
    });
    Array.prototype.forEach.call(document.querySelectorAll("iframe[src]"), function (frame) {
      if (frame.closest(".w11-end")) return;
      frame.setAttribute("data-w11-src", frame.getAttribute("src"));
      frame.setAttribute("src", "about:blank");
    });
  }

  function showEndOverlay() {
    if (overlayShown || document.querySelector(".w11-end")) return;
    overlayShown = true;
    var overlay = document.createElement("div");
    overlay.className = "w11-end";
    var dialog = document.createElement("div");
    dialog.className = "w11-end__dialog";
    dialog.setAttribute("role", "dialog");
    dialog.setAttribute("aria-modal", "true");
    dialog.setAttribute("aria-labelledby", "w11-end-title");
    var time = document.createElement("div");
    time.className = "w11-end__time";
    time.textContent = "00:00:00";
    var title = document.createElement("h2");
    title.className = "w11-end__title";
    title.id = "w11-end-title";
    title.textContent = TEXT.endTitle;
    var text = document.createElement("p");
    text.className = "w11-end__text";
    text.textContent = TEXT.endText;
    var button = preorderLink("w11-end__button", TEXT.endButton);
    dialog.appendChild(time);
    dialog.appendChild(title);
    dialog.appendChild(text);
    dialog.appendChild(button);
    overlay.appendChild(dialog);
    document.body.appendChild(overlay);
    document.documentElement.classList.add("w11-ended");
    stopMedia();
    button.focus();
    document.addEventListener("keydown", function (event) {
      if (event.key === "Tab") { event.preventDefault(); button.focus(); }
    }, true);
  }

  function render() {
    var now = Date.now();
    var active = demos.filter(function (d) { return d.deadline; });
    if (!active.length) return;
    var here = currentDemo();
    var narrow = window.innerWidth < 600;
    var cta = document.querySelector(".w11-bar__cta");
    if (cta && cta.getAttribute("href") !== preorderUrlHere()) cta.setAttribute("href", preorderUrlHere());
    var singleLabel = narrow ? TEXT.barLabelShort : TEXT.barLabel;

    // Встроенные таймеры — только по демо этой страницы. Пока демо не определено, не трогаем,
    // чтобы не показать на секунду время другого демо.
    if (here && here.deadline) {
      var inlineText = format(here.deadline - now);
      Array.prototype.forEach.call(document.querySelectorAll("[data-w11-timer]"), function (node) {
        if (node.textContent !== inlineText) node.textContent = inlineText;
      });
    }

    // Плашка
    if (here && here.deadline) {
      var left = here.deadline - now;
      setBarText(left > 0 ? [{ label: singleLabel, value: format(left) }] : [{ label: "", value: TEXT.barEnded }]);
      if (left <= 0) showEndOverlay();
    } else if (active.length === 1) {
      var only = active[0].deadline - now;
      setBarText(only > 0 ? [{ label: singleLabel, value: format(only) }] : [{ label: "", value: TEXT.barEnded }]);
    } else {
      var parts = active.map(function (d) {
        var ms = d.deadline - now;
        return { label: d.label + ":", value: ms > 0 ? format(ms) : TEXT.endedShort };
      });
      if (!narrow) parts[0].label = TEXT.barPrefixMany + " " + parts[0].label;
      setBarText(parts);
    }
  }

  function start(byProduct, testValue) {
    demos = CONFIG.demos.map(function (d) {
      return {
        productId: d.productId,
        root: d.root,
        label: d.label,
        preorderUrl: d.preorderUrl || CONFIG.preorderUrl,
        deadline: testValue || byProduct[String(d.productId)] || null
      };
    });
    if (!demos.some(function (d) { return d.deadline; })) return;
    // Ждём, пока загрузчик определит тренинг страницы (до 3 секунд), чтобы с первой же
    // секунды показать таймер нужного демо, а не общий список
    var waited = 0;
    (function waitForRoot() {
      if (!window.__GCX_NEXT_ACTIVE_ROOT__ && waited < 3000) {
        waited += 100;
        window.setTimeout(waitForRoot, 100);
        return;
      }
      installStyles();
      buildBar();
      render();
      ticker = window.setInterval(render, 1000);
    })();
    document.addEventListener("visibilitychange", function () { if (!document.hidden) render(); });
  }

  function init() {
    var test = testDeadline();
    if (test) { start({}, test); return; }
    var uid = userId();
    if (!/^[1-9][0-9]*$/.test(uid)) return;
    loadDeadlines(uid).then(function (byProduct) { start(byProduct, null); });
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", init, { once: true });
  } else {
    init();
  }
})(window, document, location);