<?php
require_once('header.php');

if (!$hasJupyter) {
    header("location:dashboard.php");
    exit;
}
?>

    <style>
      .jupyter-wrap {
        position: fixed;
        top: 56px;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 1;
        overflow: hidden;
      }
      .jupyter-wrap iframe {
        width: 100%;
        height: 100%;
        border: none;
      }
    </style>

    <div class="jupyter-wrap">
      <iframe id="jupyter-frame" src="/jupyter/lab" allow="clipboard-read; clipboard-write"></iframe>
    </div>

    <script>
    (function () {
      var THEME_API = '/jupyter/api/settings/@jupyterlab/apputils-extension:themes';
      var CSS_URL = '/jupyter/static/custom/custom.css';

      function gkTheme() {
        return localStorage.getItem('gk-theme') || 'dark';
      }

      function jpThemeName(gk) {
        return gk === 'light' ? 'JupyterLab Light' : 'JupyterLab Dark';
      }

      /* Use the iframe's fetch so Jupyter session cookies are included */
      function setJupyterTheme(themeName) {
        try {
          var ifrWin = document.getElementById('jupyter-frame').contentWindow;
          if (!ifrWin || !ifrWin.fetch) return;

          /* Jupyter API requires _xsrf cookie as header */
          var xsrf = '';
          try {
            var cookies = ifrWin.document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
              var c = cookies[i].trim();
              if (c.indexOf('_xsrf=') === 0) { xsrf = c.substring(6); break; }
            }
          } catch (e) {}

          var headers = { 'Content-Type': 'application/json' };
          if (xsrf) headers['X-XSRFToken'] = xsrf;

          ifrWin.fetch(THEME_API, {
            method: 'PUT',
            credentials: 'same-origin',
            headers: headers,
            body: JSON.stringify({ raw: JSON.stringify({ theme: themeName }) })
          }).catch(function () {});
        } catch (e) {}
      }

      function injectCustomCSS() {
        try {
          var ifrDoc = document.getElementById('jupyter-frame').contentDocument;
          if (!ifrDoc || ifrDoc.getElementById('gk-jupyter-css')) return;
          var link = ifrDoc.createElement('link');
          link.id = 'gk-jupyter-css';
          link.rel = 'stylesheet';
          link.href = CSS_URL;
          ifrDoc.head.appendChild(link);
        } catch (e) {}
      }

      /* Retry until JupyterLab is fully loaded */
      function syncThemeWhenReady(retries) {
        retries = retries || 0;
        if (retries > 15) return;

        try {
          var ifrDoc = document.getElementById('jupyter-frame').contentDocument;
          var jpApp = ifrDoc && ifrDoc.querySelector('#jp-main-dock-panel, .jp-LabShell');
          if (jpApp) {
            setJupyterTheme(jpThemeName(gkTheme()));
            injectCustomCSS();
            return;
          }
        } catch (e) {}

        setTimeout(function () { syncThemeWhenReady(retries + 1); }, 1500);
      }

      /* Sync on iframe load */
      var frame = document.getElementById('jupyter-frame');
      frame.addEventListener('load', function () {
        syncThemeWhenReady(0);
      });

      /* Watch for theme toggle clicks in the parent page */
      var observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (m) {
          if (m.attributeName === 'data-theme') {
            var next = document.documentElement.getAttribute('data-theme') || 'dark';
            setJupyterTheme(jpThemeName(next));
          }
        });
      });
      observer.observe(document.documentElement, { attributes: true });
    })();
    </script>

<?php require_once('footer.php'); ?>
