'use client'

import { useState } from 'react'

/**
 * Click-to-load YouTube facade: renders the thumbnail with a play button and
 * only injects the iframe on demand — no third-party JS on page load
 * (production performance pattern). Uses the privacy-enhanced embed domain.
 */
export function VideoExplainer({
  videoId,
  title = 'HeavyHaul Agent — product overview',
}: {
  videoId: string
  title?: string
}) {
  const [playing, setPlaying] = useState(false)

  return (
    <div className="group relative aspect-video w-full overflow-hidden rounded-2xl bg-navy-900 shadow-2xl ring-1 ring-white/15">
      {playing ? (
        <iframe
          className="absolute inset-0 h-full w-full"
          src={`https://www.youtube-nocookie.com/embed/${videoId}?autoplay=1&rel=0&modestbranding=1`}
          title={title}
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          allowFullScreen
        />
      ) : (
        <button
          type="button"
          onClick={() => setPlaying(true)}
          className="absolute inset-0 h-full w-full cursor-pointer"
          aria-label={`Play video: ${title}`}
        >
          {/* eslint-disable-next-line @next/next/no-img-element -- remote YouTube thumbnail */}
          <img
            src={`https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`}
            alt=""
            className="h-full w-full object-cover opacity-90 transition duration-300 group-hover:scale-[1.02] group-hover:opacity-100"
          />
          <span className="absolute inset-0 bg-gradient-to-t from-navy-950/70 via-transparent to-transparent" />
          {/* Play button */}
          <span className="absolute inset-0 grid place-items-center">
            <span className="grid h-16 w-16 place-items-center rounded-full bg-amber-brand shadow-lg shadow-amber-brand/40 transition duration-300 group-hover:scale-110">
              <svg viewBox="0 0 24 24" className="ml-1 h-7 w-7 fill-navy-950" aria-hidden>
                <path d="M8 5.14v13.72L19 12 8 5.14z" />
              </svg>
            </span>
          </span>
          <span className="absolute bottom-3 left-4 right-4 flex items-center justify-between text-left">
            <span className="text-sm font-semibold text-white drop-shadow">{title}</span>
            <span className="rounded-full bg-black/50 px-2 py-0.5 text-[11px] font-semibold text-white">
              ▶ 2 min
            </span>
          </span>
        </button>
      )}
    </div>
  )
}
