import { bindNativeTitleDismissOnTouch } from './nativeTitleTouchDismiss.js';

/**
 * 2D/3D-Projection-Toggle (Cinematic-Cheat).
 *
 * Bindet den Toggle-Button in der Top-Actions-Leiste an den Camera-Controller. Der
 * eigentliche Kamera-Tween läuft in `cameraController.tweenToProjection()`; diese
 * Datei ist nur der UI-Adapter (Button-Lookup, aria-pressed/aria-label/title/label-
 * Swap, Re-Entrancy-Guard, Reduced-Motion-Opt-out).
 *
 * Semantik: der Button zeigt — Label und Icon — das ZIEL des nächsten Klicks.
 *   Chart aktuell 3D → beschriftet „Flat view“ / zu orthographisch.
 *   Chart aktuell 2D → beschriftet „Perspective“ / zu perspektivisch.
 */

export function createProjectionToggle(ctx) {
  const { wrapper, state, camCtl } = ctx;
  if (!wrapper || !camCtl) return null;

  const btn = wrapper.querySelector('.ce-diagram-projection-btn');
  /* Button wird serverseitig nur für toggelbare Layouts (≠ arc, surface) gerendert —
   * fehlt er, hat dieser Controller nichts zu tun. */
  if (!btn) return null;

  const labelEl = btn.querySelector('.ce-diagram-expand-btn__label');
  const labelTo2d = btn.getAttribute('data-i18n-to-2d') || 'Switch to 2D view';
  const labelTo3d = btn.getAttribute('data-i18n-to-3d') || 'Switch to 3D view';
  const textFlat = btn.getAttribute('data-i18n-flat-view') || 'Flat view';
  const textPerspective = btn.getAttribute('data-i18n-perspective') || 'Perspective';

  function readTweenDurationMs() {
    try {
      const raw = getComputedStyle(wrapper).getPropertyValue('--ce-diagram-projection-tween-ms');
      const n = Number.parseFloat(String(raw).trim());
      if (Number.isFinite(n) && n >= 0) return n;
    } catch (_) { /* ignore */ }
    return 800;
  }

  function prefersReducedMotion() {
    try {
      return window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    } catch (_) { return false; }
  }

  function updateButtonUI(isNow2d) {
    btn.setAttribute('aria-pressed', isNow2d ? 'true' : 'false');
    const label = isNow2d ? labelTo3d : labelTo2d;
    btn.setAttribute('aria-label', label);
    btn.setAttribute('title', label);
    if (labelEl) labelEl.textContent = isNow2d ? textPerspective : textFlat;
  }

  /* Re-Entrancy-Guard: verhindert einen zweiten Klick, solange der Tween läuft.
   * Zusätzlich belastbar via camCtl.isProjectionTweening(), falls der Button in
   * exotischen Flows dupliziert angelegt würde. */
  let isBusy = false;

  function onClick(e) {
    e.preventDefault();
    if (isBusy || camCtl.isProjectionTweening()) return;
    const currentlyOrtho = !!state.isOrthographic;
    const target = currentlyOrtho ? '3d' : '2d';
    const durationMs = prefersReducedMotion() ? 0 : readTweenDurationMs();
    isBusy = true;
    camCtl.tweenToProjection(target, {
      durationMs,
      onComplete: () => {
        isBusy = false;
        updateButtonUI(target === '2d');
      },
    });
  }

  btn.addEventListener('click', onClick);
  bindNativeTitleDismissOnTouch(btn);

  /* Initial-State spiegeln (falls state.isOrthographic beim Init != aria-pressed). */
  updateButtonUI(!!state.isOrthographic);

  function destroy() {
    btn.removeEventListener('click', onClick);
  }

  return { destroy, button: btn };
}
