'use client';

// Hero — Dusk — NiceUI (MIT) · https://niceui.dev/c/marketing/hero-dusk
// One self-contained file: needs only React and Tailwind CSS. Nothing else to install.

import { useEffect, useRef, useState, type ReactNode, useMemo, type CSSProperties, 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 ArrowRight = niceIcon([["path",{"d":"M5 12h14"}],["path",{"d":"m12 5 7 7-7 7"}]]);
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"}]]);

// ── components/marketing/heroes/PixelText.tsx ───────────────────
/* An original 5×7 bitmap face. Each glyph is 7 rows of 5 bits. */
const GLYPHS: Record<string, string> = {
  A: '01110 10001 10001 11111 10001 10001 10001',
  B: '11110 10001 10001 11110 10001 10001 11110',
  C: '01110 10001 10000 10000 10000 10001 01110',
  D: '11110 10001 10001 10001 10001 10001 11110',
  E: '11111 10000 10000 11110 10000 10000 11111',
  F: '11111 10000 10000 11110 10000 10000 10000',
  G: '01110 10001 10000 10111 10001 10001 01111',
  H: '10001 10001 10001 11111 10001 10001 10001',
  I: '11111 00100 00100 00100 00100 00100 11111',
  J: '00111 00010 00010 00010 00010 10010 01100',
  K: '10001 10010 10100 11000 10100 10010 10001',
  L: '10000 10000 10000 10000 10000 10000 11111',
  M: '10001 11011 10101 10101 10001 10001 10001',
  N: '10001 11001 10101 10011 10001 10001 10001',
  O: '01110 10001 10001 10001 10001 10001 01110',
  P: '11110 10001 10001 11110 10000 10000 10000',
  Q: '01110 10001 10001 10001 10101 10010 01101',
  R: '11110 10001 10001 11110 10100 10010 10001',
  S: '01111 10000 10000 01110 00001 00001 11110',
  T: '11111 00100 00100 00100 00100 00100 00100',
  U: '10001 10001 10001 10001 10001 10001 01110',
  V: '10001 10001 10001 10001 10001 01010 00100',
  W: '10001 10001 10001 10101 10101 10101 01010',
  X: '10001 10001 01010 00100 01010 10001 10001',
  Y: '10001 10001 01010 00100 00100 00100 00100',
  Z: '11111 00001 00010 00100 01000 10000 11111',
  '0': '01110 10001 10011 10101 11001 10001 01110',
  '1': '00100 01100 00100 00100 00100 00100 01110',
  '2': '01110 10001 00001 00010 00100 01000 11111',
  '3': '11110 00001 00001 01110 00001 00001 11110',
  '4': '00010 00110 01010 10010 11111 00010 00010',
  '5': '11111 10000 11110 00001 00001 10001 01110',
  '6': '00110 01000 10000 11110 10001 10001 01110',
  '7': '11111 00001 00010 00100 01000 01000 01000',
  '8': '01110 10001 10001 01110 10001 10001 01110',
  '9': '01110 10001 10001 01111 00001 00010 01100',
  '.': '00000 00000 00000 00000 00000 01100 01100',
  ',': '00000 00000 00000 00000 01100 00100 01000',
  "'": '00100 00100 01000 00000 00000 00000 00000',
  '-': '00000 00000 00000 11111 00000 00000 00000',
  '!': '00100 00100 00100 00100 00100 00000 00100',
  '?': '01110 10001 00001 00010 00100 00000 00100',
  '&': '01100 10010 10100 01000 10101 10010 01101',
};

type Px = { x: number; y: number; d: number };

function layout(word: string) {
  const px: Px[] = [];
  const chars = [...word.toUpperCase()];
  chars.forEach((ch, i) => {
    const rows = (GLYPHS[ch] ?? GLYPHS['?']).split(' ');
    rows.forEach((row, y) => {
      for (let x = 0; x < 5; x++) {
        if (row[x] === '1') {
          // stable pseudo-random order for the decode reveal
          const h = Math.sin((i * 31 + x * 7 + y * 13) * 12.9898) * 43758.5453;
          px.push({ x: i * 6 + x, y, d: h - Math.floor(h) });
        }
      }
    });
  });
  return { px, w: chars.length * 6 - 1 };
}

type PixelTextProps = {
  text: string;
  /** Play a pixel-by-pixel decode when it mounts. */
  reveal?: boolean;
  /** Seconds before the reveal starts. */
  delay?: number;
  className?: string;
  /** Gap between words, in em. */
  wordGap?: number;
};

/**
 * Text set in a crisp 5×7 pixel face, one inline SVG per word so it wraps like
 * normal text. Size it with font-size; colour it with `color`.
 */
function PixelText({ text, reveal = true, delay = 0, className, wordGap = 0.42 }: PixelTextProps) {
  const words = useMemo(() => text.split(/\s+/).filter(Boolean).map(layout), [text]);
  // after the decode, each word becomes one merged path so no seams show between pixels
  const total = words.reduce((n, w) => n + w.w, 0);
  const [done, setDone] = useState(!reveal);
  useEffect(() => {
    if (!reveal) return setDone(true);
    setDone(false);
    const id = window.setTimeout(() => setDone(true), (delay + total * 0.012 + 0.9) * 1000);
    return () => window.clearTimeout(id);
  }, [reveal, delay, total, text]);
  let offset = 0;
  return (
    <span className={cn('inline', className)}>
      <span className="sr-only">{text}</span>
      <span aria-hidden="true">
        {words.map((w, wi) => {
          const start = offset;
          offset += w.w;
          return (
            <svg
              key={wi}
              viewBox={`0 0 ${w.w} 7`}
              className="inline-block align-baseline"
              style={{ height: '0.86em', width: `${(w.w / 7) * 0.86}em`, marginRight: wi < words.length - 1 ? `${wordGap}em` : 0 }}
            >
              {done ? (
                <path fill="currentColor" d={w.px.map((p) => `M${p.x} ${p.y}h1v1h-1z`).join('')} />
              ) : w.px.map((p, i) => (
                <rect
                  key={i}
                  x={p.x}
                  y={p.y}
                  width="1.08"
                  height="1.08"
                  fill="currentColor"
                  className={reveal ? 'nui-px' : undefined}
                  style={reveal ? ({ animationDelay: `${delay + (start + p.x) * 0.012 + p.d * 0.35}s` } as CSSProperties) : undefined}
                />
              ))}
            </svg>
          );
        })}
      </span>
      {reveal && (
        <style>{`@keyframes nui-px{0%{opacity:0}40%{opacity:1;fill:#fdba74}100%{opacity:1}}.nui-px{opacity:0;animation:nui-px .5s steps(3,end) forwards}@media (prefers-reduced-motion:reduce){.nui-px{animation:none;opacity:1}}`}</style>
      )}
    </span>
  );
}

// ── components/marketing/heroes/scenery.ts ──────────────────────
/*
 * Procedural scenery for the scenic heroes, painted once to a canvas and cached
 * as a data URL. Swap `src` for your own photo in production.
 */

type RGB = [number, number, number];
const hex = (h: string): RGB => {
  const v = parseInt(h.slice(1), 16);
  return [(v >> 16) & 255, (v >> 8) & 255, v & 255];
};
const clamp = (x: number, a = 0, b = 1) => (x < a ? a : x > b ? b : x);
const smooth = (a: number, b: number, x: number) => {
  const t = clamp((x - a) / (b - a));
  return t * t * (3 - 2 * t);
};
const ramp = (stops: [number, RGB][], t: number): RGB => {
  if (t <= stops[0][0]) return stops[0][1];
  for (let i = 1; i < stops.length; i++) {
    const [p, c] = stops[i];
    if (t <= p) {
      const [p0, c0] = stops[i - 1];
      const k = (t - p0) / (p - p0);
      return [c0[0] + (c[0] - c0[0]) * k, c0[1] + (c[1] - c0[1]) * k, c0[2] + (c[2] - c0[2]) * k];
    }
  }
  return stops[stops.length - 1][1];
};
let seed = 1;
const rnd = () => {
  seed = (seed * 1664525 + 1013904223) >>> 0;
  return seed / 4294967296;
};
const hash = (x: number, y: number) => {
  const h = Math.sin(x * 127.1 + y * 311.7) * 43758.5453;
  return h - Math.floor(h);
};
// smooth 1D value noise
const vnoise = (x: number, s: number) => {
  const i = Math.floor(x);
  const f = x - i;
  const a = hash(i, s);
  const b = hash(i + 1, s);
  return a + (b - a) * f * f * (3 - 2 * f);
};

/* ——— Dusk dunes ——— */

const SKY: [number, RGB][] = [
  [0, hex('#132c33')],
  [0.28, hex('#24434a')],
  [0.5, hex('#5f5a52')],
  [0.68, hex('#b06a48')],
  [0.82, hex('#de8a57')],
  [1, hex('#efa36c')],
];
const SAND: [number, RGB][] = [
  [0, hex('#0f0b0a')],
  [0.16, hex('#1d1311')],
  [0.36, hex('#4a2113')],
  [0.58, hex('#9c3f19')],
  [0.78, hex('#de6527')],
  [0.92, hex('#f28a45')],
  [1, hex('#f8b27a')],
];

function paintDunes(W: number, H: number) {
  const c = document.createElement('canvas');
  c.width = W;
  c.height = H;
  const g = c.getContext('2d')!;
  const img = g.createImageData(W, H);
  const d = img.data;
  // back dune crest: high on the left, sweeping down to the right
  const back = (u: number) => 0.385 - 0.03 * Math.exp(-(((u - 0.36) / 0.16) ** 2)) + 0.24 * smooth(0.42, 1.08, u) + 0.07 * Math.exp(-(((u + 0.02) / 0.14) ** 2)) + 0.006 * Math.sin(u * 23);
  // front dune: a dark shoulder bottom-left that drops away to the right
  const front = (u: number) => 0.62 + 0.05 * Math.sin(u * 2.4 + 0.6) + 0.3 * smooth(0.3, 1.0, u);

  for (let y = 0; y < H; y++) {
    const v = y / H;
    for (let x = 0; x < W; x++) {
      const u = x / W;
      let col: RGB;
      const yb = back(u);
      const yf = front(u);
      if (v < yb) {
        col = ramp(SKY, clamp(v / 0.62));
        // low sun glow on the right horizon
        const glow = Math.exp(-(((u - 0.86) / 0.32) ** 2) - ((v - 0.6) / 0.16) ** 2);
        col = [col[0] + 70 * glow, col[1] + 38 * glow, col[2] + 16 * glow];
      } else {
        const depth = v - yb;
        // lit face: brightest just under the crest toward the sun, falling into shade
        let lit = smooth(0.18, 0.95, u - 0.75 * depth + 0.05) * Math.exp(-depth * 2.1);
        lit = lit * 0.92 + 0.04;
        // wind ripples running diagonally down the slope
        const warp = vnoise(u * 9 + v * 3, 3) * 2.4;
        const rip = Math.sin(v * 210 - u * 70 + warp + Math.sin(u * 13) * 1.4);
        const fine = Math.sin(v * 560 - u * 150 + warp * 1.7);
        lit *= 1 + rip * 0.13 * smooth(0.05, 0.5, lit) + fine * 0.05;
        // a soft rim of light along the crest
        lit += Math.exp(-depth * 90) * 0.18 * smooth(0.2, 0.7, u);
        col = ramp(SAND, clamp(lit));
        if (v > yf) {
          const fd = v - yf;
          const rim = Math.exp(-fd * 120) * 0.35 * smooth(0.35, 0.9, u);
          const sh = 0.05 + rim + 0.04 * Math.sin(v * 260 - u * 40 + warp);
          col = ramp(SAND, clamp(sh));
        }
      }
      // vignette + grain
      const vig = 1 - 0.38 * ((u - 0.5) ** 2 * 1.6 + (v - 0.45) ** 2 * 1.4);
      const n = (hash(x, y) - 0.5) * 22;
      const o = (y * W + x) * 4;
      d[o] = col[0] * vig + n;
      d[o + 1] = col[1] * vig + n;
      d[o + 2] = col[2] * vig + n;
      d[o + 3] = 255;
    }
  }
  g.putImageData(img, 0, 0);
  return c.toDataURL('image/jpeg', 0.88);
}

/* ——— Spring meadow ——— */

const FLOWERS = ['#f472b6', '#fb923c', '#a78bfa', '#facc15', '#ffffff', '#f9a8d4', '#fdba74', '#c084fc'];

function paintMeadow(W: number, H: number) {
  const c = document.createElement('canvas');
  c.width = W;
  c.height = H;
  const g = c.getContext('2d')!;
  seed = 7;
  // sky
  const sky = g.createLinearGradient(0, 0, 0, H);
  sky.addColorStop(0, '#3f8fe6');
  sky.addColorStop(0.35, '#74b3f0');
  sky.addColorStop(0.62, '#bfe0f8');
  sky.addColorStop(0.75, '#e6f3fb');
  g.fillStyle = sky;
  g.fillRect(0, 0, W, H);
  /*
   * Blur is applied once per layer: draw the layer sharp on its own canvas,
   * then composite it with a single blurred drawImage. Setting ctx.filter and
   * then issuing thousands of strokes would blur the whole canvas per stroke,
   * which freezes (and can crash) the tab.
   */
  const layer = document.createElement('canvas');
  layer.width = W;
  layer.height = H;
  const lg = layer.getContext('2d')!;
  const inLayer = (blur: number, draw: (ctx: CanvasRenderingContext2D) => void) => {
    if (!blur) return draw(g);
    lg.clearRect(0, 0, W, H);
    draw(lg);
    g.filter = `blur(${blur}px)`;
    g.drawImage(layer, 0, 0);
    g.filter = 'none';
  };
  // haze clouds
  inLayer(Math.round(W / 40), (g) => {
    for (let i = 0; i < 7; i++) {
      g.fillStyle = `rgba(255,255,255,${0.18 + rnd() * 0.2})`;
      g.beginPath();
      g.ellipse(rnd() * W, H * (0.2 + rnd() * 0.35), W * (0.12 + rnd() * 0.18), H * (0.04 + rnd() * 0.05), 0, 0, Math.PI * 2);
      g.fill();
    }
  });

  // hills, back to front
  const layers = [
    {
      base: 0.6,
      amp: 0.05,
      f: 1.6,
      ph: 0.4,
      top: '#9cc9a2',
      bot: '#86b98e',
      blur: 4,
      flowers: 260,
      size: 1.1,
    },
    {
      base: 0.66,
      amp: 0.06,
      f: 2.3,
      ph: 2.1,
      top: '#7dbb6c',
      bot: '#5d9f4c',
      blur: 2,
      flowers: 700,
      size: 1.6,
    },
    {
      base: 0.73,
      amp: 0.07,
      f: 1.4,
      ph: 4.2,
      top: '#62ad48',
      bot: '#3e8a2c',
      blur: 1,
      flowers: 1400,
      size: 2.4,
    },
    {
      base: 0.84,
      amp: 0.1,
      f: 1.1,
      ph: 1.0,
      top: '#4f9e36',
      bot: '#2c6e1f',
      blur: 0,
      flowers: 2400,
      size: 3.6,
    },
  ];
  layers.forEach((L, li) => {
    const ridge = (u: number) => H * (L.base - L.amp * (Math.sin(u * L.f * Math.PI + L.ph) * 0.6 + Math.sin(u * L.f * 2.7 + L.ph * 2) * 0.4));
    inLayer(L.blur, (g) => {
      const grad = g.createLinearGradient(0, H * (L.base - L.amp), 0, H);
      grad.addColorStop(0, L.top);
      grad.addColorStop(1, L.bot);
      g.fillStyle = grad;
      g.beginPath();
      g.moveTo(0, H);
      for (let x = 0; x <= W; x += 6) g.lineTo(x, ridge(x / W));
      g.lineTo(W, H);
      g.closePath();
      g.fill();
      // grass strokes
      g.lineWidth = 0.6 + li * 0.35;
      for (let i = 0; i < L.flowers * 1.4; i++) {
        const x = rnd() * W;
        const top = ridge(x / W);
        const y = top + Math.pow(rnd(), 1.3) * (H - top);
        const len = (2 + rnd() * 5) * (0.6 + li * 0.45) * (0.6 + (y / H) * 0.8);
        g.strokeStyle = rnd() > 0.5 ? 'rgba(170,220,120,0.35)' : 'rgba(30,80,20,0.3)';
        g.beginPath();
        g.moveTo(x, y);
        g.lineTo(x + (rnd() - 0.5) * 2, y - len);
        g.stroke();
      }
      // flowers, denser and larger toward the viewer
      for (let i = 0; i < L.flowers; i++) {
        const x = rnd() * W;
        const top = ridge(x / W);
        const t = Math.pow(rnd(), 0.8);
        const y = top + 4 + t * (H - top);
        const r = L.size * (0.5 + rnd() * 0.8) * (0.7 + (y / H) * 0.6);
        const col = FLOWERS[Math.floor(rnd() * FLOWERS.length)];
        g.globalAlpha = 0.75 + rnd() * 0.25;
        g.fillStyle = col;
        g.beginPath();
        g.arc(x, y, r, 0, Math.PI * 2);
        g.fill();
      }
      g.globalAlpha = 1;
    });
  });
  // out-of-focus foreground blooms in the corners
  inLayer(Math.round(W / 140), (g) => {
    for (let i = 0; i < 70; i++) {
      const side = rnd() > 0.5 ? rnd() * 0.22 : 0.78 + rnd() * 0.22;
      const x = side * W;
      const y = H * (0.82 + rnd() * 0.2);
      g.globalAlpha = 0.85;
      g.fillStyle = FLOWERS[Math.floor(rnd() * FLOWERS.length)];
      g.beginPath();
      g.arc(x, y, W * (0.006 + rnd() * 0.01), 0, Math.PI * 2);
      g.fill();
    }
    g.globalAlpha = 1;
  });
  // light grain
  const img = g.getImageData(0, 0, W, H);
  const dd = img.data;
  for (let i = 0; i < dd.length; i += 4) {
    const n = (rnd() - 0.5) * 10;
    dd[i] += n;
    dd[i + 1] += n;
    dd[i + 2] += n;
  }
  g.putImageData(img, 0, 0);
  return c.toDataURL('image/jpeg', 0.88);
}

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

/** Paints a scene after first paint and returns its data URL (empty until ready). */
function useScene(kind: 'dunes' | 'meadow', w = 1440, h = 900) {
  const key = `${kind}-${w}-${h}`;
  const [src, setSrc] = useState(() => cache.get(key) ?? '');
  useEffect(() => {
    if (src) return;
    const id = window.setTimeout(() => {
      const url = kind === 'dunes' ? paintDunes(w, h) : paintMeadow(w, h);
      cache.set(key, url);
      setSrc(url);
    }, 30);
    return () => window.clearTimeout(id);
  }, [key, kind, w, h, src]);
  return src;
}

// ── components/marketing/heroes/HeroDusk.tsx ────────────────────
const GRAIN =
  "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix values='0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 .55 0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E\")";

/* Made-up partner marks: a tiny glyph and a wordmark each. */
const MARKS: Array<{ name: string; glyph: ReactNode; className?: string }> = [
  { name: 'halcyon', glyph: <path d="M2 12a8 8 0 0 1 16 0" fill="none" stroke="currentColor" strokeWidth="2" /> },
  { name: 'FERROUS', className: 'tracking-[0.22em] text-[13px] font-semibold', glyph: <path d="M3 4h14v4H8v3h7v4H8v3H3z" fill="currentColor" /> },
  { name: 'orbitly', glyph: <><circle cx="10" cy="10" r="3.5" fill="currentColor" /><ellipse cx="10" cy="10" rx="8.5" ry="3.5" fill="none" stroke="currentColor" strokeWidth="1.5" /></> },
  { name: 'quillon', className: 'italic', glyph: <path d="M4 17 16 3l1 1L5 18z" fill="currentColor" /> },
  { name: 'BASALT', className: 'tracking-[0.18em] text-[13px] font-semibold', glyph: <path d="M10 2 18 7v6l-8 5-8-5V7z" fill="none" stroke="currentColor" strokeWidth="1.8" /> },
  { name: 'tessera', glyph: <><rect x="2" y="2" width="7" height="7" fill="currentColor" /><rect x="11" y="11" width="7" height="7" fill="currentColor" /><rect x="11" y="2" width="7" height="7" fill="none" stroke="currentColor" strokeWidth="1.5" /></> },
  { name: 'lumenco', className: 'font-semibold', glyph: <><circle cx="10" cy="10" r="4" fill="currentColor" /><path d="M10 1v3M10 16v3M1 10h3M16 10h3" stroke="currentColor" strokeWidth="1.8" /></> },
];

const NAV = ['Platform', 'Features', 'Insights', 'Pricing'];

function RidgeMark() {
  return (
    <svg viewBox="0 0 24 24" className="h-[22px] w-[22px]" aria-hidden>
      <path d="M2 19 10 6l3.5 5.5L16 8l6 11z" fill="#f26b2c" />
      <path d="M7.5 19 10 14.8 12.6 19z" fill="#121212" />
    </svg>
  );
}

export type HeroDuskProps = {
  title?: string;
  subtitle?: string;
  cta?: string;
  /** Optional photo URL; a painted dusk landscape is used when omitted. */
  image?: string;
  className?: string;
};

/**
 * A cinematic dusk hero: grainy landscape, pixel-set headline that decodes in,
 * a boxed segmented nav, and a divided logo strip along the bottom edge.
 */
export function HeroDusk({
  title = 'See the signal in every hard call',
  subtitle = 'Pull metrics, bets and debates into one calm view, so your team can commit to the next move with confidence.',
  cta = 'Book a walkthrough',
  image,
  className,
}: HeroDuskProps) {
  const painted = useScene('dunes', 1440, 900);
  const src = image ?? painted;
  const [active, setActive] = useState(0);
  const [menu, setMenu] = useState(false);
  const navRef = useRef<HTMLDivElement>(null);
  const [pill, setPill] = useState({ x: 0, w: 0 });
  const sceneRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const el = navRef.current?.querySelectorAll<HTMLButtonElement>('button')[active];
    if (el) setPill({ x: el.offsetLeft, w: el.offsetWidth });
  }, [active]);

  // gentle pointer parallax on the landscape
  useEffect(() => {
    const root = sceneRef.current?.parentElement;
    if (!root || window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const move = (e: PointerEvent) => {
      const r = root.getBoundingClientRect();
      const dx = (e.clientX - r.left) / r.width - 0.5;
      const dy = (e.clientY - r.top) / r.height - 0.5;
      if (sceneRef.current) sceneRef.current.style.transform = `translate3d(${dx * -14}px, ${dy * -8}px, 0) scale(1.06)`;
    };
    root.addEventListener('pointermove', move);
    return () => root.removeEventListener('pointermove', move);
  }, []);

  return (
    <section data-fill className={cn('relative isolate flex min-h-[720px] flex-col overflow-hidden bg-[#0e0b0a] font-sans text-white', className)}>
      <style>{`@keyframes dusk-in{from{opacity:0;transform:scale(1.14)}to{opacity:1;transform:scale(1.06)}}@keyframes dusk-grain{0%{transform:translate(0,0)}25%{transform:translate(-3%,2%)}50%{transform:translate(2%,-3%)}75%{transform:translate(-2%,-1%)}100%{transform:translate(0,0)}}@keyframes dusk-up{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:none}}@media (prefers-reduced-motion:reduce){.dusk-anim{animation:none!important}}`}</style>

      {/* landscape */}
      <div ref={sceneRef} className="absolute inset-0 -z-20 transition-transform duration-700 ease-out" style={{ transform: 'scale(1.06)' }}>
        <div className="absolute inset-0 bg-[linear-gradient(180deg,#152f35,#5c5650_52%,#2a1712_70%,#0e0b0a)]" />
        {src && <img src={src} alt="" className="dusk-anim absolute inset-0 h-full w-full object-cover" style={{ animation: 'dusk-in 2.4s cubic-bezier(.2,.7,.2,1) both' }} />}
      </div>
      {/* legibility and grain */}
      <div className="absolute inset-0 -z-10 bg-[linear-gradient(90deg,rgba(10,8,7,.72),rgba(10,8,7,.25)_55%,transparent),linear-gradient(0deg,rgba(10,8,7,.85),transparent_45%)]" />
      <div aria-hidden className="dusk-anim pointer-events-none absolute -inset-[10%] -z-10 opacity-[.16] mix-blend-overlay" style={{ backgroundImage: GRAIN, animation: 'dusk-grain .9s steps(4) infinite' }} />

      {/* nav */}
      <header className="relative z-20 mx-auto flex w-full max-w-[1240px] items-center justify-between px-5 pt-6 md:px-10 md:pt-8">
        <a href="#" className="flex h-11 items-center gap-2.5 border border-white/10 bg-black/55 px-4 backdrop-blur-md" aria-label="Ridge home">
          <RidgeMark />
          <PixelText text="RIDGE" reveal={false} className="text-[17px] text-white/95" />
        </a>
        <nav aria-label="Primary" className="hidden md:block">
          <div ref={navRef} className="relative flex h-11 items-center border border-white/10 bg-black/55 p-1 backdrop-blur-md">
            <span aria-hidden className="absolute inset-y-1 bg-white/[.09] shadow-[inset_0_0_0_1px_rgba(255,255,255,.06)] transition-all duration-500 ease-[cubic-bezier(.3,1.3,.5,1)]" style={{ left: pill.x, width: pill.w }} />
            {NAV.map((n, i) => (
              <button
                key={n}
                onClick={() => setActive(i)}
                aria-current={active === i ? 'page' : undefined}
                className={cn('relative z-10 h-full px-5 text-[14px] transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-orange-400', active === i ? 'text-white' : 'text-white/60 hover:text-white')}
              >
                {n}
              </button>
            ))}
          </div>
        </nav>
        <button
          onClick={() => setMenu((m) => !m)}
          aria-expanded={menu}
          aria-label={menu ? 'Close menu' : 'Open menu'}
          className="flex h-11 w-11 items-center justify-center border border-white/10 bg-black/55 backdrop-blur-md md:hidden"
        >
          {menu ? <X className="h-4 w-4" /> : <Menu className="h-4 w-4" />}
        </button>
        {menu && (
          <div className="absolute inset-x-5 top-[72px] border border-white/10 bg-black/80 p-1.5 backdrop-blur-xl md:hidden" style={{ animation: 'dusk-up .25s ease both' }}>
            {NAV.map((n, i) => (
              <button key={n} onClick={() => { setActive(i); setMenu(false); }} className={cn('block w-full px-4 py-3 text-left text-[15px]', active === i ? 'bg-white/[.08] text-white' : 'text-white/65')}>
                {n}
              </button>
            ))}
          </div>
        )}
      </header>

      {/* copy */}
      <div className="relative z-10 mx-auto flex w-full max-w-[1240px] flex-1 flex-col justify-end px-5 pb-14 pt-24 md:px-10 md:pb-20">
        <h1 className="max-w-[16ch] text-[34px] leading-[1.16] text-white sm:text-[48px] lg:max-w-[22ch] lg:text-[66px]">
          <PixelText text={title} delay={0.4} />
        </h1>
        <p className="dusk-anim mt-6 max-w-[34rem] text-[16px] leading-relaxed text-white/70 md:text-[19px]" style={{ animation: 'dusk-up .8s 1.1s ease both' }}>
          {subtitle}
        </p>
        <div className="dusk-anim mt-9 flex flex-wrap items-center gap-5" style={{ animation: 'dusk-up .8s 1.3s ease both' }}>
          <a href="#" className="group inline-flex h-12 items-center gap-2 border border-white/10 bg-white/[.12] px-6 text-[15px] text-white backdrop-blur-md transition-colors hover:bg-white/[.2] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-orange-400">
            {cta}
            <ArrowRight className="h-4 w-4 -translate-x-1 opacity-0 transition-all duration-300 group-hover:translate-x-0 group-hover:opacity-100" />
          </a>
          <a href="#" className="text-[14px] text-white/60 underline-offset-4 transition-colors hover:text-white hover:underline">
            Watch the 2-minute tour
          </a>
        </div>
      </div>

      {/* logo strip */}
      <div className="relative z-10 grid grid-cols-3 border-t border-white/[.08] bg-black/35 backdrop-blur-sm sm:grid-cols-4 lg:grid-cols-7">
        {MARKS.map((m, i) => (
          <div
            key={m.name}
            className={cn(
              'flex h-[72px] items-center justify-center gap-2 border-white/[.08] text-[15px] text-white/45 transition-colors hover:text-white/85 md:h-[88px] md:text-[17px] [&:not(:last-child)]:border-r',
              i >= 3 && 'hidden sm:flex',
              i >= 4 && 'sm:hidden lg:flex',
            )}
          >
            <svg viewBox="0 0 20 20" className="h-[18px] w-[18px]" aria-hidden>
              {m.glyph}
            </svg>
            <span className={m.className}>{m.name}</span>
          </div>
        ))}
      </div>
    </section>
  );
}

export function HeroDuskDemo() {
  return <HeroDusk />;
}
