/*!
 * SmartposPromoDirector — orquestador de escenas con timeline GSAP.
 */
(function () {
  'use strict';
  var gsap = window.gsap;

  function Director(opts) {
    this.scenes   = opts.scenes;
    this.progress = opts.progress;
    this.stage    = opts.stage;
    this.audio    = opts.audio;
    this.onEnd    = opts.onEnd || function () {};
    this.base     = opts.base || '/promo/';

    this.order = ['intro', 'hacer', 'reportar', 'explicar', 'cta'];
    this.current = -1;
    this._startTime = 0;
    this._pausedAt  = 0;
    this._totalDur = 0;
    this._destroyed = false;
    this._paused = false;

    var self = this;
    this.order.forEach(function (k) {
      var s = window['SmartposPromoScene_' + k];
      if (s) self._totalDur += s.duration || 0;
    });
  }

  Director.prototype.start = function () {
    var self = this;
    this._startTime = performance.now();
    this._tickProgress();
    this._runScene(0);
  };

  Director.prototype._tickProgress = function () {
    var self = this;
    if (this._destroyed) return;
    if (this._paused) { requestAnimationFrame(function () { self._tickProgress(); }); return; }
    var elapsed = performance.now() - this._startTime;
    var pct = Math.min(100, (elapsed / this._totalDur) * 100);
    if (this.progress) this.progress.style.width = pct.toFixed(1) + '%';
    requestAnimationFrame(function () { self._tickProgress(); });
  };

  Director.prototype.pause  = function () {
    if (this._paused) return;
    this._paused = true;
    this._pausedAt = performance.now();
    // Pausar timer de avance de escena
    if (this._holdTimer) {
      clearTimeout(this._holdTimer);
      this._holdTimer = null;
      this._holdRemaining = Math.max(0, this._holdEndsAt - this._pausedAt);
    }
    if (window.gsap) gsap.globalTimeline.pause();
    if (this.audio && !this.audio.paused) { try { this.audio.pause(); } catch (e) {} this._audioWasPlaying = true; }
  };
  Director.prototype.resume = function () {
    if (!this._paused) return;
    var now = performance.now();
    this._startTime += (now - this._pausedAt);
    this._paused = false;
    if (window.gsap) gsap.globalTimeline.resume();
    if (this._audioWasPlaying && this.audio) { try { this.audio.play().catch(function(){}); } catch (e) {} this._audioWasPlaying = false; }
    // Reprogramar avance de escena
    if (this._holdRemaining != null && this._holdCallback) {
      var cb = this._holdCallback;
      var rem = this._holdRemaining;
      this._holdRemaining = null;
      this._holdEndsAt = now + rem;
      var self = this;
      this._holdTimer = setTimeout(function () { cb(); }, rem);
    }
  };

  Director.prototype._runScene = function (idx) {
    var self = this;
    if (this._destroyed) return;
    if (idx >= this.order.length) { this.onEnd(); return; }

    this.current = idx;
    var key = this.order[idx];
    var def = window['SmartposPromoScene_' + key];
    var el  = this.scenes[key];
    if (!def || !el) { this._runScene(idx + 1); return; }

    var ctx = { stage: this.stage, audio: this.audio, base: this.base };
    var enterTl = def.enter(el, ctx);
    var dur = def.duration || 6000;

    // Salida un poco antes del final para crossfade
    var holdMs = Math.max(500, dur - 600);
    this._holdCallback = function () {
      if (self._destroyed) return;
      if (idx === self.order.length - 1) {
        // CTA: no salir, queda visible hasta cerrar
        return;
      }
      var exitRet = def.exit ? def.exit(el, ctx) : null;
      setTimeout(function () { self._runScene(idx + 1); }, 350);
    };
    this._holdEndsAt = performance.now() + holdMs;
    this._holdTimer = setTimeout(this._holdCallback, holdMs);
  };

  Director.prototype.elapsed = function () {
    return (performance.now() - this._startTime) / 1000;
  };

  Director.prototype.skipToCTA = function () {
    if (this._destroyed) return;
    clearTimeout(this._holdTimer);
    var self = this;
    // Apagar escena actual rápido y saltar a CTA
    this.order.forEach(function (k, i) {
      var el = self.scenes[k];
      if (el && i !== self.order.length - 1) gsap.to(el, { opacity: 0, duration: 0.25 });
    });
    this._runScene(this.order.length - 1);
  };

  Director.prototype.replay = function () {
    if (this._destroyed) return;
    clearTimeout(this._holdTimer);
    var self = this;
    this.order.forEach(function (k) {
      var el = self.scenes[k];
      if (el) { el.style.opacity = 0; el.innerHTML = ''; }
    });
    this._startTime = performance.now();
    if (this.audio && !this.audio.muted) {
      try { this.audio.currentTime = 0; this.audio.play().catch(function(){}); } catch (e) {}
    }
    this._runScene(0);
  };

  Director.prototype.destroy = function () {
    this._destroyed = true;
    clearTimeout(this._holdTimer);
  };

  window.SmartposPromoDirector = Director;
})();
