'use client';

// Video Scrubber — NiceUI (MIT) · https://niceui.dev/c/components/video-scrubber
// One self-contained file: needs only React and Tailwind CSS. Nothing else to install.

import { useCallback, useEffect, useMemo, useRef, useState, createElement, type SVGProps } from 'react';

function cn(...classes: Array<string | false | null | undefined>) {
  return classes.filter(Boolean).join(' ');
}

// Icons from Lucide (ISC licence, lucide.dev), inlined so there is nothing to install.
type NiceIconProps = SVGProps<SVGSVGElement> & { size?: number | string; absoluteStrokeWidth?: boolean };
type LucideIcon = (props: NiceIconProps) => JSX.Element;
type LucideProps = NiceIconProps;
const niceIcon = (node: Array<[string, Record<string, string>]>): LucideIcon =>
  function Icon({ size = 24, strokeWidth = 2, absoluteStrokeWidth, children, ...rest }: NiceIconProps) {
    const sw = absoluteStrokeWidth ? (Number(strokeWidth) * 24) / Number(size) : strokeWidth;
    return createElement('svg', { xmlns: 'http://www.w3.org/2000/svg', width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: sw, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, ...rest }, ...node.map(([tag, attrs], i) => createElement(tag, { key: i, ...attrs })), children);
  };
const Pause = niceIcon([["rect",{"x":"14","y":"4","width":"4","height":"16","rx":"1"}],["rect",{"x":"6","y":"4","width":"4","height":"16","rx":"1"}]]);
const Play = niceIcon([["polygon",{"points":"6 3 20 12 6 21 6 3"}]]);
const SkipBack = niceIcon([["polygon",{"points":"19 20 9 12 19 4 19 20"}],["line",{"x1":"5","x2":"5","y1":"19","y2":"5"}]]);
const SkipForward = niceIcon([["polygon",{"points":"5 4 15 12 5 20 5 4"}],["line",{"x1":"19","x2":"19","y1":"5","y2":"19"}]]);

// NiceUI animations and helper classes, injected once so no CSS setup is needed.
const NICEUI_CSS = ".focus-ring{outline:none}.focus-ring:focus-visible{box-shadow:0 0 0 2px #000,0 0 0 4px rgba(14,165,233,.6)}";
if (typeof document !== 'undefined' && !document.getElementById('niceui-css-10x759f')) {
  const el = document.createElement('style');
  el.id = 'niceui-css-10x759f';
  el.textContent = NICEUI_CSS;
  document.head.appendChild(el);
}

// ── components/gallery/art.ts ───────────────────────────────────
/*
 * Procedural artwork for the gallery demos: soft landscapes and abstract mesh
 * gradients with film grain, rendered once to data URLs. Swap `src` for real
 * photos in your app — every gallery component just takes image URLs.
 */

type Artwork = { id: number; title: string; artist: string; place: string; year: number; tone: 'warm' | 'cool' | 'dusk' | 'mono' };

const PALETTES: string[][] = [
  ['#0b1d3a', '#1f4e79', '#f2a65a', '#f7d9a8'],
  ['#120c26', '#4b2a77', '#e66b9d', '#ffd1b3'],
  ['#06222b', '#0f5f6b', '#7fd1c7', '#e8f6f1'],
  ['#1b1410', '#5b3a26', '#d98c4a', '#f6e1c3'],
  ['#0e0f13', '#2b2f3a', '#8a93a6', '#e6e8ee'],
  ['#0a1a12', '#1f5134', '#9cc98a', '#f1f7da'],
  ['#1a0f14', '#6b1f3a', '#ef6f5e', '#ffd8a8'],
  ['#071426', '#123f73', '#5aa9e6', '#d6ecff'],
  ['#191325', '#3b2d5c', '#b39ddb', '#f3e9ff'],
  ['#201608', '#6e4a12', '#e0b34a', '#fff1c4'],
  ['#0b1216', '#29424f', '#6fa3b8', '#f0e6d2'],
  ['#170b0b', '#4a1414', '#c84b31', '#f5c26b'],
];

