/**
 * VideoGen — Peak Platform Video Generator
 * Runway ML Agent-style interface controller
 */
class VideoGen {
  constructor() {
    // Elements
    this.canvas = document.getElementById('rwCanvas');
    this.placeholder = document.getElementById('rwPlaceholder');
    this.intro = document.getElementById('rwIntro');
    this.introVideo = document.getElementById('introVideo');
    this.resultVideo = document.getElementById('resultVideo');
    this.loading = document.getElementById('rwLoading');
    this.loadingText = document.getElementById('loadingText');
    this.loadingBar = document.getElementById('loadingBar');
    this.prompt = document.getElementById('videoPrompt');
    this.generateBtn = document.getElementById('generateBtn');
    this.charCount = document.getElementById('charCount');
    this.toast = document.getElementById('rwToast');
    this.sidebar = document.getElementById('rwSidebar');
    this.sidebarToggle = document.getElementById('sidebarToggle');
    this.sidebarOpenBtn = document.getElementById('sidebarOpenBtn');
    this.durationSlider = document.getElementById('videoDuration');
    this.durationVal = document.getElementById('durationVal');
    this.historyScroll = document.getElementById('historyScroll');
    this.historyEmpty = document.getElementById('historyEmpty');
    this.historyClear = document.getElementById('historyClear');
    this.refImageInput = document.getElementById('refImageInput');
    this.refImagePreview = document.getElementById('refImagePreview');
    this.refImageImg = document.getElementById('refImageImg');
    this.refImageClear = document.getElementById('refImageClear');

    this.history = [];
    this.isGenerating = false;

    this.init();
  }

