(function(w,d){
  'use strict';

  var paneMap = {
    media: { title: 'Media Studio', selector: '#tab-media', badge: 'MEDIA' },
    transition: { title: 'Transition Studio', selector: '#tab-transitions', badge: 'TRANSITION' },
    virtual: { title: 'Virtual Studio', selector: '#tab-virtuals', badge: 'VIRTUAL' },
    gueststudio: { title: 'Guest Studio', selector: '#tab-gueststudio', badge: 'GUESTS' }
  };

  var state = {
    active: null,
    sourcePane: null,
    modal: null,
    mount: null,
    title: null,
    placeholder: null,
    movedNodes: []
  };

  function q(sel, root){ return (root || d).querySelector(sel); }
  function qa(sel, root){ return Array.prototype.slice.call((root || d).querySelectorAll(sel)); }

  function ensureModal(){
    state.modal = state.modal || q('#featureStudioModal');
    state.mount = state.mount || q('#featureStudioMount');
    state.title = state.title || q('#featureStudioTitle');
    if (!state.modal || !state.mount || !state.title) return false;

    if (!state.modal.__featureStudioBound) {
      state.modal.__featureStudioBound = true;

      var btnClose = q('#btnFeatureStudioClose');
      var btnReturn = q('#btnFeatureStudioReturn');
      var backdrop = q('[data-close-feature-studio="1"]', state.modal);

      if (btnClose) btnClose.addEventListener('click', close, true);
      if (btnReturn) btnReturn.addEventListener('click', close, true);
      if (backdrop) backdrop.addEventListener('click', close, true);

      state.modal.addEventListener('click', function(ev){
        if (ev.target === state.modal) close(ev);
      }, true);
    }
    return true;
  }

  function showModal(){
    if (!ensureModal()) return false;
    if (typeof w.__modalShow === 'function') w.__modalShow(state.modal);
    else {
      state.modal.hidden = false;
      state.modal.setAttribute('aria-hidden', 'false');
      state.modal.classList.add('show');
      d.body.classList.add('featureStudioBodyLock');
    }
    return true;
  }

  function hideModal(){
    if (!ensureModal()) return false;
    if (typeof w.__modalHide === 'function') w.__modalHide(state.modal);
    else {
      state.modal.hidden = true;
      state.modal.setAttribute('aria-hidden', 'true');
      state.modal.classList.remove('show');
      d.body.classList.remove('featureStudioBodyLock');
    }
    return true;
  }

  function movePaneIntoModal(kind){
    var cfg = paneMap[kind];
    if (!cfg || !ensureModal()) return false;

    var pane = q(cfg.selector);
    if (!pane) return false;

    if (state.active && state.active !== kind) restorePane();

    state.active = kind;
    state.sourcePane = pane;
    state.title.textContent = cfg.title;
    state.mount.setAttribute('data-feature-kind', kind);

    // leave main tab lightweight while workspace is open
    pane.classList.add('featureWorkspaceDetached');
    pane.setAttribute('data-feature-detached', '1');

    state.placeholder = d.createComment('feature-studio:' + kind);
    if (!pane.firstChild) pane.appendChild(state.placeholder);
    else pane.insertBefore(state.placeholder, pane.firstChild);

    state.movedNodes = [];
    while (pane.childNodes.length > 1 || (pane.childNodes.length === 1 && pane.firstChild !== state.placeholder)) {
      var node = pane.lastChild;
      if (node === state.placeholder) break;
      state.movedNodes.unshift(node);
      state.mount.insertBefore(node, state.mount.firstChild);
    }

    // move any remaining non-placeholder nodes in original order
    var remaining = [];
    for (var i = 0; i < pane.childNodes.length; i++) {
      var n = pane.childNodes[i];
      if (n !== state.placeholder) remaining.push(n);
    }
    remaining.forEach(function(node){
      state.movedNodes.push(node);
      state.mount.appendChild(node);
    });

    d.body.classList.add('featureStudioBodyLock');
    d.body.setAttribute('data-feature-studio-open', kind);
    return showModal();
  }

  function restorePane(){
    if (!state.sourcePane) return;
    var pane = state.sourcePane;
    var anchor = state.placeholder;

    state.movedNodes.forEach(function(node){
      pane.appendChild(node);
    });

    if (anchor && anchor.parentNode === pane) anchor.parentNode.removeChild(anchor);

    pane.classList.remove('featureWorkspaceDetached');
    pane.removeAttribute('data-feature-detached');

    state.mount.innerHTML = '';
    state.mount.removeAttribute('data-feature-kind');
    state.movedNodes = [];
    state.placeholder = null;
    state.sourcePane = null;
    state.active = null;
    d.body.classList.remove('featureStudioBodyLock');
    d.body.removeAttribute('data-feature-studio-open');
  }

  function fallbackOpen(kind){
    if (!ensureModal()) return false;
    var cfg = paneMap[kind] || { title: 'Studio' };
    state.active = kind;
    state.title.textContent = cfg.title;
    state.mount.setAttribute('data-feature-kind', kind);
    state.mount.innerHTML = '' +
      '<div class="featureStudioFallback">' +
      '  <div class="featureStudioFallback__badge">' + (cfg.badge || 'STUDIO') + '</div>' +
      '  <h4>' + cfg.title + '</h4>' +
      '  <p>This workspace shell is active, but no dedicated module renderer was found.</p>' +
      '  <p>Use this as the stable mount point for the final ' + cfg.title + ' implementation.</p>' +
      '</div>';
    d.body.classList.add('featureStudioBodyLock');
    d.body.setAttribute('data-feature-studio-open', kind);
    return showModal();
  }

  function open(kind, opts){
    opts = opts || {};
    if (kind === 'overlay') {
      if (typeof w.openOverlayComposer === 'function' && !opts.__bypassNativeOverlay) {
        return w.openOverlayComposer(opts.sceneId || '');
      }
      var oc = q('#overlayComposerModal');
      if (oc) {
        if (typeof w.__ocOpenComposerInner === 'function') {
          try { w.__ocOpenComposerInner(opts.sceneId || ''); } catch (_) {}
        }
        if (typeof w.__modalShow === 'function') w.__modalShow(oc);
        else { oc.hidden = false; oc.setAttribute('aria-hidden', 'false'); oc.classList.add('show'); }
        return false;
      }
      return fallbackOpen(kind);
    }

    if (state.active && state.active !== kind) {
      close();
    }

    if (paneMap[kind] && q(paneMap[kind].selector)) {
      return movePaneIntoModal(kind);
    }
    return fallbackOpen(kind);
  }

  function close(ev){
    if (ev && ev.preventDefault) ev.preventDefault();
    if (ev && ev.stopPropagation) ev.stopPropagation();
    restorePane();
    hideModal();
    return false;
  }

  function bindLaunchers(){
    if (d.__featureStudioDelegatedBound2) return;
    d.__featureStudioDelegatedBound2 = true;

    d.addEventListener('click', function(ev){
      var btn = ev.target && ev.target.closest ? ev.target.closest('[data-studio-launch]') : null;
      if (!btn) return;
      var kind = btn.getAttribute('data-studio-launch');
      if (!kind) return;
      if (kind === 'media' || kind === 'transition' || kind === 'virtual') {
        ev.preventDefault();
        ev.stopPropagation();
        open(kind);
      }
    }, true);

    d.addEventListener('keydown', function(ev){
      if (ev.key !== 'Escape') return;
      if (state.active) close(ev);
    }, true);
  }

  w.FeatureStudioManager = {
    open: open,
    close: close,
    restore: restorePane,
    state: state
  };

  w.openMediaStudioLauncher = function(ev){ return open('media'); };
  w.openVirtualStudioLauncher = function(ev){ return open('virtual'); };
  w.openTransitionStudioLauncher = function(ev){ return open('transition'); };
  w.openGuestStudioLauncher = function(ev){ return open('gueststudio'); };

  w.MediaStudio = w.MediaStudio || {};
  w.VirtualStudio = w.VirtualStudio || {};
  w.TransitionStudio = w.TransitionStudio || {};

  w.MediaStudio.open = function(opts){ return open('media', opts || {}); };
  w.VirtualStudio.open = function(opts){ return open('virtual', opts || {}); };
  w.TransitionStudio.open = function(opts){ return open('transition', opts || {}); };

  if (d.readyState === 'loading') d.addEventListener('DOMContentLoaded', bindLaunchers, { once:true });
  else bindLaunchers();
})(window, document);
