'use client';

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

import { useEffect, useState, type CSSProperties, type ReactNode, 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 Heart = niceIcon([["path",{"d":"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"}]]);
const MessageCircle = niceIcon([["path",{"d":"M7.9 20A9 9 0 1 0 4 16.1L2 22Z"}]]);
const RefreshCw = niceIcon([["path",{"d":"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{"d":"M21 3v5h-5"}],["path",{"d":"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{"d":"M8 16H3v5"}]]);

// 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/structure/Skeleton.tsx ───────────────────────────
export type SkeletonVariant = 'shimmer' | 'pulse';

export type SkeletonProps = {
  className?: string;
  /** Shimmer sweeps a highlight across; pulse fades in and out. */
  variant?: SkeletonVariant;
  /** Make it a circle (avatars). */
  circle?: boolean;
  style?: CSSProperties;
};

const SKELETON_CSS = `@keyframes sk-sweep{from{transform:translateX(-100%)}to{transform:translateX(100%)}}@keyframes sk-pulse{0%,100%{opacity:1}50%{opacity:.45}}@media (prefers-reduced-motion:reduce){.sk-anim,.sk-anim::after{animation:none!important}}`;

/** One placeholder block. Size it with className (h-4 w-32, aspect-video…). */
export function Skeleton({ className, variant = 'shimmer', circle, style }: SkeletonProps) {
  return (
    <span
      aria-hidden
      style={{ ...style, animation: variant === 'pulse' ? 'sk-pulse 1.6s ease-in-out infinite' : undefined }}
      className={cn(
        'sk-anim relative block overflow-hidden bg-white/[0.06]',
        circle ? 'rounded-full' : 'rounded-md',
        variant === 'shimmer' && "after:absolute after:inset-0 after:bg-gradient-to-r after:from-transparent after:via-white/[0.07] after:to-transparent after:content-[''] after:[animation:sk-sweep_1.5s_ease-in-out_infinite]",
        className,
      )}
    />
  );
}

/** Wrap placeholders so screen readers hear "Loading" once instead of nothing. */
export function SkeletonGroup({ children, loading = true, label = 'Loading', className }: { children: ReactNode; loading?: boolean; label?: string; className?: string }) {
  return (
    <div role="status" aria-live="polite" aria-busy={loading} className={className}>
      <style>{SKELETON_CSS}</style>
      <span className="sr-only">{loading ? `${label}…` : 'Loaded'}</span>
      {children}
    </div>
  );
}

/* ── preset layouts ─────────────────────────────────────────────── */

type PresetProps = { variant?: SkeletonVariant; className?: string };

export function SkeletonCard({ variant, className }: PresetProps) {
  return (
    <div className={cn('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)]', className)}>
      <Skeleton variant={variant} className="aspect-[16/9] w-full rounded-none" />
      <div className="space-y-2.5 p-4">
        <Skeleton variant={variant} className="h-4 w-3/4" />
        <Skeleton variant={variant} className="h-3 w-full" />
        <Skeleton variant={variant} className="h-3 w-5/6" />
      </div>
    </div>
  );
}

export function SkeletonListRow({ variant, className }: PresetProps) {
  return (
    <div className={cn('flex items-center gap-3 py-3', className)}>
      <Skeleton variant={variant} circle className="h-9 w-9 shrink-0" />
      <div className="min-w-0 flex-1 space-y-2">
        <Skeleton variant={variant} className="h-3 w-1/2" />
        <Skeleton variant={variant} className="h-3 w-4/5" />
      </div>
      <Skeleton variant={variant} className="h-6 w-14 shrink-0 rounded-full" />
    </div>
  );
}

export function SkeletonProfile({ variant, className }: PresetProps) {
  return (
    <div className={cn('flex flex-col items-center gap-3 rounded-2xl bg-[#0b0c0e] p-6 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)]', className)}>
      <Skeleton variant={variant} circle className="h-16 w-16" />
      <Skeleton variant={variant} className="h-4 w-32" />
      <Skeleton variant={variant} className="h-3 w-44" />
      <div className="mt-2 flex gap-2">
        <Skeleton variant={variant} className="h-8 w-20 rounded-lg" />
        <Skeleton variant={variant} className="h-8 w-20 rounded-lg" />
      </div>
    </div>
  );
}

export function SkeletonTable({ variant, rows = 4, className }: PresetProps & { rows?: number }) {
  return (
    <div className={cn('overflow-hidden rounded-xl border border-white/[0.06]', className)}>
      <div className="grid grid-cols-[2fr_1fr_1fr] gap-4 border-b border-white/[0.06] bg-white/[0.02] px-4 py-3">
        {[0, 1, 2].map((i) => (
          <Skeleton key={i} variant={variant} className="h-3 w-2/3" />
        ))}
      </div>
      {Array.from({ length: rows }, (_, r) => (
        <div key={r} className="grid grid-cols-[2fr_1fr_1fr] gap-4 border-b border-white/[0.04] px-4 py-3.5 last:border-0">
          <Skeleton variant={variant} className="h-3 w-4/5" />
          <Skeleton variant={variant} className="h-3 w-1/2" />
          <Skeleton variant={variant} className="h-3 w-3/5" />
        </div>
      ))}
    </div>
  );
}

export function SkeletonChat({ variant, className }: PresetProps) {
  return (
    <div className={cn('space-y-3', className)}>
      <div className="flex items-end gap-2">
        <Skeleton variant={variant} circle className="h-7 w-7 shrink-0" />
        <Skeleton variant={variant} className="h-14 w-3/5 rounded-2xl rounded-bl-md" />
      </div>
      <div className="flex justify-end">
        <Skeleton variant={variant} className="h-9 w-2/5 rounded-2xl rounded-br-md" />
      </div>
      <div className="flex items-end gap-2">
        <Skeleton variant={variant} circle className="h-7 w-7 shrink-0" />
        <Skeleton variant={variant} className="h-20 w-4/5 rounded-2xl rounded-bl-md" />
      </div>
    </div>
  );
}

export function SkeletonArticle({ variant, className }: PresetProps) {
  return (
    <div className={cn('space-y-3', className)}>
      <Skeleton variant={variant} className="h-6 w-4/5" />
      <Skeleton variant={variant} className="h-6 w-1/2" />
      <div className="flex items-center gap-2 pt-1">
        <Skeleton variant={variant} circle className="h-6 w-6" />
        <Skeleton variant={variant} className="h-3 w-28" />
      </div>
      <div className="space-y-2 pt-2">
        {[100, 96, 92, 98, 70].map((w, i) => (
          <Skeleton key={i} variant={variant} className="h-3" style={{ width: `${w}%` }} />
        ))}
      </div>
    </div>
  );
}

/* ── demo ───────────────────────────────────────────────────────── */

function PostCard() {
  return (
    <article className="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)]">
      <div className="aspect-[16/9] w-full bg-[radial-gradient(120%_90%_at_20%_10%,#38bdf8_0%,#0c4a6e_45%,#000_100%)]" />
      <div className="p-4">
        <p className="text-[15px] font-medium text-[#f3f4f6]">Designing calm loading states</p>
        <p className="mt-1.5 text-[13px] leading-relaxed text-[#8b9099]">Placeholders that match the final layout make waiting feel shorter and stop the page from jumping.</p>
      </div>
    </article>
  );
}

const PEOPLE = [
  ['Maya Lin', 'Shipped the onboarding redesign', 'Design'],
  ['Omar Haddad', 'Reviewed 4 pull requests', 'Eng'],
  ['Ines Duarte', 'Closed the Q3 roadmap', 'Product'],
];

function ChatDone() {
  return (
    <div className="space-y-3 text-[13px]">
      <div className="flex items-end gap-2">
        <span className="grid h-7 w-7 shrink-0 place-items-center rounded-full bg-[#0ea5e9]/20 text-[11px] text-[#bae6fd]">AI</span>
        <p className="max-w-[75%] rounded-2xl rounded-bl-md bg-[#121316] px-3.5 py-2.5 text-[#c9cdd3]">Your report is ready. Revenue is up 12% this month.</p>
      </div>
      <div className="flex justify-end">
        <p className="rounded-2xl rounded-br-md bg-[#0ea5e9] px-3.5 py-2 text-[#000000]">Show me by region</p>
      </div>
      <div className="flex items-end gap-2">
        <span className="grid h-7 w-7 shrink-0 place-items-center rounded-full bg-[#0ea5e9]/20 text-[11px] text-[#bae6fd]">AI</span>
        <p className="max-w-[80%] rounded-2xl rounded-bl-md bg-[#121316] px-3.5 py-2.5 text-[#c9cdd3]">Europe leads at +18%, then North America at +11% and APAC at +6%.</p>
      </div>
    </div>
  );
}

function Swap({ loading, skeleton, children }: { loading: boolean; skeleton: ReactNode; children: ReactNode }) {
  return (
    <div className="grid [&>*]:col-start-1 [&>*]:row-start-1">
      <div aria-hidden={!loading} className={cn('transition-opacity duration-500 ease-[cubic-bezier(0.16,1,0.3,1)]', loading ? 'opacity-100' : 'pointer-events-none opacity-0')}>
        {skeleton}
      </div>
      <div aria-hidden={loading} className={cn('transition-all duration-500 ease-[cubic-bezier(0.16,1,0.3,1)]', loading ? 'pointer-events-none translate-y-1 opacity-0' : 'translate-y-0 opacity-100')}>
        {children}
      </div>
    </div>
  );
}

export function SkeletonDemo() {
  const [loading, setLoading] = useState(true);
  const [variant, setVariant] = useState<SkeletonVariant>('shimmer');
  useEffect(() => {
    if (!loading) return;
    const id = window.setTimeout(() => setLoading(false), 2200);
    return () => window.clearTimeout(id);
  }, [loading]);

  return (
    <SkeletonGroup className="mx-auto w-full max-w-4xl" loading={loading}>
      <div className="mb-5 flex flex-wrap items-center gap-2">
        <div role="radiogroup" aria-label="Animation" className="flex rounded-xl bg-[#0b0c0e] p-1 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)]">
          {(['shimmer', 'pulse'] as const).map((v) => (
            <button
              key={v}
              role="radio"
              aria-checked={variant === v}
              onClick={() => setVariant(v)}
              className={cn('focus-ring rounded-lg px-3 py-1.5 text-xs font-medium capitalize transition-colors', variant === v ? 'bg-[#1c1e22] text-[#f3f4f6]' : 'text-[#8b9099] hover:text-[#c9cdd3]')}
            >
              {v}
            </button>
          ))}
        </div>
        <button onClick={() => setLoading(true)} disabled={loading} className="focus-ring flex items-center gap-1.5 rounded-xl bg-[#0b0c0e] px-3.5 py-2 text-xs font-medium 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)] transition-colors hover:text-[#f3f4f6] disabled:opacity-50">
          <RefreshCw className={cn('h-3.5 w-3.5', loading && 'animate-spin')} /> {loading ? 'Loading…' : 'Reload'}
        </button>
      </div>

      <div className="grid gap-4 md:grid-cols-3">
        <Swap loading={loading} skeleton={<SkeletonCard variant={variant} />}>
          <PostCard />
        </Swap>

        <div className="rounded-2xl bg-[#0b0c0e] px-4 py-1 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)]">
          <Swap
            loading={loading}
            skeleton={
              <div className="divide-y divide-white/[0.05]">
                {[0, 1, 2].map((i) => (
                  <SkeletonListRow key={i} variant={variant} />
                ))}
              </div>
            }
          >
            <ul className="divide-y divide-white/[0.05]">
              {PEOPLE.map(([n, t, tag]) => (
                <li key={n} className="flex items-center gap-3 py-3">
                  <span className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-[#1c1e22] text-xs text-[#c9cdd3]">{n.split(' ').map((p) => p[0]).join('')}</span>
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-[13px] font-medium text-[#e5e7eb]">{n}</p>
                    <p className="truncate text-xs text-[#8b9099]">{t}</p>
                  </div>
                  <span className="shrink-0 rounded-full bg-[#0ea5e9]/10 px-2 py-0.5 text-[11px] text-[#7dd3fc]">{tag}</span>
                </li>
              ))}
            </ul>
          </Swap>
        </div>

        <div className="rounded-2xl bg-[#0b0c0e] p-4 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)]">
          <Swap loading={loading} skeleton={<SkeletonChat variant={variant} />}>
            <ChatDone />
          </Swap>
        </div>
      </div>

      <div className="mt-4 grid gap-4 md:grid-cols-[1fr_2fr]">
        <Swap loading={loading} skeleton={<SkeletonProfile variant={variant} />}>
          <div className="flex flex-col items-center gap-1.5 rounded-2xl bg-[#0b0c0e] p-6 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)]">
            <span className="grid h-16 w-16 place-items-center rounded-full bg-gradient-to-br from-[#7dd3fc] to-[#0369a1] text-lg font-medium text-[#000000]">NB</span>
            <p className="mt-1.5 text-[15px] font-medium text-[#f3f4f6]">Noah Bennett</p>
            <p className="text-xs text-[#8b9099]">Product designer · Lisbon</p>
            <div className="mt-3 flex gap-2 text-xs">
              <span className="flex items-center gap-1 rounded-lg bg-[#121316] px-3 py-1.5 text-[#c9cdd3]"><Heart className="h-3.5 w-3.5" /> 1.2k</span>
              <span className="flex items-center gap-1 rounded-lg bg-[#121316] px-3 py-1.5 text-[#c9cdd3]"><MessageCircle className="h-3.5 w-3.5" /> 86</span>
            </div>
          </div>
        </Swap>
        <Swap loading={loading} skeleton={<SkeletonTable variant={variant} rows={3} />}>
          <div className="overflow-hidden rounded-xl border border-white/[0.06] text-[13px]">
            <div className="grid grid-cols-[2fr_1fr_1fr] gap-4 border-b border-white/[0.06] bg-white/[0.02] px-4 py-2.5 text-xs text-[#8b9099]">
              <span>Invoice</span>
              <span>Status</span>
              <span className="text-right">Amount</span>
            </div>
            {[
              ['Northwind Studio', 'Paid', '$4,200'],
              ['Halcyon App', 'Due', '$1,850'],
              ['Quiet Hours', 'Paid', '$960'],
            ].map(([a, s, m]) => (
              <div key={a} className="grid grid-cols-[2fr_1fr_1fr] gap-4 border-b border-white/[0.04] px-4 py-3 last:border-0">
                <span className="truncate text-[#e5e7eb]">{a}</span>
                <span className={s === 'Paid' ? 'text-emerald-400' : 'text-amber-300'}>{s}</span>
                <span className="text-right font-mono text-[#c9cdd3]">{m}</span>
              </div>
            ))}
          </div>
        </Swap>
      </div>
      <div className="mt-4 rounded-2xl bg-[#0b0c0e] p-5 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)]">
        <p className="mb-4 font-mono text-[11px] uppercase tracking-wider text-[#6b7079]">Article preset</p>
        <SkeletonArticle variant={variant} />
      </div>
    </SkeletonGroup>
  );
}
