/**
 * GlucoPlayer — Self-hosted VSL Player v2
 * Zero dependencies, pure HTML5 + JS
 * 
 * v2 Changes:
 * - Controls hidden during playback, show only on click/tap (auto-hide after 3s)
 * - CTA removed from player (placed externally below video)
 * - Fullscreen with Safari/iOS support
 * - Play button starts WITH sound
 */

class GlucoPlayer {
  constructor(containerId, options = {}) {
    this.container = document.getElementById(containerId);
    if (!this.container) {
      console.error(`GlucoPlayer: Container #${containerId} not found`);
      return;
    }

    this.config = {
      src: options.src || '',
      poster: options.poster || '',
      aspectRatio: options.aspectRatio || '16:9',
      autoplay: options.autoplay !== false,
      antiSkip: options.antiSkip || false,
      resumePlayback: options.resumePlayback !== false,
      storageKey: options.storageKey || 'glucoplayer_' + containerId,
      primaryColor: options.primaryColor || '#16a34a',
      controlsTimeout: options.controlsTimeout || 3000,
      onTimeUpdate: options.onTimeUpdate || null,
      onComplete: options.onComplete || null,
    };

    this.state = {
      playing: false,
      muted: false,
      maxWatched: 0,
      duration: 0,
    };

    this._controlsTimer = null;

    this.build();
    this.attachEvents();

    if (this.config.resumePlayback) {
      this.restorePosition();
    }
  }