const ARTWORKS: Artwork[] = [
  { id: 0, title: 'Low Tide, Dawn', artist: 'Mira Okafor', place: 'Comporta', year: 2025, tone: 'warm' },
  { id: 1, title: 'Neon Bloom', artist: 'Ilya Varga', place: 'Kyoto', year: 2024, tone: 'dusk' },
  { id: 2, title: 'Glass Lagoon', artist: 'Sana Iqbal', place: 'Faroe Islands', year: 2025, tone: 'cool' },
  { id: 3, title: 'Copper Dunes', artist: 'Teo Marchetti', place: 'Merzouga', year: 2023, tone: 'warm' },
  { id: 4, title: 'Fog Study No. 4', artist: 'Lena Brandt', place: 'Dolomites', year: 2024, tone: 'mono' },
  { id: 5, title: 'Green Hour', artist: 'Ravi Menon', place: 'Munnar', year: 2025, tone: 'cool' },
  { id: 6, title: 'Ember Coast', artist: 'Noor Haddad', place: 'Big Sur', year: 2024, tone: 'warm' },
  { id: 7, title: 'Blue Hour Harbour', artist: 'Jonas Weber', place: 'Bergen', year: 2025, tone: 'cool' },
  { id: 8, title: 'Lavender Field', artist: 'Camille Roy', place: 'Valensole', year: 2023, tone: 'dusk' },
  { id: 9, title: 'Golden Ridge', artist: 'Aiko Tanaka', place: 'Hokkaido', year: 2025, tone: 'warm' },
  { id: 10, title: 'Salt Flats', artist: 'Diego Alvarez', place: 'Uyuni', year: 2024, tone: 'mono' },
  { id: 11, title: 'Red Canyon', artist: 'Hana Kobayashi', place: 'Arizona', year: 2025, tone: 'warm' },
];

let seedState = 1;
const rand = () => {
  seedState = (seedState * 1664525 + 1013904223) >>> 0;
  return seedState / 4294967296;
};

const cache = new Map<string, string>();

/** A deterministic artwork as a data URL. `kind` picks a landscape or an abstract mesh. */
function artwork(id: number, w = 960, h = 640, kind: 'landscape' | 'mesh' = id % 3 === 1 ? 'mesh' : 'landscape'): string {
  const key = `${id}-${w}-${h}-${kind}`;
  const hit = cache.get(key);
  if (hit) return hit;
  if (typeof document === 'undefined') return '';
  const c = document.createElement('canvas');
  c.width = w;
  c.height = h;
  const g = c.getContext('2d');
  if (!g) return '';
  seedState = (id + 1) * 9973;
  const [deep, mid, hot, light] = PALETTES[id % PALETTES.length];

  const sky = g.createLinearGradient(0, 0, 0, h);
  sky.addColorStop(0, deep);
  sky.addColorStop(0.55, mid);
  sky.addColorStop(1, kind === 'mesh' ? deep : hot);
  g.fillStyle = sky;
  g.fillRect(0, 0, w, h);

  // soft light blobs
  const blobs = kind === 'mesh' ? 6 : 3;
  for (let i = 0; i < blobs; i++) {
    const x = rand() * w;
    const y = rand() * h * (kind === 'mesh' ? 1 : 0.6);
    const r = (0.25 + rand() * 0.45) * Math.max(w, h);
    const rg = g.createRadialGradient(x, y, 0, x, y, r);
    rg.addColorStop(0, [hot, light, mid][i % 3] + 'cc');
    rg.addColorStop(1, 'transparent');
    g.globalCompositeOperation = 'screen';
    g.fillStyle = rg;
    g.fillRect(0, 0, w, h);
  }
  g.globalCompositeOperation = 'source-over';

  if (kind === 'landscape') {
    // sun
    const sx = (0.25 + rand() * 0.5) * w;
    const sy = h * (0.38 + rand() * 0.12);
    const sr = Math.min(w, h) * (0.07 + rand() * 0.05);
    const glow = g.createRadialGradient(sx, sy, 0, sx, sy, sr * 5);
    glow.addColorStop(0, light + 'aa');
    glow.addColorStop(1, 'transparent');
    g.fillStyle = glow;
    g.fillRect(0, 0, w, h);
    g.fillStyle = light;
    g.beginPath();
    g.arc(sx, sy, sr, 0, Math.PI * 2);
    g.fill();
    // ridges, back to front
    for (let layer = 0; layer < 4; layer++) {
      const base = h * (0.5 + layer * 0.12);
      const amp = h * (0.12 - layer * 0.02);
      const f1 = 1.5 + rand() * 2;
      const f2 = 4 + rand() * 4;
      const ph = rand() * 10;
      g.beginPath();
      g.moveTo(0, h);
      for (let x = 0; x <= w; x += 4) {
        const u = x / w;
        const y = base - amp * (0.6 * Math.sin(u * f1 * Math.PI + ph) + 0.3 * Math.sin(u * f2 * Math.PI + ph * 2) + 0.1 * Math.sin(u * 23 + ph));
        g.lineTo(x, y);
      }
      g.lineTo(w, h);
      g.closePath();
      const t = layer / 3;
      const lg = g.createLinearGradient(0, base - amp, 0, h);
      lg.addColorStop(0, mix(mid, deep, 0.25 + t * 0.6));
      lg.addColorStop(1, mix(deep, '#000000', t * 0.5));
      g.fillStyle = lg;
      g.globalAlpha = 0.92;
      g.fill();
      g.globalAlpha = 1;
    }
  } else {
    // flowing ribbons
    for (let i = 0; i < 3; i++) {
      g.beginPath();
      const y0 = h * (0.2 + rand() * 0.6);
      g.moveTo(-50, y0);
      g.bezierCurveTo(w * 0.3, y0 - h * (rand() - 0.5), w * 0.7, y0 + h * (rand() - 0.5), w + 50, y0 + h * (rand() - 0.5) * 0.6);
      g.lineWidth = Math.min(w, h) * (0.08 + rand() * 0.12);
      g.strokeStyle = [light, hot, mid][i] + '55';
      g.filter = `blur(${Math.round(Math.min(w, h) * 0.04)}px)`;
      g.stroke();
      g.filter = 'none';
    }
  }

  // vignette
  const vg = g.createRadialGradient(w / 2, h / 2, Math.min(w, h) * 0.3, w / 2, h / 2, Math.max(w, h) * 0.75);
  vg.addColorStop(0, 'transparent');
  vg.addColorStop(1, 'rgba(0,0,0,0.45)');
  g.fillStyle = vg;
  g.fillRect(0, 0, w, h);

  // film grain
  const img = g.getImageData(0, 0, w, h);
  const d = img.data;
  for (let i = 0; i < d.length; i += 4) {
    const n = (rand() - 0.5) * 18;
    d[i] += n;
    d[i + 1] += n;
    d[i + 2] += n;
  }
  g.putImageData(img, 0, 0);

  const url = c.toDataURL('image/jpeg', 0.86);
  cache.set(key, url);
  return url;
}

