/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 *
 * Container Assignments Module (Phase 2.6 Extraction)
 * Responsibility:
 *  - Load blocks assigned to a container (zone-aware)
 *  - Zone assignment helpers (GET & PUT)
 *  - Assign & remove block
 *  - Build / update schedule & trigger preview rendering
 */

export async function loadContainerBlocks(editor, containerId) {
  try {
    console.debug('[CC] loadContainerBlocks:start', { containerId });
    let data = [];
    const zoneId = editor.getSelectedZoneId ? editor.getSelectedZoneId(containerId) : '';
    if (zoneId) {
      const resp = await fetch(`${castconductorCanvasAjax.rest_url}castconductor/v5/containers/${containerId}/zones/${encodeURIComponent(zoneId)}/assignments`, { method:'GET', headers:{ 'Content-Type':'application/json','X-WP-Nonce':castconductorCanvasAjax.nonce } });
      if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
      data = await resp.json();
    } else {
      const response = await fetch(`${castconductorCanvasAjax.rest_url}castconductor/v5/containers/${containerId}/blocks`, { method:'GET', headers:{ 'Content-Type':'application/json','X-WP-Nonce':castconductorCanvasAjax.nonce } });
      if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
      data = await response.json();
      try { // Lower Third defaults safeguard
        const co = (editor._containersById || {})[String(containerId)] || {}; const pos=(co.position||'').toLowerCase(); const already=!!editor._defaultsAppliedOnce;
        if (pos==='lower_third' && Array.isArray(data) && data.length===0 && !already) {
          editor._defaultsAppliedOnce = true;
          const dResp = await fetch(`${castconductorCanvasAjax.rest_url}castconductor/v5/containers/${containerId}/defaults`, { method:'POST', headers:{ 'Content-Type':'application/json','X-WP-Nonce':castconductorCanvasAjax.nonce }, body: JSON.stringify({ interval:15, mode:'full_reset' }) });
          if (!dResp.ok) {
            const msg = (dResp.status===401||dResp.status===403)?'Defaults apply failed: session expired (401/403). Refresh and retry.':`Defaults apply failed: HTTP ${dResp.status}`;
            editor.showNotification(msg,'error',true);
          }
          const r2 = await fetch(`${castconductorCanvasAjax.rest_url}castconductor/v5/containers/${containerId}/blocks`, { method:'GET', headers:{ 'Content-Type':'application/json','X-WP-Nonce':castconductorCanvasAjax.nonce } });
          if (r2.ok) { data = await r2.json(); editor.showNotification('Lower Third defaults applied for out-of-the-box preview','success'); }
        }
      } catch(_){}
    }
    try { if (Array.isArray(data)) { data.forEach(b => { if (String(b.enabled ?? 1) !== '0' && b.has_config && typeof b.config_version !== 'undefined') { editor.blockConfigVersionIndex[String(b.content_block_id)] = b.config_version; } }); } } catch(_){}
    editor.displayAssignedBlocks(containerId, data);
    editor._assignedBlocksCache = editor._assignedBlocksCache || {}; editor._assignedBlocksCache[String(containerId)] = Array.isArray(data)?data:[];
    editor.buildContainerSchedule(containerId, data, editor.previewShuffle);
    editor.renderContainerPreview(containerId, data);
    const enabled = Array.isArray(data)? data.filter(b => String(b.enabled ?? 1) !== '0') : [];
    if (editor.showContentPreview && enabled.length>1) editor.startContainerPreviewCycle(containerId, data); else editor.stopContainerPreviewCycle(containerId);
    console.debug('[CC] loadContainerBlocks:end', { containerId, assigned: Array.isArray(data)? data.length : 0 });
  } catch (e) {
    console.error('Error loading container blocks:', e);
    editor.showNotification(`Failed to load assignments for container ${editor.escapeHtml(String(containerId))}`,'error');
  }
}