  // ── Build DOM ────────────────────────────────
  build() {
    const ar = this.config.aspectRatio === '9:16' ? '177.78%' : '56.25%';

    this.container.innerHTML = `
      <div class="gp-wrapper" style="position:relative;width:100%;padding-top:${ar};background:#000;border-radius:10px;overflow:hidden;cursor:pointer;">
        
        <!-- Video -->
        <video class="gp-video" 
          preload="metadata" 
          playsinline 
          webkit-playsinline
          ${this.config.poster ? `poster="${this.config.poster}"` : ''}
          style="position:absolute;top:0;left:0;width:100%;height:100%;object-fit:contain;background:#000;">
          <source src="${this.config.src}" type="video/mp4"/>
        </video>

        <!-- Big Play Button (overlay — shown before first play) -->
        <div class="gp-play-overlay" style="position:absolute;top:0;left:0;width:100%;height:100%;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.35);z-index:5;transition:opacity 0.3s ease;">
          <div class="gp-play-circle" style="width:72px;height:72px;border-radius:50%;background:rgba(255,255,255,0.95);display:grid;place-items:center;box-shadow:0 4px 20px rgba(0,0,0,0.3);transition:transform 0.15s ease;">
            <svg width="28" height="28" viewBox="0 0 24 24" fill="#111" xmlns="http://www.w3.org/2000/svg">
              <polygon points="8,4 20,12 8,20"/>
            </svg>
          </div>
        </div>

        <!-- Controls Bar (hidden by default, shown on click/tap) -->
        <div class="gp-controls" style="
          position:absolute;bottom:0;left:0;right:0;z-index:8;
          background:linear-gradient(transparent, rgba(0,0,0,0.8));
          padding:30px 14px 10px;display:flex;flex-direction:column;gap:6px;
          opacity:0;transition:opacity 0.25s ease;pointer-events:none;
        ">
          <!-- Progress Bar -->
          <div class="gp-progress-wrap" style="
            width:100%;height:5px;background:rgba(255,255,255,0.2);
            border-radius:3px;cursor:pointer;position:relative;
            ${this.config.antiSkip ? 'display:none;' : ''}
          ">
            <div class="gp-progress-bar" style="
              height:100%;width:0%;background:${this.config.primaryColor};
              border-radius:3px;transition:width 0.1s linear;position:relative;
            ">
              <div style="position:absolute;right:-5px;top:-3px;width:11px;height:11px;border-radius:50%;background:#fff;box-shadow:0 1px 4px rgba(0,0,0,0.3);"></div>
            </div>
          </div>

          <!-- Bottom Controls -->
          <div style="display:flex;align-items:center;justify-content:space-between;">
            <div style="display:flex;align-items:center;gap:12px;">
              <!-- Play/Pause -->
              <button class="gp-btn-play" style="background:none;border:0;cursor:pointer;color:#fff;display:grid;place-items:center;padding:4px;">
                <svg class="gp-icon-play" width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><polygon points="6,3 20,12 6,21"/></svg>
                <svg class="gp-icon-pause" width="18" height="18" viewBox="0 0 24 24" fill="currentColor" style="display:none"><rect x="5" y="3" width="4" height="18" rx="1"/><rect x="15" y="3" width="4" height="18" rx="1"/></svg>
              </button>
              <!-- Volume -->
              <button class="gp-btn-mute" style="background:none;border:0;cursor:pointer;color:#fff;display:grid;place-items:center;padding:4px;">
                <svg class="gp-icon-vol" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/></svg>
                <svg class="gp-icon-muted" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:none"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><line x1="23" y1="9" x2="17" y2="15"/><line x1="17" y1="9" x2="23" y2="15"/></svg>
              </button>
              <!-- Time -->
              <span class="gp-time" style="color:rgba(255,255,255,0.7);font-size:12px;font-family:monospace;min-width:90px;">0:00 / 0:00</span>
            </div>
            <!-- Fullscreen -->
            <button class="gp-btn-fs" style="background:none;border:0;cursor:pointer;color:#fff;display:grid;place-items:center;padding:4px;">
              <svg class="gp-icon-expand" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>
              <svg class="gp-icon-shrink" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:none"><polyline points="4 14 10 14 10 20"/><polyline points="20 10 14 10 14 4"/><line x1="14" y1="10" x2="21" y2="3"/><line x1="3" y1="21" x2="10" y2="14"/></svg>
            </button>
          </div>
        </div>

        <!-- Live Badge -->
        <div class="gp-live-badge" style="
          position:absolute;top:12px;left:12px;z-index:8;
          display:inline-flex;align-items:center;gap:5px;
          background:rgba(0,0,0,0.6);backdrop-filter:blur(8px);
          padding:5px 10px;border-radius:6px;
          font-size:11px;color:#fff;font-weight:600;letter-spacing:0.03em;
        ">
          <span style="width:6px;height:6px;border-radius:50%;background:#ef4444;animation:gp-pulse-dot 1.5s ease-in-out infinite;"></span>
          EN DIRECTO
        </div>
      </div>

      <style>
        @keyframes gp-pulse-dot { 0%,100%{opacity:1} 50%{opacity:0.3} }
        .gp-wrapper.gp-playing .gp-play-overlay { opacity:0; pointer-events:none; }
        /* Controls ONLY visible via JS class — no hover */
        .gp-controls { opacity:0 !important; pointer-events:none !important; }
        .gp-wrapper.gp-controls-visible .gp-controls { opacity:1 !important; pointer-events:auto !important; }
        .gp-progress-wrap:hover { height:7px !important; }
        /* Play circle hover only on desktop */
        @media (hover:hover) { .gp-play-circle:hover { transform:scale(1.08); } }
        /* Fullscreen styles */
        .gp-wrapper:fullscreen,
        .gp-wrapper:-webkit-full-screen {
          padding-top: 0 !important;
          width: 100vw !important;
          height: 100vh !important;
          border-radius: 0 !important;
        }
        .gp-wrapper:fullscreen .gp-video,
        .gp-wrapper:-webkit-full-screen .gp-video {
          object-fit: contain !important;
        }
      </style>
    `;

    // Cache elements
    this.wrapper = this.container.querySelector('.gp-wrapper');
    this.video = this.container.querySelector('.gp-video');
    this.overlay = this.container.querySelector('.gp-play-overlay');
    this.controls = this.container.querySelector('.gp-controls');
    this.progressWrap = this.container.querySelector('.gp-progress-wrap');
    this.progressBar = this.container.querySelector('.gp-progress-bar');
    this.btnPlay = this.container.querySelector('.gp-btn-play');
    this.btnMute = this.container.querySelector('.gp-btn-mute');
    this.btnFs = this.container.querySelector('.gp-btn-fs');
    this.timeDisplay = this.container.querySelector('.gp-time');
    this.iconPlay = this.container.querySelector('.gp-icon-play');
    this.iconPause = this.container.querySelector('.gp-icon-pause');
    this.iconVol = this.container.querySelector('.gp-icon-vol');
    this.iconMuted = this.container.querySelector('.gp-icon-muted');
    this.iconExpand = this.container.querySelector('.gp-icon-expand');
    this.iconShrink = this.container.querySelector('.gp-icon-shrink');
  }

