← back to Marketing Command Center

public/panels/calendarhub.js

49 lines

// Calendar hub — merges the advanced "calendars" and simple "calendar" panels
// into one tabbed surface WITHOUT duplicating their code. Each tab loads the real
// panel's html into its pane and calls that panel's own MCC_PANELS[id].init(pane),
// so calendars.js / calendar.js remain the single source of truth. Lazy: Timeline
// inits on open, Plan on first click. (calendars.js scopes DOM by global document
// queries on #cwroot, so it works fine loaded into a pane.)
window.MCC_PANELS = window.MCC_PANELS || {};
window.MCC_PANELS['calendarhub'] = {
  async init(root) {
    const ORIGIN = location.origin;
    const paneT = root.querySelector('[data-pane="timeline"]');
    const paneP = root.querySelector('[data-pane="plan"]');
    let tInited = false, pInited = false;

    async function ensureScript(id) {
      if (window.MCC_PANELS[id]) return;
      await new Promise(res => {
        const s = document.createElement('script');
        s.src = ORIGIN + '/panels/' + id + '.js';
        s.onload = res; s.onerror = res;
        document.body.appendChild(s);
      });
    }
    async function mountInto(id, pane) {
      try {
        const r = await fetch(ORIGIN + '/panels/' + id + '.html', { credentials: 'same-origin' });
        pane.innerHTML = r.ok ? await r.text() : `<div class="muted">Could not load ${id}.</div>`;
      } catch { pane.innerHTML = `<div class="muted">Could not load ${id}.</div>`; return; }
      await ensureScript(id);
      try {
        if (window.MCC_PANELS[id] && window.MCC_PANELS[id].init) await window.MCC_PANELS[id].init(pane);
      } catch (e) { console.error('[calendarhub] ' + id + ' init failed', e); }
    }

    async function initTimeline() { if (tInited) return; tInited = true; await mountInto('calendars', paneT); }
    async function initPlan() { if (pInited) return; pInited = true; await mountInto('calendar', paneP); }

    root.querySelectorAll('.calh-tab').forEach(btn => btn.onclick = () => {
      const t = btn.dataset.tab;
      root.querySelectorAll('.calh-tab').forEach(b => b.classList.toggle('active', b === btn));
      paneT.hidden = t !== 'timeline';
      paneP.hidden = t !== 'plan';
      if (t === 'plan') initPlan();
    });

    initTimeline(); // Timeline is the default view
  },
};