'use client';

// Image Loader — NiceUI (MIT) · https://niceui.dev/c/components/image-loader
// One self-contained file: needs only React and Tailwind CSS. Nothing else to install.

import { useCallback, useEffect, useMemo, 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 ImageOff = niceIcon([["line",{"x1":"2","x2":"22","y1":"2","y2":"22"}],["path",{"d":"M10.41 10.41a2 2 0 1 1-2.83-2.83"}],["line",{"x1":"13.5","x2":"6","y1":"13.5","y2":"21"}],["line",{"x1":"18","x2":"21","y1":"12","y2":"15"}],["path",{"d":"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59"}],["path",{"d":"M21 15V5a2 2 0 0 0-2-2H9"}]]);
const RotateCcw = niceIcon([["path",{"d":"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{"d":"M3 3v5h5"}]]);

// 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/ImageLoader.tsx ────────────────────────────
export type ImageLoaderProps = {
  src: string;
  /** A tiny version of the image (e.g. 24px wide) shown blurred while the full one loads. */
  placeholder?: string;
  alt: string;
  /** Reveal style once loaded. */
  reveal?: 'blur' | 'fade' | 'scale';
  /** Show a shimmer skeleton when there is no placeholder. */
  skeleton?: boolean;
  className?: string;
  /** Demo helper: wait this long before swapping in `src` (simulates a slow network). */
  delay?: number;
  /** Demo helper: fail the first attempt to show the error state. */
  failFirst?: boolean;
};

/** Blur-up image loading: blurred preview or skeleton → sharp image, with an error state and retry. */
export function ImageLoader({ src, placeholder, alt, reveal = 'blur', skeleton = true, className, delay = 0, failFirst }: ImageLoaderProps) {
  const [status, setStatus] = useState<'loading' | 'loaded' | 'error'>('loading');
  const [attempt, setAttempt] = useState(0);
  const [url, setUrl] = useState<string | null>(null);

  useEffect(() => {
    setStatus('loading');
    setUrl(null);
    const t = window.setTimeout(() => {
      if (failFirst && attempt === 0) {
        setStatus('error');
        return;
      }
      setUrl(src);
    }, delay);
    return () => window.clearTimeout(t);
  }, [src, delay, failFirst, attempt]);

  const retry = useCallback(() => setAttempt((a) => a + 1), []);
  const loaded = status === 'loaded';

  return (
    <div className={cn('relative isolate overflow-hidden rounded-2xl bg-[#0b0c0e]', className)} aria-busy={status === 'loading'}>
      {placeholder ? (
        <img
          src={placeholder}
          alt=""
          aria-hidden
          className={cn('absolute inset-0 h-full w-full scale-110 object-cover blur-xl transition-opacity duration-700', loaded ? 'opacity-0' : 'opacity-100')}
        />
      ) : (
        skeleton &&
        !loaded &&
        status !== 'error' && (
          <div aria-hidden className="il-shimmer absolute inset-0 bg-[linear-gradient(100deg,#0b0c0e_30%,#1c1e22_50%,#0b0c0e_70%)] bg-[length:200%_100%]" />
        )
      )}

      {url && (
        <img
          src={url}
          alt={alt}
          onLoad={() => setStatus('loaded')}
          onError={() => setStatus('error')}
          className={cn(
            'relative h-full w-full object-cover transition-[opacity,transform,filter] duration-700 ease-[cubic-bezier(0.16,1,0.3,1)] motion-reduce:transition-none',
            loaded ? 'scale-100 opacity-100 blur-0' : reveal === 'scale' ? 'scale-105 opacity-0' : reveal === 'blur' ? 'opacity-0 blur-md' : 'opacity-0',
          )}
        />
      )}

      {status === 'loading' && (
        <span className="absolute bottom-3 left-3 rounded-full bg-black/55 px-2.5 py-1 text-[11px] text-[#c9cdd3] backdrop-blur" role="status">
          Loading…
        </span>
      )}

      {status === 'error' && (
        <div role="alert" className="absolute inset-0 grid place-items-center bg-[#0b0c0e]">
          <div className="flex flex-col items-center gap-3 text-center">
            <ImageOff className="h-6 w-6 text-[#8b9099]" />
            <p className="text-sm text-[#a3a8b0]">Couldn&rsquo;t load this image</p>
            <button type="button" onClick={retry} className="focus-ring inline-flex items-center gap-1.5 rounded-full bg-[#1c1e22] px-3 py-1.5 text-xs text-[#e5e7eb] hover:bg-[#30333a]">
              <RotateCcw className="h-3.5 w-3.5" /> Retry
            </button>
          </div>
        </div>
      )}
      <style>{`@keyframes il-shimmer{from{background-position:200% 0}to{background-position:-200% 0}}.il-shimmer{animation:il-shimmer 1.4s linear infinite}@media (prefers-reduced-motion:reduce){.il-shimmer{animation:none}}`}</style>
    </div>
  );
}

export function ImageLoaderDemo() {
  const [run, setRun] = useState(0);
  const imgs = useMemo(
    () => [
      { id: 0, kind: 'landscape' as const, reveal: 'blur' as const, label: 'Blur-up', tiny: true },
      { id: 7, kind: 'mesh' as const, reveal: 'scale' as const, label: 'Skeleton + scale', tiny: false },
      { id: 3, kind: 'landscape' as const, reveal: 'fade' as const, label: 'Error + retry', tiny: true, fail: true },
    ],
    [],
  );
  const [srcs, setSrcs] = useState<{ full: string; tiny: string }[]>([]);
  useEffect(() => {
    setSrcs(imgs.map((m) => ({ full: artwork(m.id, 720, 480, m.kind), tiny: artwork(m.id, 24, 16, m.kind) })));
  }, [imgs]);

  return (
    <div className="flex w-full flex-col items-center gap-6">
      <div className="grid w-full max-w-3xl gap-4 sm:grid-cols-3">
        {imgs.map((m, i) => (
          <figure key={`${m.id}-${run}`} className="flex flex-col gap-2">
            {srcs[i] && (
              <ImageLoader
                src={srcs[i].full}
                placeholder={m.tiny ? srcs[i].tiny : undefined}
                alt={m.label}
                reveal={m.reveal}
                delay={900 + i * 700}
                failFirst={m.fail}
                className="aspect-[3/2] w-full"
              />
            )}
            <figcaption className="text-xs text-[#8b9099]">{m.label}</figcaption>
          </figure>
        ))}
      </div>
      <button type="button" onClick={() => setRun((r) => r + 1)} className="focus-ring inline-flex items-center gap-1.5 rounded-full bg-[#0b0c0e] px-4 py-2 text-xs text-[#c9cdd3] 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)] hover:text-[#f3f4f6]">
        <RotateCcw className="h-3.5 w-3.5" /> Replay loading
      </button>
    </div>
  );
}
