// Scenes Containers Panel: assign/order containers per scene with per-scene geometry/rotation overrides
import { getScene as apiGetScene, getSceneContainers as apiGetSceneContainers, putSceneContainers as apiPutSceneContainers } from './scenes-api.js';

export function attachScenesContainersPanel(editor) {
  if (editor.__scenesContainersPanelAttached) return;
  editor.__scenesContainersPanelAttached = true;

  editor.openSceneContainersPanel = async function openSceneContainersPanel(sceneId) {
    try {
      if (!editor.showModal) return;
      const sid = parseInt(sceneId, 10);
      if (!sid) { editor.showNotification && editor.showNotification('No scene selected', 'warning'); return; }

      // Load scene basics and current mappings
      const [sceneResp, mapResp] = await Promise.all([
        apiGetScene(sid), apiGetSceneContainers(sid)
      ]);
      const scene = (sceneResp && sceneResp.data) || {};
      const mappings = Array.isArray(mapResp && mapResp.data) ? mapResp.data : [];

      // Fetch available containers from cache or server
      let containers = [];
      try {
        if (Array.isArray(editor._containers)) containers = editor._containers;
        else if (typeof editor.fetchAndRenderContainers == 'function') {
          await editor.fetchAndRenderContainers();
          containers = editor._containers || [];
        }
      } catch (_) {}

      // Build rows with checkbox + geometry/rotation override inputs
      const mapById = {};
      mappings.forEach(m => { mapById[String(m.container_id)] = m; });
      const rows = containers.map((c, idx) => {
        const m = mapById[String(c.id)] || {};
        const enabled = (typeof m.enabled !== 'undefined') ? (String(m.enabled) !== '0') : true;
        let ov = {};
        try {
          ov = (m.overrides && typeof m.overrides === 'string') ? JSON.parse(m.overrides) : (m.overrides || {});
        } catch(_) { ov = {}; }
        const x = Number.isFinite(parseInt(ov.x_position ?? c.x_position ?? 0, 10)) ? parseInt(ov.x_position ?? c.x_position ?? 0, 10) : 0;
        const y = Number.isFinite(parseInt(ov.y_position ?? c.y_position ?? 0, 10)) ? parseInt(ov.y_position ?? c.y_position ?? 0, 10) : 0;
        const w = Number.isFinite(parseInt(ov.width ?? c.width ?? 0, 10)) ? parseInt(ov.width ?? c.width ?? 0, 10) : 0;
        const h = Number.isFinite(parseInt(ov.height ?? c.height ?? 0, 10)) ? parseInt(ov.height ?? c.height ?? 0, 10) : 0;
        const z = Number.isFinite(parseInt(ov.z_index ?? c.z_index ?? (100 + idx), 10)) ? parseInt(ov.z_index ?? c.z_index ?? (100 + idx), 10) : (100 + idx);
        const rotEnabled = (ov.rotation_enabled ?? c.rotation_enabled ?? true) ? true : false;
        const rotInt = Number.isFinite(parseInt(ov.rotation_interval ?? c.rotation_interval ?? 30, 10)) ? parseInt(ov.rotation_interval ?? c.rotation_interval ?? 30, 10) : 30;
        return `
          <tr data-container-id="${editor.escapeHtml(String(c.id))}">
            <td><input type="checkbox" class="sc-enabled" ${enabled ? 'checked' : ''}></td>
            <td>${editor.escapeHtml(c.name || ('Container #' + c.id))}</td>
            <td class="num"><input type="number" class="sc-x" min="0" step="1" value="${x}" title="x (px)"></td>
            <td class="num"><input type="number" class="sc-y" min="0" step="1" value="${y}" title="y (px)"></td>
            <td class="num"><input type="number" class="sc-w" min="1" step="1" value="${w}" title="width (px)"></td>
            <td class="num"><input type="number" class="sc-h" min="1" step="1" value="${h}" title="height (px)"></td>
            <td class="num"><input type="number" class="sc-z" step="1" value="${z}" title="z-index"></td>
            <td class="num"><input type="number" class="sc-rot-int" min="1" step="1" value="${rotInt}" title="rotation interval (sec)"></td>
            <td><input type="checkbox" class="sc-rot-enabled" ${rotEnabled ? 'checked' : ''} title="rotation enabled"></td>
          </tr>
        `;
      }).join('');

      const body = `
        <div class="scenes-containers-panel">
          <div class="sc-header">Scene Containers — ${editor.escapeHtml(scene.name || ('#'+sid))}</div>
          <div class="sc-help">Enable containers and set per-scene geometry/rotation overrides. Save to apply.</div>
          <table class="sc-table">
            <thead>
              <tr>
                <th>Enable</th>
                <th>Container</th>
                <th>X</th>
                <th>Y</th>
                <th>W</th>
                <th>H</th>
                <th>Z</th>
                <th>Rot (s)</th>
                <th>Rot On</th>
              </tr>
            </thead>
            <tbody>${rows || '<tr><td colspan="9">No containers found</td></tr>'}</tbody>
          </table>
          <div class="sc-actions">
            <button type="button" id="sc-cancel">Cancel</button>
            <button type="button" class="primary" id="sc-save">Save</button>
          </div>
        </div>
      `;

      editor.showModal('Scene Containers…', body);
      const modal = document.getElementById('canvas-editor-modal');
      modal?.querySelector('#sc-cancel')?.addEventListener('click', () => editor.closeModal());
      modal?.querySelector('#sc-save')?.addEventListener('click', async () => {
        try {
          const payload = [];
          modal.querySelectorAll('tbody tr').forEach(tr => {
            const id = parseInt(tr.getAttribute('data-container-id'), 10);
            const enabled = !!tr.querySelector('.sc-enabled')?.checked;
            const x = parseInt(tr.querySelector('.sc-x')?.value || '0', 10) || 0;
            const y = parseInt(tr.querySelector('.sc-y')?.value || '0', 10) || 0;
            const w = Math.max(1, parseInt(tr.querySelector('.sc-w')?.value || '0', 10) || 0);
            const h = Math.max(1, parseInt(tr.querySelector('.sc-h')?.value || '0', 10) || 0);
            const z = parseInt(tr.querySelector('.sc-z')?.value || '0', 10) || 0;
            const rotInt = Math.max(1, parseInt(tr.querySelector('.sc-rot-int')?.value || '0', 10) || 0);
            const rotOn = !!tr.querySelector('.sc-rot-enabled')?.checked;
            if (id) payload.push({
              container_id: id,
              enabled,
              overrides: {
                x_position: x,
                y_position: y,
                width: w,
                height: h,
                z_index: z,
                rotation_enabled: rotOn,
                rotation_interval: rotInt
              },
              zones: {}
            });
          });
          // Sort by z-index asc, then stable by id for deterministic upserts
          payload.sort((a,b)=> (a.overrides.z_index - b.overrides.z_index) || (a.container_id - b.container_id));
          await apiPutSceneContainers(sid, payload);
          editor.showNotification && editor.showNotification('Scene containers saved','success');
          editor.closeModal();
          try { await editor.generatePreview?.(); } catch(_) {}
        } catch (e) {
          console.warn('[ScenesContainers] save failed', e);
          editor.showNotification && editor.showNotification('Failed to save scene containers','error');
        }
      });
    } catch (e) {
      console.warn('[ScenesContainers] open panel failed', e);
      editor.showNotification && editor.showNotification('Failed to open Scene Containers','error');
    }
  };
}
