(function(){
  'use strict';

  const state = {
    selectedIndex: -1,
    notesByKey: Object.create(null),
    root: {},
    options: {}
  };

  function safe(v){ return v == null ? '' : String(v); }
  function byId(id){ return document.getElementById(id); }
  function getSlots(){
    try {
      const provider = state.options.slotsProvider;
      const slots = typeof provider === 'function' ? provider() : [];
      return Array.isArray(slots) ? slots : [];
    } catch (_) {
      return [];
    }
  }
  function slotKey(slot, idx){
    return safe(slot && (slot.uid || slot.identity || slot.name || slot.label)) || `slot-${idx}`;
  }
  function slotName(slot, idx){
    return safe(slot && (slot.displayName || slot.name || slot.uid || slot.identity)) || `Guest ${idx + 1}`;
  }
  function slotRole(slot, idx){
    const name = slotName(slot, idx).toLowerCase();
    if (name.includes('host')) return 'Host';
    return 'Guest';
  }
  function slotState(slot){
    try {
      if (typeof state.options.getConnState === 'function') return safe(state.options.getConnState(slot)) || 'OFFLINE';
    } catch (_) {}
    return slot && slot.connected ? 'LIVE' : 'OFFLINE';
  }
  function slotMuted(slot){
    try {
      if (typeof state.options.isMuted === 'function') return !!state.options.isMuted(slot);
    } catch (_) {}
    return false;
  }

  function root(name){ return state.root[name] || null; }

  function ensureSelectedIndex(slots){
    if (!slots.length) {
      state.selectedIndex = -1;
      return;
    }
    if (state.selectedIndex < 0 || state.selectedIndex >= slots.length) state.selectedIndex = 0;
  }

  function updateInspector(){
    const slots = getSlots();
    ensureSelectedIndex(slots);
    const slot = slots[state.selectedIndex] || null;

    const nameEl = root('nameEl');
    const roleEl = root('roleEl');
    const talkbackEl = root('talkbackEl');
    const returnEl = root('returnEl');
    const ifbEl = root('ifbEl');
    const notesEl = root('notesEl');

    if (!slot) {
      if (nameEl) nameEl.value = '—';
      if (notesEl) notesEl.value = '';
      return;
    }

    const idx = state.selectedIndex;
    const key = slotKey(slot, idx);
    if (nameEl) nameEl.value = slotName(slot, idx);
    if (roleEl) roleEl.value = slotRole(slot, idx);
    if (talkbackEl && !talkbackEl.value) talkbackEl.value = 'Private';
    if (returnEl && !returnEl.value) returnEl.value = 'Program';
    if (ifbEl && !ifbEl.value) ifbEl.value = '72';
    if (notesEl) notesEl.value = state.notesByKey[key] || '';
  }

  function makeButton(label, action, cls){
    const b = document.createElement('button');
    b.type = 'button';
    b.className = cls || '';
    b.dataset.action = action;
    b.textContent = label;
    return b;
  }

  function render(){
    const grid = root('gridEl');
    if (!grid) return;
    const slots = getSlots();
    ensureSelectedIndex(slots);
    grid.innerHTML = '';

    if (!slots.length) {
      const empty = document.createElement('div');
      empty.className = 'guestStudioCard';
      empty.innerHTML = '<div class="head">No guests yet</div><div class="state">Waiting for participants</div>';
      grid.appendChild(empty);
      updateInspector();
      return;
    }

    slots.forEach((slot, idx) => {
      const card = document.createElement('div');
      card.className = 'guestStudioCard' + (idx === state.selectedIndex ? ' selected' : '');
      card.dataset.guestIndex = String(idx);
      card.dataset.guestKey = slotKey(slot, idx);

      const head = document.createElement('div');
      head.className = 'head';
      head.textContent = slotName(slot, idx);

      const meta = document.createElement('div');
      meta.className = 'state';
      meta.textContent = `${slotState(slot)} • ${slotMuted(slot) ? 'Muted' : 'Ready'}`;

      const row1 = document.createElement('div');
      row1.className = 'row';
      row1.appendChild(makeButton('TB', 'tb', 'tb'));
      row1.appendChild(makeButton('Solo', 'solo', 'solo'));
      row1.appendChild(makeButton('Live', 'live', 'live'));

      const row2 = document.createElement('div');
      row2.className = 'row';
      row2.appendChild(makeButton('Mute', 'mute', 'mute'));
      row2.appendChild(makeButton('Kick', 'kick', 'kick'));
      row2.appendChild(makeButton('Promote', 'promote', 'promote'));

      card.appendChild(head);
      card.appendChild(meta);
      card.appendChild(row1);
      card.appendChild(row2);
      grid.appendChild(card);
    });

    updateInspector();
  }

  function selectGuestStudio(index){
    const slots = getSlots();
    if (!slots.length) {
      state.selectedIndex = -1;
      render();
      return;
    }
    const idx = Number(index);
    state.selectedIndex = Number.isFinite(idx) ? Math.max(0, Math.min(slots.length - 1, idx)) : 0;
    render();
  }

  function selectedSlot(){
    const slots = getSlots();
    ensureSelectedIndex(slots);
    const slot = slots[state.selectedIndex] || null;
    return { slot, index: state.selectedIndex, key: slot ? slotKey(slot, state.selectedIndex) : '' };
  }

  function logAction(action, idx){
    const slots = getSlots();
    const slot = slots[idx] || null;
    const payload = { action, index: idx, key: slot ? slotKey(slot, idx) : '', name: slot ? slotName(slot, idx) : '' };
    console.info('[GuestStudio]', payload);
  }

  function applyInspector(){
    const info = selectedSlot();
    if (!info.slot) return;
    const notesEl = root('notesEl');
    state.notesByKey[info.key] = notesEl ? String(notesEl.value || '') : '';
    console.info('[GuestStudio] apply', {
      guest: info.key,
      name: root('nameEl') ? root('nameEl').value : '',
      role: root('roleEl') ? root('roleEl').value : '',
      talkback: root('talkbackEl') ? root('talkbackEl').value : '',
      returnFeed: root('returnEl') ? root('returnEl').value : '',
      ifb: root('ifbEl') ? root('ifbEl').value : '',
      notes: state.notesByKey[info.key] || ''
    });
  }

  function onGridClick(ev){
    const actionBtn = ev.target.closest('button[data-action]');
    const card = ev.target.closest('.guestStudioCard[data-guest-index]');
    if (!card) return;
    const idx = Number(card.dataset.guestIndex || '-1');
    if (!Number.isFinite(idx) || idx < 0) return;

    if (actionBtn) {
      ev.preventDefault();
      ev.stopPropagation();
      state.selectedIndex = idx;
      const action = actionBtn.dataset.action || '';
      render();
      logAction(action, idx);
      return;
    }

    selectGuestStudio(idx);
  }

  function init(opts){
    state.options = opts || {};
    state.root = {
      gridEl: opts && opts.gridEl ? opts.gridEl : byId('guestStudioGrid'),
      nameEl: opts && opts.nameEl ? opts.nameEl : byId('guestStudioName'),
      roleEl: opts && opts.roleEl ? opts.roleEl : byId('guestStudioRole'),
      talkbackEl: opts && opts.talkbackEl ? opts.talkbackEl : byId('guestStudioTalkback'),
      returnEl: opts && opts.returnEl ? opts.returnEl : byId('guestStudioReturn'),
      ifbEl: opts && opts.ifbEl ? opts.ifbEl : byId('guestStudioIfb'),
      notesEl: opts && opts.notesEl ? opts.notesEl : byId('guestStudioNotes'),
      applyBtn: opts && opts.applyBtn ? opts.applyBtn : byId('btnApplyGuestStudio')
    };

    if (state.root.gridEl && !state.root.gridEl.__guestStudioBound) {
      state.root.gridEl.__guestStudioBound = true;
      state.root.gridEl.addEventListener('click', onGridClick);
    }
    if (state.root.applyBtn && !state.root.applyBtn.__guestStudioBound) {
      state.root.applyBtn.__guestStudioBound = true;
      state.root.applyBtn.addEventListener('click', applyInspector);
    }

    render();
  }

  window.renderGuestStudio = render;
  window.selectGuestStudio = selectGuestStudio;
  window.guestTB = function(index){ logAction('tb', Number(index)); };
  window.guestSolo = function(index){ logAction('solo', Number(index)); };
  window.guestLive = function(index){ logAction('live', Number(index)); };
  window.guestMute = function(index){ logAction('mute', Number(index)); };
  window.guestKick = function(index){ logAction('kick', Number(index)); };
  window.guestPromote = function(index){ logAction('promote', Number(index)); };
  window.GuestStudio = { init, render, select: selectGuestStudio, apply: applyInspector };
})();