  init() {
    // Prompt input
    this.prompt.addEventListener('input', () => this.onPromptInput());
    this.prompt.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        this.generate();
      }
    });

    // Generate
    this.generateBtn.addEventListener('click', () => this.generate());

    // Sidebar
    this.sidebarToggle.addEventListener('click', () => this.toggleSidebar());
    this.sidebarOpenBtn.addEventListener('click', () => this.openSidebar());

    // Aspect Ratio
    document.querySelectorAll('.rw-aspect-btn').forEach(btn => {
      btn.addEventListener('click', () => this.setAspectRatio(btn));
    });

    // Camera Motion
    document.querySelectorAll('.rw-camera-btn[data-motion]').forEach(btn => {
      btn.addEventListener('click', () => this.setCameraMotion(btn));
    });

    // Duration
    this.durationSlider.addEventListener('input', () => {
      this.durationVal.textContent = this.durationSlider.value + 's';
    });

    // History clear
    this.historyClear.addEventListener('click', () => this.clearHistory());

    // Ref image
    this.refImageInput.addEventListener('change', (e) => this.onRefImage(e));
    this.refImageClear.addEventListener('click', () => this.clearRefImage());

    // Download & fullscreen
    document.getElementById('btnDownload').addEventListener('click', () => this.downloadVideo());
    document.getElementById('btnFullscreen').addEventListener('click', () => this.fullscreenVideo());

    // Auto-resize textarea
    this.autoResize();
  }

  onPromptInput() {
    const len = this.prompt.value.length;
    this.charCount.textContent = len + '/1000';
    this.autoResize();
  }

  autoResize() {
    this.prompt.style.height = 'auto';
    this.prompt.style.height = Math.min(this.prompt.scrollHeight, 120) + 'px';
  }

  toggleSidebar() {
    this.sidebar.classList.toggle('collapsed');
    if (window.innerWidth <= 900) {
      this.sidebar.classList.toggle('mobile-open');
    }
  }

  openSidebar() {
    this.sidebar.classList.remove('collapsed');
    if (window.innerWidth <= 900) {
      this.sidebar.classList.add('mobile-open');
    }
  }

  setAspectRatio(btn) {
    document.querySelectorAll('.rw-aspect-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    const ratio = btn.dataset.ratio;
    this.canvas.className = 'rw-canvas';
    if (ratio === '16:9') this.canvas.classList.add('ar-16-9');
    else if (ratio === '1:1') this.canvas.classList.add('ar-1-1');
    else if (ratio === '9:16') this.canvas.classList.add('ar-9-16');
    if (this.resultVideo.style.display !== 'none') {
      this.canvas.classList.add('has-video');
    }
  }

  setCameraMotion(btn) {
    document.querySelectorAll('.rw-camera-btn[data-motion]').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
  }

  onRefImage(e) {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
      this.refImageImg.src = ev.target.result;
      this.refImagePreview.style.display = 'block';
      document.getElementById('refImageLabel').style.display = 'none';
    };
    reader.readAsDataURL(file);
  }

  clearRefImage() {
    this.refImageInput.value = '';
    this.refImagePreview.style.display = 'none';
    document.getElementById('refImageLabel').style.display = 'flex';
  }

  showToast(msg, duration = 4000) {
    this.toast.textContent = msg;
    this.toast.classList.add('active');
    setTimeout(() => this.toast.classList.remove('active'), duration);
  }

  generate() {
    const text = this.prompt.value.trim();
    if (!text) {
      this.showToast('Please describe the video you want to create');
      return;
    }
    if (this.isGenerating) return;

    this.isGenerating = true;
    this.generateBtn.disabled = true;

    // Hide placeholder/intro, show loading
    this.placeholder.style.display = 'none';
    if (this.intro) this.intro.style.display = 'none';
    this.resultVideo.style.display = 'none';
    this.canvas.classList.remove('has-video');
    this.loading.classList.add('active');
    this.loadingBar.style.animation = 'none';
    void this.loadingBar.offsetWidth;
    this.loadingBar.style.animation = '';

    // Simulate generation stages
    const stages = [
      { text: 'Analyzing prompt...', delay: 1500 },
      { text: 'Building scene composition...', delay: 2500 },
      { text: 'Rendering frames...', delay: 3000 },
      { text: 'Applying motion dynamics...', delay: 2000 },
      { text: 'Finalizing video...', delay: 1500 }
    ];

    let totalDelay = 0;
    stages.forEach((stage, i) => {
      totalDelay += stage.delay;
      setTimeout(() => {
        this.loadingText.textContent = stage.text;
      }, totalDelay - stage.delay);
    });

    // After "generation" completes, show a demo result
    setTimeout(() => {
      this.loading.classList.remove('active');
      this.isGenerating = false;
      this.generateBtn.disabled = false;

      // Show placeholder video result (demo)
      this.showDemoResult(text);
    }, totalDelay + 500);
  }

  showDemoResult(promptText) {
    // For now, show a placeholder canvas with the prompt text
    // When real API is connected, this will show actual generated video
    this.placeholder.style.display = 'none';
    this.resultVideo.style.display = 'none';

    // Create a canvas-based demo
    const demoCanvas = document.createElement('canvas');
    const ctx = demoCanvas.getContext('2d');
    demoCanvas.width = 1280;
    demoCanvas.height = 720;

    // Dark gradient background
    const grad = ctx.createLinearGradient(0, 0, 1280, 720);
    grad.addColorStop(0, '#0a0a2e');
    grad.addColorStop(0.5, '#1a0a3e');
    grad.addColorStop(1, '#0a1a2e');
    ctx.fillStyle = grad;
    ctx.fillRect(0, 0, 1280, 720);

    // Decorative circles
    for (let i = 0; i < 20; i++) {
      ctx.beginPath();
      ctx.arc(
        Math.random() * 1280,
        Math.random() * 720,
        Math.random() * 80 + 20,
        0, Math.PI * 2
      );
      ctx.fillStyle = `rgba(${100 + Math.random()*155}, ${50 + Math.random()*100}, ${200 + Math.random()*55}, ${0.05 + Math.random()*0.1})`;
      ctx.fill();
    }

    // Text
    ctx.fillStyle = '#ffffff';
    ctx.font = 'bold 28px Inter, sans-serif';
    ctx.textAlign = 'center';
    ctx.fillText('Video Generated Successfully', 640, 320);
    ctx.font = '16px Inter, sans-serif';
    ctx.fillStyle = 'rgba(255,255,255,0.5)';
    const truncated = promptText.length > 80 ? promptText.slice(0, 80) + '...' : promptText;
    ctx.fillText('"' + truncated + '"', 640, 360);
    ctx.font = '13px Inter, sans-serif';
    ctx.fillStyle = 'rgba(255,255,255,0.3)';
    ctx.fillText('Connect your video API to generate real videos', 640, 400);

    // Convert to video-like display using an image
    const imgUrl = demoCanvas.toDataURL('image/png');
    
    // Show as image in canvas
    let demoImg = this.canvas.querySelector('.rw-demo-result');
    if (!demoImg) {
      demoImg = document.createElement('img');
      demoImg.className = 'rw-demo-result';
      demoImg.style.cssText = 'width:100%;height:100%;object-fit:cover;border-radius:11px;';
      this.canvas.appendChild(demoImg);
    }
    demoImg.src = imgUrl;
    demoImg.style.display = 'block';
    this.canvas.classList.add('has-video');

    // Add to history
    this.addToHistory(imgUrl, promptText);
  }

  addToHistory(thumbUrl, prompt) {
    this.historyEmpty.style.display = 'none';
    const duration = this.durationSlider.value;

    const item = document.createElement('div');
    item.className = 'rw-history-item';
    item.innerHTML = `
      <img src="${thumbUrl}" alt="${prompt.slice(0,30)}">
      <span class="rw-history-duration">${duration}s</span>
    `;
    item.addEventListener('click', () => {
      // Show this history item in canvas
      let demoImg = this.canvas.querySelector('.rw-demo-result');
      if (!demoImg) {
        demoImg = document.createElement('img');
        demoImg.className = 'rw-demo-result';
        demoImg.style.cssText = 'width:100%;height:100%;object-fit:cover;border-radius:11px;';
        this.canvas.appendChild(demoImg);
      }
      demoImg.src = thumbUrl;
      demoImg.style.display = 'block';
      this.placeholder.style.display = 'none';
      this.resultVideo.style.display = 'none';
      this.canvas.classList.add('has-video');
      document.querySelectorAll('.rw-history-item').forEach(h => h.classList.remove('active'));
      item.classList.add('active');
    });

    this.historyScroll.insertBefore(item, this.historyScroll.firstChild);
    this.history.push({ thumb: thumbUrl, prompt, duration });

    // Activate this item
    document.querySelectorAll('.rw-history-item').forEach(h => h.classList.remove('active'));
    item.classList.add('active');
  }

  clearHistory() {
    this.historyScroll.innerHTML = '';
    this.historyEmpty.style.display = '';
    this.historyScroll.appendChild(this.historyEmpty);
    this.history = [];
  }

  downloadVideo() {
    const demoImg = this.canvas.querySelector('.rw-demo-result');
    if (demoImg && demoImg.src) {
      const a = document.createElement('a');
      a.href = demoImg.src;
      a.download = 'peak-ai-video.png';
      a.click();
    } else {
      this.showToast('No video to download');
    }
  }

  fullscreenVideo() {
    if (this.canvas.requestFullscreen) {
      this.canvas.requestFullscreen();
    } else if (this.canvas.webkitRequestFullscreen) {
      this.canvas.webkitRequestFullscreen();
    }
  }
}

// Initialize
document.addEventListener('DOMContentLoaded', () => {
  new VideoGen();
});