function mix(a: string, b: string, t: number) {
  const pa = parseInt(a.slice(1), 16);
  const pb = parseInt(b.slice(1), 16);
  const ch = (s: number) => Math.round(((pa >> s) & 255) * (1 - t) + ((pb >> s) & 255) * t);
  return `rgb(${ch(16)},${ch(8)},${ch(0)})`;
}

// ── components/media/VideoScrubber.tsx ──────────────────────────
export type Chapter = { start: number; title: string };

export type VideoScrubberProps = {
  /** Total length in seconds. */
  duration: number;
  /** Current time in seconds. */
  time: number;
  onSeek: (t: number) => void;
  chapters?: Chapter[];
  /** Seconds buffered so far. */
  buffered?: number;
  /** Returns a preview image URL for a given time (shown on hover). */
  preview?: (t: number) => string;
  className?: string;
};

const fmtTime = (s: number) => {
  const t = Math.max(0, Math.floor(s));
  const h = Math.floor(t / 3600);
  const m = Math.floor((t % 3600) / 60);
  const sec = String(t % 60).padStart(2, '0');
  return h ? `${h}:${String(m).padStart(2, '0')}:${sec}` : `${m}:${sec}`;
};

/** A video scrubber timeline with chapters, hover preview, buffered range and keyboard seeking. */
export function VideoScrubber({ duration, time, onSeek, chapters = [], buffered = 0, preview, className }: VideoScrubberProps) {
  const bar = useRef<HTMLDivElement>(null);
  const [hover, setHover] = useState<number | null>(null);
  const [drag, setDrag] = useState(false);
  const [barW, setBarW] = useState(0);

  useEffect(() => {
    const el = bar.current;
    if (!el) return;
    const ro = new ResizeObserver(() => setBarW(el.clientWidth));
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  const tAt = useCallback(
    (clientX: number) => {
      const r = bar.current!.getBoundingClientRect();
      return Math.max(0, Math.min(1, (clientX - r.left) / r.width)) * duration;
    },
    [duration],
  );

  const segs = useMemo(() => {
    const list = chapters.length ? [...chapters].sort((a, b) => a.start - b.start) : [{ start: 0, title: '' }];
    return list.map((c, i) => ({ ...c, end: list[i + 1]?.start ?? duration }));
  }, [chapters, duration]);
  const chapterAt = (t: number) => segs.find((s) => t >= s.start && t < s.end) ?? segs[segs.length - 1];

  const shown = hover ?? (drag ? time : null);
  const tipX = shown === null ? 0 : Math.max(64, Math.min(barW - 64, (shown / duration) * barW));
  const now = chapterAt(time);

  return (
    <div className={cn('w-full select-none', className)}>
      <div className="relative">
        {shown !== null && (
          <div className="pointer-events-none absolute bottom-full mb-3 -translate-x-1/2" style={{ left: tipX }}>
            <div className="w-32 overflow-hidden rounded-lg border border-white/10 bg-[#0b0c0e] shadow-[0_0_0_1px_rgba(255,255,255,0.08),0_16px_48px_-12px_rgba(0,0,0,0.7),0_4px_12px_rgba(0,0,0,0.4)]">
              {preview && <img src={preview(shown)} alt="" className="aspect-video w-full object-cover" />}
              <div className="px-2 py-1.5">
                <p className="truncate text-[11px] font-medium text-[#e5e7eb]">{chapterAt(shown).title || 'Preview'}</p>
                <p className="font-mono text-[10px] tabular-nums text-[#7dd3fc]">{fmtTime(shown)}</p>
              </div>
            </div>
          </div>
        )}
        <div
          ref={bar}
          role="slider"
          tabIndex={0}
          aria-label="Seek"
          aria-valuemin={0}
          aria-valuemax={Math.round(duration)}
          aria-valuenow={Math.round(time)}
          aria-valuetext={`${fmtTime(time)} of ${fmtTime(duration)}${now.title ? `, ${now.title}` : ''}`}
          onPointerDown={(e) => {
            e.currentTarget.setPointerCapture(e.pointerId);
            setDrag(true);
            onSeek(tAt(e.clientX));
          }}
          onPointerMove={(e) => {
            const t = tAt(e.clientX);
            if (e.pointerType === 'mouse') setHover(t);
            if (drag) onSeek(t);
          }}
          onPointerUp={() => setDrag(false)}
          onPointerCancel={() => setDrag(false)}
          onPointerLeave={() => setHover(null)}
          onKeyDown={(e) => {
            const step = e.shiftKey ? 10 : 5;
            const map: Record<string, number> = { ArrowRight: time + step, ArrowLeft: time - step, Home: 0, End: duration, PageUp: time + 30, PageDown: time - 30 };
            if (e.key in map) {
              e.preventDefault();
              onSeek(Math.max(0, Math.min(duration, map[e.key])));
            }
          }}
          className="focus-ring group relative flex h-6 cursor-pointer items-center gap-[3px] rounded-md"
        >
          {segs.map((s) => {
            const w = ((s.end - s.start) / duration) * 100;
            const played = Math.max(0, Math.min(1, (time - s.start) / (s.end - s.start)));
            const buf = Math.max(0, Math.min(1, (buffered - s.start) / (s.end - s.start)));
            const hot = shown !== null && shown >= s.start && shown < s.end;
            return (
              <div key={s.start} className={cn('relative h-1.5 overflow-hidden rounded-full bg-white/10 transition-[height] duration-200 group-hover:h-2.5', hot && 'h-2.5')} style={{ width: `${w}%` }}>
                <div className="absolute inset-y-0 left-0 bg-white/20" style={{ width: `${buf * 100}%` }} />
                {hover !== null && hot && <div className="absolute inset-y-0 left-0 bg-white/25" style={{ width: `${Math.max(0, Math.min(1, (hover - s.start) / (s.end - s.start))) * 100}%` }} />}
                <div className="absolute inset-y-0 left-0 bg-gradient-to-r from-[#38bdf8] to-[#7dd3fc]" style={{ width: `${played * 100}%` }} />
              </div>
            );
          })}
          <div
            aria-hidden
            className={cn('pointer-events-none absolute top-1/2 h-3.5 w-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-white shadow-[0_0_0_4px_rgba(125,211,252,0.25)] transition-transform duration-200', drag ? 'scale-125' : 'scale-0 group-hover:scale-100 group-focus-visible:scale-100')}
            style={{ left: `${(time / duration) * 100}%` }}
          />
        </div>
      </div>
      <div className="mt-2 flex items-center justify-between gap-3 text-[11px] text-[#8b9099]">
        <span className="font-mono tabular-nums text-[#c9cdd3]">
          {fmtTime(time)} <span className="text-[#6b7079]">/ {fmtTime(duration)}</span>
        </span>
        {now.title && <span className="truncate text-[#a3a8b0]">{now.title}</span>}
      </div>
    </div>
  );
}

const CHAPTERS: Chapter[] = [
  { start: 0, title: 'Cold open' },
  { start: 48, title: 'The coastline' },
  { start: 131, title: 'Building the studio' },
  { start: 205, title: 'Night edits' },
  { start: 262, title: 'What comes next' },
];

export function VideoScrubberDemo() {
  const duration = 318;
  const [time, setTime] = useState(52);
  const [playing, setPlaying] = useState(true);
  const [buffered, setBuffered] = useState(90);
  const frames = useRef(new Map<number, string>());

  useEffect(() => {
    if (!playing) return;
    let last = performance.now();
    let raf = 0;
    const tick = (now: number) => {
      const dt = (now - last) / 1000;
      last = now;
      setTime((t) => (t + dt * 4 >= duration ? 0 : t + dt * 4));
      setBuffered((b) => Math.min(duration, b + dt * 9));
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [playing]);

  const preview = useCallback((t: number) => {
    const idx = CHAPTERS.findIndex((c, i) => t >= c.start && t < (CHAPTERS[i + 1]?.start ?? duration));
    const key = Math.max(0, idx);
    if (!frames.current.has(key)) frames.current.set(key, artwork([0, 2, 5, 7, 11][key % 5], 256, 144, key % 2 ? 'mesh' : 'landscape'));
    return frames.current.get(key)!;
  }, []);

  const current = CHAPTERS.reduce((acc, c, i) => (time >= c.start ? i : acc), 0);
  const jump = (dir: 1 | -1) => setTime(CHAPTERS[Math.max(0, Math.min(CHAPTERS.length - 1, current + dir))].start);

  return (
    <div className="w-full max-w-2xl">
      <div className="relative aspect-video overflow-hidden rounded-2xl bg-[#0b0c0e] shadow-[0_0_0_1px_rgba(255,255,255,0.06),0_1px_2px_rgba(0,0,0,0.4),0_8px_24px_-8px_rgba(0,0,0,0.5)]">
        <img src={preview(time)} alt="" className="h-full w-full object-cover opacity-80" />
        <div className="absolute inset-0 bg-gradient-to-t from-black/85 via-black/10 to-transparent" />
        <div className="absolute inset-x-0 bottom-0 p-4 pt-16 sm:p-5">
          <VideoScrubber duration={duration} time={time} onSeek={setTime} chapters={CHAPTERS} buffered={buffered} preview={preview} />
          <div className="mt-2 flex items-center gap-1.5">
            <button type="button" onClick={() => jump(-1)} aria-label="Previous chapter" className="focus-ring grid h-9 w-9 place-items-center rounded-full text-[#c9cdd3] hover:bg-white/10">
              <SkipBack className="h-4 w-4" />
            </button>
            <button type="button" onClick={() => setPlaying((p) => !p)} aria-label={playing ? 'Pause' : 'Play'} className="focus-ring grid h-10 w-10 place-items-center rounded-full bg-white text-[#000000] transition-transform active:scale-90">
              {playing ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4 translate-x-px" />}
            </button>
            <button type="button" onClick={() => jump(1)} aria-label="Next chapter" className="focus-ring grid h-9 w-9 place-items-center rounded-full text-[#c9cdd3] hover:bg-white/10">
              <SkipForward className="h-4 w-4" />
            </button>
          </div>
        </div>
      </div>
      <ol className="mt-4 grid gap-1 sm:grid-cols-2">
        {CHAPTERS.map((c, i) => (
          <li key={c.start}>
            <button
              type="button"
              onClick={() => setTime(c.start)}
              aria-current={i === current ? 'true' : undefined}
              className={cn('focus-ring flex w-full items-center gap-3 rounded-lg px-3 py-2 text-left text-xs transition-colors', i === current ? 'bg-[#0ea5e9]/10 text-[#f3f4f6]' : 'text-[#8b9099] hover:bg-white/5 hover:text-[#c9cdd3]')}
            >
              <span className="w-10 font-mono tabular-nums text-[#7dd3fc]">{fmtTime(c.start)}</span>
              <span className="truncate">{c.title}</span>
            </button>
          </li>
        ))}
      </ol>
    </div>
  );
}
