/* CoProducer Modular Loader (CP)
Purpose:
- isolate feature code by modules: stream, mixer, overlays, media, virtuals
- keep core UI stable while modules can be replaced/overridden
*/
(function(){
  'use strict';
  const CP = (window.CP = window.CP || {});
  CP.modules = CP.modules || {};
  CP.register = function(name, mod){
    if (!name) return;
    CP.modules[name] = mod || {};
  };
  CP.get = function(name){ return CP.modules[name]; };

  CP.ready = function(fn){
    if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', fn);
    else fn();
  };

  // Tiny helpers used by modules (safe on shared hosting / no build tools)
  CP.$  = (sel, root) => (root || document).querySelector(sel);
  CP.$$ = (sel, root) => Array.from((root || document).querySelectorAll(sel));

  CP.on = function(el, evt, fn, opts){
    if (!el) return;
    el.addEventListener(evt, fn, opts || false);
  };

  CP.dispatch = function(name, detail){
    try { window.dispatchEvent(new CustomEvent('cp:' + name, { detail: detail || {} })); } catch(e){}
  };

  CP.safeJSON = function(s, fallback){
    try { return JSON.parse(s); } catch(e){ return fallback; }
  };

  // Boot: init all registered modules that expose init()
  CP.boot = function(){
    Object.keys(CP.modules).forEach((k)=>{
      const mod = CP.modules[k];
      if (mod && typeof mod.init === 'function') {
        try { mod.init(); } catch(e){ console.error('[CP] module init failed:', k, e); }
      }
    });
  };

  CP.ready(()=> CP.boot());
})();