  // ── Events ───────────────────────────────────
  attachEvents() {
    // Prevent right-click download
    this.video.addEventListener('contextmenu', e => e.preventDefault());
    this.wrapper.addEventListener('contextmenu', e => e.preventDefault());

    // Play overlay click — always play WITH sound
    this.overlay.addEventListener('click', () => this.playWithSound());

    // Unified click/tap handler for video area
    // On mobile: touchend fires, we use that. On desktop: click fires.
    let touchHandled = false;

    this.video.addEventListener('touchend', e => {
      e.preventDefault(); // prevent ghost click
      touchHandled = true;
      if (!this.state.playing) {
        this.playWithSound();
        return;
      }
      this.toggleControlsVisibility();
    });

    this.video.addEventListener('click', () => {
      // Skip if already handled by touch
      if (touchHandled) { touchHandled = false; return; }
      if (!this.state.playing) {
        this.playWithSound();
        return;
      }
      this.toggleControlsVisibility();
    });

    // Play/Pause button
    this.btnPlay.addEventListener('click', e => { e.stopPropagation(); this.toggle(); });

    // Mute button
    this.btnMute.addEventListener('click', e => { e.stopPropagation(); this.toggleMute(); });

    // Fullscreen
    this.btnFs.addEventListener('click', e => { e.stopPropagation(); this.toggleFullscreen(); });

    // Progress bar seeking
    this.progressWrap.addEventListener('click', e => {
      e.stopPropagation();
      if (this.config.antiSkip && !this.state.ctaShown) return;
      const rect = this.progressWrap.getBoundingClientRect();
      const pct = (e.clientX - rect.left) / rect.width;
      const maxPct = this.state.maxWatched / this.state.duration;
      this.video.currentTime = Math.min(pct, maxPct) * this.state.duration;
    });

    // Time update
    this.video.addEventListener('timeupdate', () => this.onTimeUpdate());

    // Duration loaded
    this.video.addEventListener('loadedmetadata', () => {
      this.state.duration = this.video.duration;
      this.updateTime();
    });

    // Video ended
    this.video.addEventListener('ended', () => {
      this.state.playing = false;
      this.updatePlayIcon();
      this.wrapper.classList.remove('gp-playing');
      this.showControls(); // show controls when ended
      if (this.config.onComplete) this.config.onComplete();
    });



    // Fullscreen change — update icon
    const fsHandler = () => this.updateFullscreenIcon();
    document.addEventListener('fullscreenchange', fsHandler);
    document.addEventListener('webkitfullscreenchange', fsHandler);

    // Save position before unload
    window.addEventListener('beforeunload', () => this.savePosition());

    // Autoplay
    if (this.config.autoplay) {
      this.autoplay();
    }
  }

  // ── Controls Visibility ─────────────────────
  showControls() {
    this.wrapper.classList.add('gp-controls-visible');
    this._scheduleHideControls();
  }

  hideControls() {
    this.wrapper.classList.remove('gp-controls-visible');
  }

  toggleControlsVisibility() {
    if (this.wrapper.classList.contains('gp-controls-visible')) {
      this.hideControls();
      clearTimeout(this._controlsTimer);
    } else {
      this.showControls();
    }
  }

  _scheduleHideControls() {
    clearTimeout(this._controlsTimer);
    if (this.state.playing) {
      this._controlsTimer = setTimeout(() => {
        this.hideControls();
      }, this.config.controlsTimeout);
    }
  }

  // ── Playback Controls ────────────────────────
  // User-initiated play — always WITH sound
  async playWithSound() {
    this.video.muted = false;
    this.state.muted = false;
    try {
      await this.video.play();
      this.state.playing = true;
    } catch {
      this.video.muted = true;
      this.state.muted = true;
      try {
        await this.video.play();
        this.state.playing = true;
      } catch { /* give up */ }
    }
    this.updatePlayIcon();
    this.updateMuteIcon();
    this.wrapper.classList.add('gp-playing');
    this.hideControls(); // hide controls when playing starts
  }

