'use client';

// Mega Menu — NiceUI (MIT) · https://niceui.dev/c/marketing/mega-menu
// One self-contained file: needs only React and Tailwind CSS. Nothing else to install.

import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode, type AnchorHTMLAttributes, 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 ArrowUpRight = niceIcon([["path",{"d":"M7 7h10v10"}],["path",{"d":"M7 17 17 7"}]]);
const ChevronDown = niceIcon([["path",{"d":"m6 9 6 6 6-6"}]]);
const Menu = niceIcon([["line",{"x1":"4","x2":"20","y1":"12","y2":"12"}],["line",{"x1":"4","x2":"20","y1":"6","y2":"6"}],["line",{"x1":"4","x2":"20","y1":"18","y2":"18"}]]);
const X = niceIcon([["path",{"d":"M18 6 6 18"}],["path",{"d":"m6 6 12 12"}]]);
const AlignLeft = niceIcon([["line",{"x1":"21","x2":"3","y1":"6","y2":"6"}],["line",{"x1":"15","x2":"3","y1":"12","y2":"12"}],["line",{"x1":"17","x2":"3","y1":"18","y2":"18"}]]);
const BarChart3 = niceIcon([["path",{"d":"M3 3v16a2 2 0 0 0 2 2h16"}],["path",{"d":"M18 17V9"}],["path",{"d":"M13 17V5"}],["path",{"d":"M8 17v-3"}]]);
const Blocks = niceIcon([["rect",{"width":"7","height":"7","x":"14","y":"3","rx":"1"}],["path",{"d":"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3"}]]);
const BookOpen = niceIcon([["path",{"d":"M12 7v14"}],["path",{"d":"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"}]]);
const Bot = niceIcon([["path",{"d":"M12 8V4H8"}],["rect",{"width":"16","height":"12","x":"4","y":"8","rx":"2"}],["path",{"d":"M2 14h2"}],["path",{"d":"M20 14h2"}],["path",{"d":"M15 13v2"}],["path",{"d":"M9 13v2"}]]);
const CircleHelp = niceIcon([["circle",{"cx":"12","cy":"12","r":"10"}],["path",{"d":"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}],["path",{"d":"M12 17h.01"}]]);
const Clapperboard = niceIcon([["path",{"d":"M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3Z"}],["path",{"d":"m6.2 5.3 3.1 3.9"}],["path",{"d":"m12.4 3.4 3.1 4"}],["path",{"d":"M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"}]]);
const CreditCard = niceIcon([["rect",{"width":"20","height":"14","x":"2","y":"5","rx":"2"}],["line",{"x1":"2","x2":"22","y1":"10","y2":"10"}]]);
const FileWarning = niceIcon([["path",{"d":"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}],["path",{"d":"M12 9v4"}],["path",{"d":"M12 17h.01"}]]);
const GalleryHorizontal = niceIcon([["path",{"d":"M2 3v18"}],["rect",{"width":"12","height":"18","x":"6","y":"3","rx":"2"}],["path",{"d":"M22 3v18"}]]);
const Hourglass = niceIcon([["path",{"d":"M5 22h14"}],["path",{"d":"M5 2h14"}],["path",{"d":"M17 22v-4.172a2 2 0 0 0-.586-1.414L12 12l-4.414 4.414A2 2 0 0 0 7 17.828V22"}],["path",{"d":"M7 2v4.172a2 2 0 0 0 .586 1.414L12 12l4.414-4.414A2 2 0 0 0 17 6.172V2"}]]);
const Image = niceIcon([["rect",{"width":"18","height":"18","x":"3","y":"3","rx":"2","ry":"2"}],["circle",{"cx":"9","cy":"9","r":"2"}],["path",{"d":"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]]);
const Info = niceIcon([["circle",{"cx":"12","cy":"12","r":"10"}],["path",{"d":"M12 16v-4"}],["path",{"d":"M12 8h.01"}]]);
const LayoutDashboard = niceIcon([["rect",{"width":"7","height":"9","x":"3","y":"3","rx":"1"}],["rect",{"width":"7","height":"5","x":"14","y":"3","rx":"1"}],["rect",{"width":"7","height":"9","x":"14","y":"12","rx":"1"}],["rect",{"width":"7","height":"5","x":"3","y":"16","rx":"1"}]]);
const LayoutGrid = niceIcon([["rect",{"width":"7","height":"7","x":"3","y":"3","rx":"1"}],["rect",{"width":"7","height":"7","x":"14","y":"3","rx":"1"}],["rect",{"width":"7","height":"7","x":"14","y":"14","rx":"1"}],["rect",{"width":"7","height":"7","x":"3","y":"14","rx":"1"}]]);
const LayoutPanelTop = niceIcon([["rect",{"width":"18","height":"7","x":"3","y":"3","rx":"1"}],["rect",{"width":"7","height":"7","x":"3","y":"14","rx":"1"}],["rect",{"width":"7","height":"7","x":"14","y":"14","rx":"1"}]]);
const ListChecks = niceIcon([["path",{"d":"m3 17 2 2 4-4"}],["path",{"d":"m3 7 2 2 4-4"}],["path",{"d":"M13 6h8"}],["path",{"d":"M13 12h8"}],["path",{"d":"M13 18h8"}]]);
const Megaphone = niceIcon([["path",{"d":"m3 11 18-5v12L3 14v-3z"}],["path",{"d":"M11.6 16.8a3 3 0 1 1-5.8-1.6"}]]);
const MousePointerClick = niceIcon([["path",{"d":"M14 4.1 12 6"}],["path",{"d":"m5.1 8-2.9-.8"}],["path",{"d":"m6 12-1.9 2"}],["path",{"d":"M7.2 2.2 8 5.1"}],["path",{"d":"M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z"}]]);
const Navigation = niceIcon([["polygon",{"points":"3 11 22 2 13 21 11 13 3 11"}]]);
const Palette = niceIcon([["circle",{"cx":"13.5","cy":"6.5","r":".5","fill":"currentColor"}],["circle",{"cx":"17.5","cy":"10.5","r":".5","fill":"currentColor"}],["circle",{"cx":"8.5","cy":"7.5","r":".5","fill":"currentColor"}],["circle",{"cx":"6.5","cy":"12.5","r":".5","fill":"currentColor"}],["path",{"d":"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z"}]]);
const PanelBottom = niceIcon([["rect",{"width":"18","height":"18","x":"3","y":"3","rx":"2"}],["path",{"d":"M3 15h18"}]]);
const Quote = niceIcon([["path",{"d":"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}],["path",{"d":"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z"}]]);
const ScrollText = niceIcon([["path",{"d":"M15 12h-5"}],["path",{"d":"M15 8h-5"}],["path",{"d":"M19 17V5a2 2 0 0 0-2-2H4"}],["path",{"d":"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3"}]]);
const Sparkles = niceIcon([["path",{"d":"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"}],["path",{"d":"M20 3v4"}],["path",{"d":"M22 5h-4"}],["path",{"d":"M4 17v2"}],["path",{"d":"M5 18H3"}]]);
const SquareStack = niceIcon([["path",{"d":"M4 10c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h4c1.1 0 2 .9 2 2"}],["path",{"d":"M10 16c-1.1 0-2-.9-2-2v-4c0-1.1.9-2 2-2h4c1.1 0 2 .9 2 2"}],["rect",{"width":"8","height":"8","x":"14","y":"14","rx":"2"}]]);
const Type = niceIcon([["polyline",{"points":"4 7 4 4 20 4 20 7"}],["line",{"x1":"9","x2":"15","y1":"20","y2":"20"}],["line",{"x1":"12","x2":"12","y1":"4","y2":"20"}]]);
const Users = niceIcon([["path",{"d":"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}],["circle",{"cx":"9","cy":"7","r":"4"}],["path",{"d":"M22 21v-2a4 4 0 0 0-3-3.87"}],["path",{"d":"M16 3.13a4 4 0 0 1 0 7.75"}]]);
const Wand2 = niceIcon([["path",{"d":"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72"}],["path",{"d":"m14 7 3 3"}],["path",{"d":"M5 6v4"}],["path",{"d":"M19 14v4"}],["path",{"d":"M10 2v2"}],["path",{"d":"M7 8H3"}],["path",{"d":"M21 16h-4"}],["path",{"d":"M11 3H9"}]]);

// ── 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/marketing/MegaMenu.tsx ───────────────────────────
type MegaPreview = { art: number; kind?: 'mesh' | 'landscape'; title: string; meta?: string };
type MegaLink = { label: string; href?: string; icon?: LucideIcon; description?: string; badge?: string; preview?: MegaPreview };
type MegaMenuPanel =
  | { kind: 'grid'; heading?: string; columns: MegaLink[][]; preview?: MegaPreview }
  | { kind: 'list'; heading?: string; links: MegaLink[]; feature?: MegaPreview };
type MegaItem = { label: string; href?: string; menu?: MegaMenuPanel };

/* ——— preview card ——— */

function PreviewCard({ preview, className }: { preview: MegaPreview; className?: string }) {
  const [shown, setShown] = useState(preview);
  const [fade, setFade] = useState(false);
  useEffect(() => {
    if (preview.title === shown.title) return;
    setFade(true);
    const id = window.setTimeout(() => {
      setShown(preview);
      setFade(false);
    }, 140);
    return () => window.clearTimeout(id);
  }, [preview, shown.title]);
  const src = artwork(shown.art, 560, 440, shown.kind ?? 'mesh');
  return (
    <div className={cn('relative overflow-hidden rounded-xl border border-white/[.08] bg-[#1b1b1a]', className)}>
      {src && <img src={src} alt="" className={cn('absolute inset-0 h-full w-full object-cover transition-all duration-300', fade ? 'scale-105 opacity-0' : 'scale-100 opacity-100')} />}
      <div className="absolute inset-0 bg-[linear-gradient(180deg,transparent_40%,rgba(0,0,0,.65))]" />
      <div className={cn('absolute inset-x-4 bottom-4 transition-all duration-300', fade ? 'translate-y-2 opacity-0' : 'opacity-100')}>
        {shown.meta && <p className="font-mono text-[10px] uppercase tracking-[0.16em] text-white/60">{shown.meta}</p>}
        <p className="mt-1 font-serif text-[24px] leading-[1.05] text-white">{shown.title}</p>
      </div>
    </div>
  );
}

/* ——— panel contents ——— */

function GridPanel({ menu, onPick }: { menu: Extract<MegaMenuPanel, { kind: 'grid' }>; onPick: () => void }) {
  const all = menu.columns.flat();
  const [hot, setHot] = useState<MegaLink>(all[0]);
  const preview = hot.preview ?? menu.preview ?? all[0].preview;
  return (
    <div className="flex gap-6 p-5">
      <div>
        {menu.heading && <p className="mb-3 px-2 font-mono text-[10px] uppercase tracking-[0.18em] text-white/40">{menu.heading}</p>}
        <div className="flex gap-2">
          {menu.columns.map((col, ci) => (
            <ul key={ci} className="w-[172px]">
              {col.map((l) => {
                const Icon = l.icon;
                return (
                  <li key={l.label}>
                    <a
                      href={l.href ?? '#'}
                      onPointerEnter={() => setHot(l)}
                      onFocus={() => setHot(l)}
                      onClick={onPick}
                      className={cn('group flex items-center gap-2.5 rounded-lg px-2 py-[7px] text-[13px] outline-none transition-colors', hot === l ? 'bg-white/[.06] text-white' : 'text-white/70 hover:text-white focus-visible:bg-white/[.06]')}
                    >
                      {Icon && <Icon className={cn('h-[15px] w-[15px] shrink-0 transition-colors', hot === l ? 'text-[#c8d5b9]' : 'text-white/40')} strokeWidth={1.7} />}
                      <span className="truncate">{l.label}</span>
                      {l.badge && <span className="ml-auto rounded bg-[#c8d5b9]/15 px-1.5 py-px font-mono text-[9px] uppercase tracking-wider text-[#c8d5b9]">{l.badge}</span>}
                    </a>
                  </li>
                );
              })}
            </ul>
          ))}
        </div>
      </div>
      {preview && <PreviewCard preview={preview} className="hidden w-[230px] self-stretch lg:block" />}
    </div>
  );
}

function ListPanel({ menu, onPick }: { menu: Extract<MegaMenuPanel, { kind: 'list' }>; onPick: () => void }) {
  const [hot, setHot] = useState(0);
  const preview = menu.links[hot]?.preview ?? menu.feature;
  return (
    <div className="flex gap-5 p-4">
      <div>
        {menu.heading && <p className="mb-2 px-3 pt-1 font-mono text-[10px] uppercase tracking-[0.18em] text-white/40">{menu.heading}</p>}
        <ul className="w-[268px] space-y-0.5">
          {menu.links.map((l, i) => {
            const Icon = l.icon;
            return (
              <li key={l.label}>
                <a
                  href={l.href ?? '#'}
                  onPointerEnter={() => setHot(i)}
                  onFocus={() => setHot(i)}
                  onClick={onPick}
                  className={cn('flex gap-3 rounded-lg px-3 py-2.5 outline-none transition-colors', hot === i ? 'bg-white/[.06]' : 'hover:bg-white/[.04]')}
                >
                  {Icon && (
                    <span className={cn('mt-0.5 grid h-7 w-7 shrink-0 place-items-center rounded-md border transition-colors', hot === i ? 'border-[#c8d5b9]/30 text-[#c8d5b9]' : 'border-white/[.08] text-white/50')}>
                      <Icon className="h-3.5 w-3.5" strokeWidth={1.8} />
                    </span>
                  )}
                  <span className="min-w-0">
                    <span className="block text-[13px] font-medium text-white">{l.label}</span>
                    {l.description && <span className="mt-0.5 block text-[12px] leading-snug text-white/50">{l.description}</span>}
                  </span>
                </a>
              </li>
            );
          })}
        </ul>
      </div>
      {preview && <PreviewCard preview={preview} className="hidden w-[260px] self-stretch lg:block" />}
    </div>
  );
}

function Panel({ menu, onPick }: { menu: MegaMenuPanel; onPick: () => void }) {
  return menu.kind === 'grid' ? <GridPanel menu={menu} onPick={onPick} /> : <ListPanel menu={menu} onPick={onPick} />;
}

/* ——— the menu ——— */

type MegaMenuProps = {
  items: MegaItem[];
  /** Left slot, usually the logo. */
  brand?: ReactNode;
  /** Right slot, usually actions. */
  actions?: ReactNode;
  /** Index of a menu to show open on first render (handy for previews). */
  defaultOpen?: number;
  className?: string;
};

/**
 * A desktop mega menu with one shared panel that morphs its size and position
 * between menus, hover intent, a live preview card, keyboard support, and an
 * accordion sheet on small screens.
 */
function MegaMenu({ items, brand, actions, defaultOpen, className }: MegaMenuProps) {
  const [open, setOpen] = useState<number | null>(defaultOpen ?? null);
  const [last, setLast] = useState<number | null>(defaultOpen ?? null);
  const [sheet, setSheet] = useState(false);
  const [acc, setAcc] = useState<number | null>(null);
  const navRef = useRef<HTMLDivElement>(null);
  const triggers = useRef<Array<HTMLButtonElement | HTMLAnchorElement | null>>([]);
  const contents = useRef<Array<HTMLDivElement | null>>([]);
  const [box, setBox] = useState({ x: 0, w: 0, h: 0 });
  const timer = useRef(0);

  const show = useCallback(
    (i: number | null) => {
      window.clearTimeout(timer.current);
      setOpen(i);
      if (i !== null) setLast(i);
    },
    [],
  );
  const later = (i: number | null, ms: number) => {
    window.clearTimeout(timer.current);
    timer.current = window.setTimeout(() => show(i), ms);
  };

  // size and place the shared panel for the active menu
  useLayoutEffect(() => {
    const i = open ?? last;
    if (i === null) return;
    const c = contents.current[i];
    const t = triggers.current[i];
    const nav = navRef.current;
    if (!c || !t || !nav) return;
    const w = c.offsetWidth;
    const h = c.offsetHeight;
    const nr = nav.getBoundingClientRect();
    const tr = t.getBoundingClientRect();
    const center = tr.left - nr.left + tr.width / 2;
    const x = Math.max(0, Math.min(nr.width - w, center - w / 2));
    setBox({ x, w, h });
  }, [open, last]);

  useEffect(() => {
    if (open === null) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        const t = triggers.current[open];
        show(null);
        t?.focus();
      }
    };
    const onDown = (e: PointerEvent) => {
      if (!navRef.current?.contains(e.target as Node)) show(null);
    };
    window.addEventListener('keydown', onKey);
    window.addEventListener('pointerdown', onDown);
    return () => {
      window.removeEventListener('keydown', onKey);
      window.removeEventListener('pointerdown', onDown);
    };
  }, [open, show]);

  useEffect(() => () => window.clearTimeout(timer.current), []);

  const active = open ?? last;

  return (
    <div className={cn('relative', className)}>
      <div ref={navRef} className="relative flex h-16 items-center" onPointerLeave={() => later(null, 180)} onPointerEnter={() => window.clearTimeout(timer.current)}>
        <div className="flex flex-1 items-center">{brand}</div>

        <ul className="hidden items-center gap-1 md:flex">
          {items.map((it, i) => (
            <li key={it.label}>
              {it.menu ? (
                <button
                  ref={(el) => (triggers.current[i] = el)}
                  aria-expanded={open === i}
                  aria-controls="mega-panel"
                  onPointerEnter={(e) => e.pointerType === 'mouse' && (open === null ? later(i, 70) : show(i))}
                  onClick={() => show(open === i ? null : i)}
                  onKeyDown={(e) => {
                    if (e.key === 'ArrowDown') {
                      e.preventDefault();
                      show(i);
                      window.setTimeout(() => contents.current[i]?.querySelector<HTMLAnchorElement>('a')?.focus(), 30);
                    }
                  }}
                  className={cn('flex h-9 items-center gap-1 rounded-lg px-3 text-[13.5px] outline-none transition-colors focus-visible:ring-1 focus-visible:ring-white/30', open === i ? 'bg-white/[.07] text-white' : 'text-white/70 hover:text-white')}
                >
                  {it.label}
                  <ChevronDown className={cn('h-3.5 w-3.5 opacity-60 transition-transform duration-300', open === i && 'rotate-180')} />
                </button>
              ) : (
                <a
                  ref={(el) => (triggers.current[i] = el)}
                  href={it.href ?? '#'}
                  onPointerEnter={() => later(null, 120)}
                  className="flex h-9 items-center rounded-lg px-3 text-[13.5px] text-white/70 outline-none transition-colors hover:text-white focus-visible:ring-1 focus-visible:ring-white/30"
                >
                  {it.label}
                </a>
              )}
            </li>
          ))}
        </ul>

        <div className="hidden flex-1 items-center justify-end gap-2 md:flex">{actions}</div>
        <button onClick={() => setSheet((s) => !s)} aria-expanded={sheet} aria-label={sheet ? 'Close menu' : 'Open menu'} className="ml-auto grid h-10 w-10 place-items-center rounded-lg text-white/80 hover:bg-white/[.06] md:hidden">
          {sheet ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
        </button>

        {/* shared morphing panel */}
        <div
          id="mega-panel"
          role="region"
          aria-label={active !== null ? `${items[active].label} menu` : undefined}
          className={cn(
            'absolute top-[calc(100%+6px)] z-50 hidden origin-top overflow-hidden rounded-2xl border border-white/[.08] bg-[#131312] shadow-[0_30px_80px_-20px_rgba(0,0,0,.8)] md:block',
            'transition-[left,width,height,opacity,transform] duration-[380ms] ease-[cubic-bezier(.2,.8,.2,1)] motion-reduce:transition-none',
            open === null ? 'pointer-events-none -translate-y-1 scale-[.98] opacity-0' : 'opacity-100',
          )}
          style={{ left: box.x, width: box.w, height: box.h }}
        >
          {items.map((it, i) =>
            it.menu ? (
              <div
                key={it.label}
                ref={(el) => (contents.current[i] = el)}
                aria-hidden={active !== i}
                className={cn(
                  'absolute left-0 top-0 w-max transition-all duration-300 ease-out motion-reduce:transition-none',
                  active === i ? 'visible translate-x-0 opacity-100' : cn('invisible opacity-0', i < (active ?? 0) ? '-translate-x-6' : 'translate-x-6'),
                )}
              >
                <Panel menu={it.menu} onPick={() => show(null)} />
              </div>
            ) : null,
          )}
        </div>
      </div>

      {/* small screens: accordion sheet */}
      {sheet && (
        <div className="absolute inset-x-0 top-full z-50 max-h-[75vh] overflow-y-auto rounded-2xl border border-white/[.08] bg-[#121211] p-2 shadow-2xl md:hidden">
          {items.map((it, i) =>
            it.menu ? (
              <div key={it.label} className="border-b border-white/[.05] last:border-0">
                <button onClick={() => setAcc(acc === i ? null : i)} aria-expanded={acc === i} className="flex w-full items-center justify-between px-3 py-3.5 text-[15px] text-white">
                  {it.label}
                  <ChevronDown className={cn('h-4 w-4 text-white/50 transition-transform', acc === i && 'rotate-180')} />
                </button>
                <div className={cn('grid transition-[grid-template-rows] duration-300', acc === i ? 'grid-rows-[1fr]' : 'grid-rows-[0fr]')}>
                  <div className="overflow-hidden">
                    <div className="grid grid-cols-2 gap-1 px-1 pb-3">
                      {(it.menu.kind === 'grid' ? it.menu.columns.flat() : it.menu.links).map((l) => {
                        const Icon = l.icon;
                        return (
                          <a key={l.label} href={l.href ?? '#'} className="flex items-center gap-2 rounded-lg px-2 py-2 text-[13px] text-white/70 hover:bg-white/[.05] hover:text-white">
                            {Icon && <Icon className="h-4 w-4 text-white/40" strokeWidth={1.7} />}
                            {l.label}
                          </a>
                        );
                      })}
                    </div>
                  </div>
                </div>
              </div>
            ) : (
              <a key={it.label} href={it.href ?? '#'} className="flex items-center justify-between border-b border-white/[.05] px-3 py-3.5 text-[15px] text-white last:border-0">
                {it.label}
                <ArrowUpRight className="h-4 w-4 text-white/40" />
              </a>
            ),
          )}
          {actions && <div className="flex gap-2 p-2 pt-3">{actions}</div>}
        </div>
      )}
    </div>
  );
}

// ── pages/landing/shared/motion.tsx ─────────────────────────────
function useInView<T extends Element>(threshold = 0.2) {
  const ref = useRef<T>(null);
  const [inView, setInView] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setInView(true);
          io.disconnect();
        }
      },
      { threshold },
    );
    io.observe(el);
    return () => io.disconnect();
  }, [threshold]);
  return { ref, inView };
}

function Reveal({ children, delay = 0, className }: { children: ReactNode; delay?: number; className?: string }) {
  const { ref, inView } = useInView<HTMLDivElement>(0.15);
  return (
    <div
      ref={ref}
      className={cn('transition-all duration-1000 ease-[cubic-bezier(0.16,1,0.3,1)]', inView ? 'translate-y-0 opacity-100 blur-0' : 'translate-y-6 opacity-0 blur-[2px]', className)}
      style={{ transitionDelay: `${delay}ms` }}
    >
      {children}
    </div>
  );
}

function useCountUp(target: number, active: boolean, duration = 1800) {
  const [val, setVal] = useState(0);
  useEffect(() => {
    if (!active) return;
    let raf = 0;
    const start = performance.now();
    const loop = (now: number) => {
      const t = Math.min(1, (now - start) / duration);
      setVal(target * (1 - Math.pow(2, -10 * t)));
      if (t < 1) raf = requestAnimationFrame(loop);
      else setVal(target);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, [target, active, duration]);
  return val;
}

// ── pages/landing/quarry/ui.tsx ─────────────────────────────────
/** Palette: warm near-black, bone white, stone grey, one sage accent. */
const Q = {
  bg: '#0e0e0d',
  panel: '#151514',
  line: 'rgba(255,255,255,0.07)',
  bone: '#f2efe9',
  stone: '#8b8880',
  sage: '#c8d5b9',
};

function QuarryMark({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 28 28" className={className} aria-hidden>
      <path d="M4 19.5 10.5 14l6 4.5-6 5z" fill="currentColor" opacity=".45" />
      <path d="M11 12.5 17.5 7l6.5 5-6.5 5.2z" fill="currentColor" opacity=".75" />
      <path d="M12.5 21.2 18.5 16.6l5.5 4.2-6 4.7z" fill="currentColor" />
    </svg>
  );
}

function Wordmark() {
  return (
    <span className="flex items-center gap-2 text-[#f2efe9]">
      <QuarryMark className="h-7 w-7" />
      <span className="text-[19px] font-medium tracking-[-0.03em]">quarry</span>
    </span>
  );
}

/** Small mono label in a hairline box. */
function Tag({ children, className }: { children: ReactNode; className?: string }) {
  return (
    <span className={cn('inline-flex items-center gap-2 rounded-md border border-white/[.07] bg-white/[.025] px-3 py-1.5 font-mono text-[10.5px] uppercase tracking-[0.16em] text-[#8b8880]', className)}>
      {children}
    </span>
  );
}

/** Two-tone heading: the first line bone, the second stone. */
function Heading({ tag, a, b, body, center, className }: { tag?: string; a: ReactNode; b?: ReactNode; body?: ReactNode; center?: boolean; className?: string }) {
  return (
    <Reveal className={cn(center && 'text-center', className)}>
      {tag && <Tag>{tag}</Tag>}
      <h2 className={cn('text-[34px] font-medium leading-[1.08] tracking-[-0.035em] md:text-[48px]', tag && 'mt-5')}>
        <span className="text-[#f2efe9]">{a}</span>
        {b && (
          <>
            <br />
            <span className="text-[#8b8880]">{b}</span>
          </>
        )}
      </h2>
      {body && <p className={cn('mt-5 max-w-lg text-[15px] leading-relaxed text-[#8b8880]', center && 'mx-auto')}>{body}</p>}
    </Reveal>
  );
}

function QButton({ children, variant = 'light', className, ...rest }: AnchorHTMLAttributes<HTMLAnchorElement> & { variant?: 'light' | 'dark' | 'ghost' }) {
  return (
    <a
      href="#"
      {...rest}
      className={cn(
        'group inline-flex h-12 items-center justify-center gap-2 rounded-xl px-6 text-[15px] font-medium transition-all duration-200 active:scale-[.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#c8d5b9]/60 focus-visible:ring-offset-2 focus-visible:ring-offset-[#0e0e0d]',
        variant === 'light' && 'bg-[#f2efe9] text-[#141413] hover:bg-white',
        variant === 'dark' && 'bg-[#141413] text-[#f2efe9] hover:bg-black',
        variant === 'ghost' && 'text-[#f2efe9] hover:bg-white/[.05]',
        className,
      )}
    >
      {children}
    </a>
  );
}

// ── pages/landing/quarry/Nav.tsx ────────────────────────────────
const p = (art: number, title: string, meta: string, kind: 'mesh' | 'landscape' = 'landscape') => ({ art, title, meta, kind });

const QUARRY_MENU: MegaItem[] = [
  {
    label: 'Library',
    menu: {
      kind: 'grid',
      heading: 'Page sections',
      columns: [
        [
          { label: 'Navigation', icon: Navigation, preview: p(7, 'Bars that stay out of the way', '24 sections') },
          { label: 'Heroes', icon: LayoutPanelTop, badge: 'New', preview: p(0, 'First screens worth stopping for', '61 sections') },
          { label: 'Features', icon: LayoutGrid, preview: p(2, 'Explain it in one glance', '38 sections', 'mesh') },
          { label: 'Bento grids', icon: Blocks, preview: p(8, 'Tiles that tell a story', '22 sections', 'mesh') },
          { label: 'Pricing', icon: CreditCard, preview: p(9, 'Plans people can compare', '19 sections') },
          { label: 'Dashboards', icon: LayoutDashboard, preview: p(4, 'Product shots that feel real', '15 sections', 'mesh') },
        ],
        [
          { label: 'About', icon: Info, preview: p(5, 'Tell the story behind it', '14 sections') },
          { label: 'Testimonials', icon: Quote, preview: p(6, 'Let customers say it', '27 sections') },
          { label: 'Stats', icon: BarChart3, preview: p(10, 'Numbers that land', '12 sections', 'mesh') },
          { label: 'Team', icon: Users, preview: p(3, 'Faces behind the work', '9 sections') },
          { label: 'Blog', icon: BookOpen, preview: p(11, 'Writing that gets read', '16 sections') },
          { label: 'FAQ', icon: CircleHelp, preview: p(1, 'Answers before the asks', '11 sections', 'mesh') },
        ],
        [
          { label: 'Calls to action', icon: Megaphone, preview: p(9, 'The last nudge', '21 sections', 'mesh') },
          { label: 'Gallery', icon: GalleryHorizontal, preview: p(0, 'Work, beautifully framed', '17 sections') },
          { label: 'Forms', icon: ListChecks, preview: p(7, 'Inputs people finish', '13 sections', 'mesh') },
          { label: 'Coming soon', icon: Hourglass, preview: p(8, 'Build the waitlist', '8 sections') },
          { label: 'Error pages', icon: FileWarning, preview: p(4, 'Lost, but in style', '7 sections') },
          { label: 'Footers', icon: PanelBottom, preview: p(2, 'A tidy place to end', '18 sections') },
        ],
      ],
    },
  },
  {
    label: 'Parts',
    menu: {
      kind: 'list',
      heading: 'UI parts',
      links: [
        { label: 'Type in motion', icon: Type, description: 'Split, stagger and settle headlines', preview: p(6, 'Words that arrive gently', 'Text', 'mesh') },
        { label: 'Buttons', icon: MousePointerClick, description: 'Pressable, magnetic and quiet CTAs', preview: p(9, 'Click-worthy, not loud', 'Buttons', 'mesh') },
        { label: 'Micro-interactions', icon: Sparkles, description: 'Hover, cursor and focus details', preview: p(1, 'The small stuff, done right', 'Details', 'mesh') },
        { label: 'Scroll scenes', icon: ScrollText, description: 'Pin, parallax and reveal on scroll', preview: p(3, 'Pages that unfold', 'Scroll') },
        { label: 'Page transitions', icon: Clapperboard, description: 'Cinematic moves between routes', preview: p(11, 'Cut, don’t jump', 'Motion') },
      ],
    },
  },
  {
    label: 'Templates',
    menu: {
      kind: 'list',
      links: [
        { label: 'Websites', icon: SquareStack, description: 'Whole sites, ready to fill in', preview: p(5, '24 full websites', 'Templates') },
        { label: 'Social posts', icon: Image, description: '1080 × 1350 posts as plain code', preview: p(8, 'Posts as components', 'Social', 'mesh') },
      ],
    },
  },
  {
    label: 'Tools',
    menu: {
      kind: 'list',
      links: [
        { label: 'Palette lab', icon: Palette, description: 'Turn one colour into a full theme', preview: p(1, 'One colour in, a theme out', 'Tool', 'mesh') },
        { label: 'Agent bridge', icon: Bot, description: 'Sections straight into your editor', preview: p(7, 'Ask, and it’s in your code', 'Agents') },
        { label: 'Copy polish', icon: Wand2, description: 'Rewrite headlines in your voice', preview: p(10, 'Headlines with a pulse', 'Tool', 'mesh') },
        { label: 'Changelog', icon: AlignLeft, description: 'What shipped this week', preview: p(0, 'Fresh every Thursday', 'Updates') },
      ],
    },
  },
  { label: 'Pricing', href: '#quarry-pricing' },
  { label: 'FAQ', href: '#quarry-faq' },
];

function QuarryNav() {
  return (
    <header className="sticky top-0 z-40 border-b border-white/[.05] bg-[#0e0e0d]/80 backdrop-blur-xl">
      <div className="mx-auto max-w-[1240px] px-5 md:px-8">
        <MegaMenu
          items={QUARRY_MENU}
          brand={
            <a href="#" aria-label="Quarry home">
              <Wordmark />
            </a>
          }
          actions={
            <>
              <a href="#" className="rounded-lg px-3 py-2 text-[13.5px] text-white/70 hover:text-white">
                Sign in
              </a>
              <a href="#" className="rounded-lg bg-[#f2efe9] px-3.5 py-2 text-[13.5px] font-medium text-[#141413] transition-colors hover:bg-white">
                Get started
              </a>
            </>
          }
        />
      </div>
    </header>
  );
}

// ── components/marketing/MegaMenuDemo.tsx ───────────────────────
/** The mega menu on its own: hover Library, Parts, Templates or Tools. */
export function MegaMenuDemo() {
  return (
    <div className="h-[560px] w-full bg-[#0e0e0d] font-sans">
      <div className="border-b border-white/[.05] px-5 md:px-8">
        <MegaMenu
          items={QUARRY_MENU}
          defaultOpen={0}
          brand={<Wordmark />}
          actions={
            <a href="#" className="rounded-lg bg-[#f2efe9] px-3.5 py-2 text-[13.5px] font-medium text-[#141413] hover:bg-white">
              Get started
            </a>
          }
        />
      </div>
      <div className="px-8 pt-16 md:hidden">
        <p className="text-[13px] text-white/50">Open the menu button for the mobile sheet.</p>
      </div>
    </div>
  );
}
