/**
 * Gemeinsamer Snapshot-Overlay-Abschluss (Wake + Deep-Dispose-Reinit).
 * Siehe `PLAN-wake-render-path-vereinheitlichung.md`.
 */

/** Am Wrapper: Snapshot über Live-Canvas — Perspective-PT1 / Pie-Callout-Layout pausieren. */
export const CE_PD_SNAPSHOT_OVERLAY_CLASS = 'ce-diagram-wrapper--snapshot-overlay';

const ORTHO_WAKE_BLEND_FRAMES_PIE = 36;
const ORTHO_WAKE_BLEND_FRAMES_DEFAULT = 28;
const POST_WAKE_PERSP_SOFT_FRAMES_PIE = 20;
const POST_WAKE_PERSP_SOFT_FRAMES_DEFAULT = 14;

/** Ortho-Wake-Blend oder Perspektive: Seed + kurzer Post-Wake-Softblend (PT1). */
export function applyPostSnapshotOverlayCamera(camCtl, state) {
  if (!camCtl || !state) return;
  if (state.isOrthographic) {
    /* Nutzer hat pannt/gezoomt: kein Blend zum „nackten“ Fit-Target (Mitte-Flash). */
    if (state.userHasOrbited) {
      try { camCtl.applyPseudoOrthoPose(); } catch (_) { /* ignore */ }
      return;
    }
    camCtl.beginOrthoWakeCameraBlend(
      state.layout === 'pie' ? ORTHO_WAKE_BLEND_FRAMES_PIE : ORTHO_WAKE_BLEND_FRAMES_DEFAULT,
    );
  } else {
    camCtl.seedPerspectiveSmoothingToCurrentPose();
    camCtl.schedulePostWakePerspSoftBlend(
      (state.layout === 'pie' || state.layout === 'pieStairs' || state.layout === 'pyramid') ? POST_WAKE_PERSP_SOFT_FRAMES_PIE : POST_WAKE_PERSP_SOFT_FRAMES_DEFAULT,
    );
  }
}

export function flashOwnCanvasCompositingLayer(ownCanvas) {
  if (!ownCanvas || !ownCanvas.style) return;
  ownCanvas.style.transform = 'translateZ(0)';
  if (typeof requestAnimationFrame === 'function') {
    requestAnimationFrame(() => { ownCanvas.style.transform = ''; });
  } else {
    ownCanvas.style.transform = '';
  }
}

/**
 * Entfernt Snapshot-<img>s sofort (harter Cut zu Live-Canvas, kein verzögertes Frame-Timing).
 * Overlay-Freeze: `CE_PD_SNAPSHOT_OVERLAY_CLASS` am Wrapper (gesetzt mit Snapshot-DOM).
 *
 * @param {HTMLElement[]} snapshotImgs
 * @param {() => void} [afterRemoved]
 */
export function scheduleSnapshotOverlayDomRemoval(snapshotImgs, afterRemoved) {
  if (snapshotImgs && snapshotImgs.length) {
    for (let i = 0; i < snapshotImgs.length; i++) {
      const el = snapshotImgs[i];
      if (el && el.parentNode) el.parentNode.removeChild(el);
    }
  }
  if (typeof afterRemoved === 'function') {
    try { afterRemoved(); } catch (_) { /* ignore */ }
  }
}
