'use client';

/**
 * CMS YouTube Video — mirrors cms-element-youtube-video.html.twig
 *
 * Supported config fields (Shopware admin "Element settings"):
 *   videoID            : YouTube video ID
 *   iframeTitle        : accessible title for the iframe
 *   autoPlay           : boolean — play automatically
 *   loop               : boolean — play in a loop
 *   showControls       : boolean — show player controls (default true)
 *   advancedPrivacyMode: boolean — use youtube-nocookie.com
 *   start              : string  — start time, e.g. "2:00" or seconds
 *   end                : string  — end time, e.g. "2:02" or seconds
 *   displayMode        : 'standard' (Original) | 'cover' (Scaled)
 *   needsConfirmation  : boolean — show consent overlay before loading
 */

import { useState } from 'react';
import type { CmsSlot } from '@/components/cms/types';

// ─── Helpers ─────────────────────────────────────────────────────────────────

/** Convert "m:ss" or plain number-string to total seconds, or undefined if blank/invalid. */
function toSeconds(raw: string | number | undefined | null): number | undefined {
  if (raw == null || raw === '') return undefined;
  const s = String(raw).trim();
  if (!s) return undefined;
  if (s.includes(':')) {
    const parts = s.split(':').map(Number);
    if (parts.length === 2) return parts[0] * 60 + parts[1];
    if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  }
  const n = Number(s);
  return isNaN(n) ? undefined : n;
}

// ─── Component ────────────────────────────────────────────────────────────────

export default function CmsElementYoutubeVideo({ slot }: { slot: CmsSlot }) {
  const cfg = slot.config ?? {};

  const videoId         = cfg.videoID?.value      ?? slot.data?.videoId ?? '';
  const iframeTitle     = cfg.iframeTitle?.value  ?? 'YouTube video';
  const autoPlay        = cfg.autoPlay?.value      ?? false;
  const loop            = cfg.loop?.value          ?? false;
  const showControls    = cfg.showControls?.value  ?? true;
  const privacyMode     = cfg.advancedPrivacyMode?.value ?? true;
  const needsConfirm    = cfg.needsConfirmation?.value   ?? false;
  const displayMode     = cfg.displayMode?.value   ?? 'standard';

  const startSec = toSeconds(cfg.start?.value);
  const endSec   = toSeconds(cfg.end?.value);

  const [confirmed, setConfirmed] = useState(!needsConfirm);

  if (!videoId) return null;

  // ── Build embed URL ────────────────────────────────────────────────────────
  const base = privacyMode
    ? 'https://www.youtube-nocookie.com/embed/'
    : 'https://www.youtube.com/embed/';

  const params = new URLSearchParams({
    rel: '0',
    disablekb: '1',
  });

  if (autoPlay)        params.set('autoplay', '1');
  if (!showControls)   params.set('controls', '0');
  if (loop) {
    params.set('loop', '1');
    params.set('playlist', videoId); // YouTube requires playlist=videoId for loop
  }
  if (startSec != null && startSec > 0) params.set('start', String(startSec));
  if (endSec   != null && endSec   > 0) params.set('end',   String(endSec));

  const src = `${base}${videoId}?${params.toString()}`;

  // ── Display mode container ─────────────────────────────────────────────────
  // standard (Original) → natural 16:9 aspect ratio box
  // cover    (Scaled)   → stretches to fill the parent container's height
  const isScaled = displayMode === 'cover';

  const wrapClass   = isScaled ? 'relative w-full h-full' : 'relative w-full aspect-video';
  const iframeClass = 'absolute inset-0 w-full h-full rounded-xl';

  // ── Consent overlay ────────────────────────────────────────────────────────
  if (!confirmed) {
    const previewMedia = slot.data?.media;
    return (
      <div className={`${wrapClass} rounded-xl overflow-hidden bg-surface-900`}>
        {/* Optional preview thumbnail */}
        {previewMedia?.url && (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={previewMedia.url}
            alt=""
            className={`absolute inset-0 w-full h-full ${isScaled ? 'object-cover' : 'object-contain'} opacity-40`}
          />
        )}

        {/* Overlay */}
        <div className="absolute inset-0 flex flex-col items-center justify-center gap-4 p-6 text-center bg-black/60 rounded-xl">
          {/* YouTube logo hint */}
          <svg className="w-16 h-16 text-white/70" viewBox="0 0 24 24" fill="currentColor">
            <path d="M23.5 6.19a3.02 3.02 0 0 0-2.12-2.14C19.54 3.5 12 3.5 12 3.5s-7.54 0-9.38.55A3.02 3.02 0 0 0 .5 6.19C0 8.04 0 12 0 12s0 3.96.5 5.81a3.02 3.02 0 0 0 2.12 2.14C4.46 20.5 12 20.5 12 20.5s7.54 0 9.38-.55a3.02 3.02 0 0 0 2.12-2.14C24 15.96 24 12 24 12s0-3.96-.5-5.81zM9.75 15.5V8.5l6.5 3.5-6.5 3.5z"/>
          </svg>

          <p className="text-white text-sm max-w-xs">
            This video is hosted by YouTube. By loading it you agree to YouTube&apos;s privacy policy.
          </p>

          <button
            onClick={() => setConfirmed(true)}
            className="px-6 py-2 bg-white text-surface-900 font-semibold rounded-lg hover:bg-surface-100 transition"
          >
            Load video
          </button>
        </div>
      </div>
    );
  }

  // ── Iframe ─────────────────────────────────────────────────────────────────
  return (
    <div className={`${wrapClass} rounded-xl overflow-hidden`}>
      <iframe
        src={src}
        title={iframeTitle}
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
        allowFullScreen
        className={iframeClass}
      />
    </div>
  );
}