export async function assignBlockToContainer(editor, containerId, blockId, rotationPercentage=25) {
  try {
    const zoneId = editor.getSelectedZoneId ? editor.getSelectedZoneId(containerId) : '';
    const co = (editor._containersById || {})[String(containerId)];
    const hasZones = !!(co && co.layout && Array.isArray(co.layout.zones) && co.layout.zones.length);
    if (hasZones && !zoneId) { editor.showNotification('Select a zone (e.g., Upper Left or Upper Right) before assigning blocks.','warning'); return; }
    if (zoneId) {
      const cur = await getZoneAssignments(editor, containerId, zoneId);
      const order=(cur?.length||0)+1;
      const payload=[...(cur||[]), { content_block_id: parseInt(blockId,10), rotation_percentage: parseFloat(rotationPercentage)||0, rotation_order: order, enabled:1 }];
      await putZoneAssignments(editor, containerId, zoneId, payload);
    } else {
      const response = await fetch(`${castconductorCanvasAjax.rest_url}castconductor/v5/containers/${containerId}/blocks`, { method:'POST', headers:{ 'Content-Type':'application/json','X-WP-Nonce':castconductorCanvasAjax.nonce }, body: JSON.stringify({ block_id: parseInt(blockId,10), rotation_percentage: rotationPercentage, rotation_order:1 }) });
      if (!response.ok) { const errData = await safeJson(response); throw new Error(errData?.message || `HTTP error! status: ${response.status}`); }
      await response.json();
    }
    editor.showNotification('Content block assigned successfully','success');
    await editor.loadContainerBlocks(containerId);
  } catch (e) {
    console.error('Error assigning block to container:', e);
    editor.showNotification(e.message || 'Error assigning content block','error');
  }
}

export async function removeBlockAssignment(editor, containerId, blockId) {
  if (!confirm('Are you sure you want to remove this content block assignment?')) return;
  try {
    const zoneId = editor.getSelectedZoneId ? editor.getSelectedZoneId(containerId) : '';
    if (zoneId) {
      const cur = await getZoneAssignments(editor, containerId, zoneId);
      const next = (cur||[]).filter(x => String(x.content_block_id) !== String(blockId));
      await putZoneAssignments(editor, containerId, zoneId, next);
    } else {
      const resp = await fetch(`${castconductorCanvasAjax.rest_url}castconductor/v5/containers/${containerId}/blocks/${blockId}`, { method:'DELETE', headers:{ 'Content-Type':'application/json','X-WP-Nonce':castconductorCanvasAjax.nonce } });
      if (!resp.ok) throw new Error(`HTTP error! status: ${resp.status}`);
    }
    editor.showNotification('Content block assignment removed','success');
    await editor.loadContainerBlocks(containerId);
  } catch (e) {
    console.error('Error removing block assignment:', e);
    editor.showNotification('Error removing content block assignment','error');
  }
}

export async function getZoneAssignments(editor, containerId, zoneId) {
  const url = `${castconductorCanvasAjax.rest_url}castconductor/v5/containers/${containerId}/zones/${encodeURIComponent(zoneId)}/assignments`;
  const resp = await fetch(url, { method:'GET', headers:{ 'Content-Type':'application/json','X-WP-Nonce':castconductorCanvasAjax.nonce } });
  if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
  const data = await resp.json();
  return Array.isArray(data)? data.map(x => ({ content_block_id: parseInt(x.content_block_id ?? x.block_id ?? 0, 10), rotation_percentage: parseFloat(x.rotation_percentage ?? 0), rotation_order: parseInt(x.rotation_order ?? 0,10), enabled: String(x.enabled ?? 1) === '0' ? 0 : 1, block_name: x.block_name, block_type: x.block_type })) : [];
}

export async function putZoneAssignments(editor, containerId, zoneId, list) {
  const payload = (list||[]).map((x,idx) => ({ block_id: parseInt(x.content_block_id ?? x.block_id ?? 0,10), rotation_percentage: parseFloat(x.rotation_percentage ?? 0), rotation_order: parseInt(x.rotation_order ?? (idx+1),10), enabled: String(x.enabled ?? 1) === '0' ? 0 : 1 }));
  const url = `${castconductorCanvasAjax.rest_url}castconductor/v5/containers/${containerId}/zones/${encodeURIComponent(zoneId)}/assignments`;
  const resp = await fetch(url, { method:'PUT', headers:{ 'Content-Type':'application/json','X-WP-Nonce':castconductorCanvasAjax.nonce }, body: JSON.stringify({ assignments: payload }) });
  if (!resp.ok) { const err = await safeJson(resp); throw new Error(err?.message || `HTTP ${resp.status}`); }
  return true;
}

async function safeJson(resp) { try { return await resp.json(); } catch(_) { return null; } }

export const containerAssignmentsApi = { loadContainerBlocks, assignBlockToContainer, removeBlockAssignment, getZoneAssignments, putZoneAssignments };