  async play() {
    this.video.muted = false;
    this.state.muted = false;
    try {
      await this.video.play();
      this.state.playing = true;
    } catch { /* ignore */ }
    this.updatePlayIcon();
    this.updateMuteIcon();
    this.wrapper.classList.add('gp-playing');
    this.hideControls();
  }

  pause() {
    this.video.pause();
    this.state.playing = false;
    this.updatePlayIcon();
    this.showControls(); // show controls when paused
  }

  toggle() {
    this.state.playing ? this.pause() : this.play();
  }

  toggleMute() {
    this.video.muted = !this.video.muted;
    this.state.muted = this.video.muted;
    this.updateMuteIcon();
    this._scheduleHideControls();
  }

  toggleFullscreen() {
    const el = this.wrapper;
    if (document.fullscreenElement || document.webkitFullscreenElement) {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
      }
    } else {
      if (el.requestFullscreen) {
        el.requestFullscreen();
      } else if (el.webkitRequestFullscreen) {
        el.webkitRequestFullscreen();
      } else if (this.video.webkitEnterFullscreen) {
        // iOS Safari fallback — uses native video fullscreen
        this.video.webkitEnterFullscreen();
      }
    }
    this._scheduleHideControls();
  }

  async autoplay() {
    this.video.muted = false;
    try {
      await this.video.play();
      this.state.playing = true;
      this.state.muted = false;
    } catch {
      this.video.muted = true;
      this.state.muted = true;
      try {
        await this.video.play();
        this.state.playing = true;
      } catch {
        return;
      }
    }
    this.updatePlayIcon();
    this.updateMuteIcon();
    this.wrapper.classList.add('gp-playing');
    this.hideControls();
  }

  // ── Time Update Handler ──────────────────────
  onTimeUpdate() {
    const t = this.video.currentTime;
    const d = this.video.duration || 1;

    if (t > this.state.maxWatched) {
      this.state.maxWatched = t;
    }

    this.progressBar.style.width = (t / d * 100) + '%';
    this.updateTime();

    if (this.config.onTimeUpdate) {
      this.config.onTimeUpdate(t, d);
    }

    if (Math.floor(t) % 10 === 0) {
      this.savePosition();
    }
  }

  // ── UI Updates ───────────────────────────────
  updatePlayIcon() {
    this.iconPlay.style.display = this.state.playing ? 'none' : 'block';
    this.iconPause.style.display = this.state.playing ? 'block' : 'none';
  }

  updateMuteIcon() {
    this.iconVol.style.display = this.state.muted ? 'none' : 'block';
    this.iconMuted.style.display = this.state.muted ? 'block' : 'none';
  }

  updateFullscreenIcon() {
    const isFs = !!(document.fullscreenElement || document.webkitFullscreenElement);
    this.iconExpand.style.display = isFs ? 'none' : 'block';
    this.iconShrink.style.display = isFs ? 'block' : 'none';
  }

  updateTime() {
    const fmt = s => {
      const m = Math.floor(s / 60);
      const sec = Math.floor(s % 60);
      return m + ':' + String(sec).padStart(2, '0');
    };
    this.timeDisplay.textContent = fmt(this.video.currentTime) + ' / ' + fmt(this.video.duration || 0);
  }

  // ── Resume Playback ──────────────────────────
  savePosition() {
    if (!this.config.resumePlayback) return;
    try {
      localStorage.setItem(this.config.storageKey, JSON.stringify({
        time: this.video.currentTime,
        max: this.state.maxWatched,
      }));
    } catch {}
  }

  restorePosition() {
    try {
      const saved = JSON.parse(localStorage.getItem(this.config.storageKey));
      if (saved && saved.time > 5) {
        this.video.currentTime = saved.time;
        this.state.maxWatched = saved.max || saved.time;
      }
    } catch {}
  }

  // ── Public API ───────────────────────────────
  destroy() {
    this.savePosition();
    this.video.pause();
    this.container.innerHTML = '';
  }

  setSource(src) {
    this.video.querySelector('source').src = src;
    this.video.load();
  }
}

if (typeof module !== 'undefined') {
  module.exports = GlucoPlayer;
}
