'use client'

import React, { useEffect, useRef, useState } from 'react'
import { cn } from '@/utilities/ui'
import { InfiniteSlider } from '@/components/ui/infinite-slider'
import { ArrowRightIcon, PhoneCallIcon } from 'lucide-react'
import { createPortal } from 'react-dom'
import { MenuToggleIcon } from '@/components/ui/menu-toggle-icon'
import { useScroll } from '@/components/ui/use-scroll'
import { useThemeMode } from '@/hooks/useThemeMode'
import { CMSLink } from '@/components/Link'
import RichText from '@/components/RichText'
import type { Page } from '@/payload-types'
import { Button } from '@/components/ui/button'

// ─── Types ────────────────────────────────────────────────────────────────────

interface Star {
  x: number; y: number; r: number
  v: number; baseAlpha: number
  phase: number; twinkleSpeed: number
  vx: number; vy: number
}

interface Wave {
  amp: number; freq: number; speed: number
  phase: number; yBase: number; width: number; v: number
}

// ─── Constants ───────────────────────────────────────────────────────────────

const STAR_TONES = [255, 210, 160, 110, 65]
const WAVE_TONES = [55, 90, 125, 165, 205]
const WAVE_CONFIGS = [
  { amp: 26, freq: 0.011, speed: 0.35, phase: 0.0, yBase: 0.38, width: 1.6, toneIdx: 0 },
  { amp: 20, freq: 0.015, speed: 0.50, phase: 1.3, yBase: 0.52, width: 1.8, toneIdx: 1 },
  { amp: 30, freq: 0.008, speed: 0.28, phase: 2.6, yBase: 0.63, width: 2.2, toneIdx: 2 },
  { amp: 16, freq: 0.019, speed: 0.65, phase: 0.8, yBase: 0.74, width: 2.0, toneIdx: 3 },
  { amp: 22, freq: 0.013, speed: 0.42, phase: 3.2, yBase: 0.85, width: 2.6, toneIdx: 4 },
]

// ─── Canvas helpers ───────────────────────────────────────────────────────────

function makeStars(W: number, H: number): Star[] {
  return Array.from({ length: 180 }, () => {
    const i = Math.floor(Math.random() * STAR_TONES.length)
    return {
      x: Math.random() * W, y: Math.random() * H,
      r: 0.4 + Math.random() * 1.6,
      v: STAR_TONES[i], baseAlpha: 0.5 + i * 0.1,
      phase: Math.random() * Math.PI * 2,
      twinkleSpeed: 0.8 + Math.random() * 2.0,
      vx: (Math.random() - 0.5) * 0.3,
      vy: (Math.random() - 0.5) * 0.15,
    }
  })
}

function makeWaves(): Wave[] {
  return WAVE_CONFIGS.map(c => ({ ...c, v: WAVE_TONES[c.toneIdx] }))
}

function drawStars(ctx: CanvasRenderingContext2D, stars: Star[], W: number, H: number, ga: number) {
  const now = Date.now() / 1000
  for (const s of stars) {
    s.x += s.vx; s.y += s.vy
    if (s.x < 0) s.x = W; if (s.x > W) s.x = 0
    if (s.y < 0) s.y = H; if (s.y > H) s.y = 0
    const tw = 0.35 + 0.65 * ((Math.sin(now * s.twinkleSpeed + s.phase) + 1) / 2)
    ctx.beginPath()
    ctx.arc(s.x, s.y, s.r, 0, Math.PI * 2)
    ctx.fillStyle = `rgba(${s.v},${s.v},${s.v},${s.baseAlpha * tw * ga})`
    ctx.fill()
  }
}

function wavePts(w: Wave, W: number, H: number, now: number) {
  const pts: { x: number; y: number }[] = []
  for (let x = 0; x <= W; x += 8)
    pts.push({ x, y: H * w.yBase + Math.sin(x * w.freq + w.phase + now * w.speed) * w.amp })
  return pts
}

function wavePath(ctx: CanvasRenderingContext2D, pts: { x: number; y: number }[]) {
  ctx.beginPath()
  ctx.moveTo(pts[0].x, pts[0].y)
  for (let i = 0; i < pts.length - 1; i++) {
    const mx = (pts[i].x + pts[i + 1].x) / 2
    const my = (pts[i].y + pts[i + 1].y) / 2
    ctx.quadraticCurveTo(pts[i].x, pts[i].y, mx, my)
  }
  ctx.lineTo(pts[pts.length - 1].x, pts[pts.length - 1].y)
}

function drawWaves(ctx: CanvasRenderingContext2D, waves: Wave[], W: number, H: number, ga: number, bgR: number) {
  const now = Date.now() / 1000
  const bg = Math.round(bgR)
  for (const w of waves) {
    const v = w.v
    const yBase = H * w.yBase
    const pts = wavePts(w, W, H, now)
    const grad = ctx.createLinearGradient(0, yBase - w.amp, 0, yBase + w.amp * 3)
    grad.addColorStop(0,   `rgba(${v},${v},${v},${0.030 * ga})`)
    grad.addColorStop(0.4, `rgba(${v},${v},${v},${0.012 * ga})`)
    grad.addColorStop(1,   `rgba(${bg},${bg},${bg},0)`)
    wavePath(ctx, pts)
    ctx.lineTo(W, H); ctx.lineTo(0, H); ctx.closePath()
    ctx.fillStyle = grad
    ctx.fill()
    wavePath(ctx, pts)
    ctx.strokeStyle = `rgba(${v},${v},${v},${0.85 * ga})`
    ctx.lineWidth = w.width
    ctx.lineJoin = 'round'
    ctx.lineCap = 'round'
    ctx.stroke()
  }
}

// ─── Background canvas ────────────────────────────────────────────────────────

function Background({ isDark }: { isDark: boolean }) {
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const darkRef = useRef(isDark)
  useEffect(() => { darkRef.current = isDark }, [isDark])

  useEffect(() => {
    const canvas = canvasRef.current
    if (!canvas) return
    const ctx = canvas.getContext('2d')
    if (!ctx) return
    let W = 0, H = 0
    let stars: Star[] = [], waves: Wave[] = []
    let bgR = 0, bgG = 0, bgB = 0, crossfade = 0
    let rafId: number

    function resize() {
      W = canvas!.width = canvas!.offsetWidth
      H = canvas!.height = canvas!.offsetHeight
      stars = makeStars(W, H)
      waves = makeWaves()
    }

    function loop() {
      const dark = darkRef.current
      const tBg = dark ? 0 : 255
      const tCross = dark ? 0 : 1
      bgR += (tBg - bgR) * 0.04
      bgG += (tBg - bgG) * 0.04
      bgB += (tBg - bgB) * 0.04
      crossfade += (tCross - crossfade) * 0.03
      ctx!.fillStyle = `rgb(${Math.round(bgR)},${Math.round(bgG)},${Math.round(bgB)})`
      ctx!.fillRect(0, 0, W, H)
      const sa = 1 - crossfade, wa = crossfade
      if (sa > 0.01) drawStars(ctx!, stars, W, H, sa)
      if (wa > 0.01) drawWaves(ctx!, waves, W, H, wa, bgR)
      rafId = requestAnimationFrame(loop)
    }

    const ro = new ResizeObserver(resize)
    ro.observe(canvas)
    resize()
    rafId = requestAnimationFrame(loop)
    return () => { cancelAnimationFrame(rafId); ro.disconnect() }
  }, [])

  return <canvas ref={canvasRef} style={{ display: 'block', width: '100%', height: '100%' }} />
}

// ─── Hero section ─────────────────────────────────────────────────────────────

type HeroProps = Pick<Page['hero'], 'richText' | 'links'>

function HeroSection({ isDark, richText, links }: HeroProps & { isDark: boolean }) {
  const muted = isDark ? 'text-white/55' : 'text-black/55'
  const borderLine = isDark ? 'bg-white/10' : 'bg-black/10'
  const borderLineFaint = isDark ? 'bg-white/5' : 'bg-black/5'
  const richTextColor = isDark ? 'text-white' : 'text-black'

  return (
    <section className="relative mx-auto w-full max-w-5xl">
      {/* Vertical border lines */}
      <div aria-hidden="true" className="absolute inset-0 mx-auto hidden min-h-screen w-full max-w-5xl lg:block pointer-events-none">
        <div className={cn('mask-y-from-80% mask-y-to-100% absolute inset-y-0 left-0 z-10 h-full w-px', borderLine)} />
        <div className={cn('mask-y-from-80% mask-y-to-100% absolute inset-y-0 right-0 z-10 h-full w-px', borderLine)} />
      </div>

      {/* Inner vertical border lines */}
      <div aria-hidden="true" className="absolute inset-0 -z-[1] size-full overflow-hidden pointer-events-none">
        <div className={cn('absolute inset-y-0 left-4 w-px bg-linear-to-b from-transparent via-border to-border md:left-8', borderLine)} />
        <div className={cn('absolute inset-y-0 right-4 w-px bg-linear-to-b from-transparent via-border to-border md:right-8', borderLine)} />
        <div className={cn('absolute inset-y-0 left-8 w-px bg-linear-to-b from-transparent via-border/50 to-border/50 md:left-12', borderLineFaint)} />
        <div className={cn('absolute inset-y-0 right-8 w-px bg-linear-to-b from-transparent via-border/50 to-border/50 md:right-12', borderLineFaint)} />
      </div>

      <div className="relative flex flex-col items-center justify-center gap-5 pt-32 pb-28 px-6 text-center">

        {/* Rich text from Payload */}
        {richText && (
          <RichText
            className={cn(
              'fade-in slide-in-from-bottom-10 animate-in fill-mode-backwards delay-100 duration-500 ease-out',
              'max-w-[36.5rem] text-center',
              richTextColor
            )}
            data={richText}
            enableGutter={false}
          />
        )}

        {/* Links from Payload */}
        {Array.isArray(links) && links.length > 0 && (
          <div className="fade-in slide-in-from-bottom-10 animate-in fill-mode-backwards delay-300 duration-500 ease-out flex flex-wrap items-center justify-center gap-3 pt-2">
            {links.map(({ link }, i) => (
              <CMSLink
                key={i}
                {...link}
                className={cn(
                  'flex items-center gap-2 rounded-full px-5 py-2.5 text-sm font-medium transition-all',
                  i === 0
                    ? isDark
                      ? 'bg-white text-black hover:bg-white/90'
                      : 'bg-black text-white hover:bg-black/85'
                    : isDark
                      ? 'border border-white/25 text-white hover:bg-white/8'
                      : 'border border-black/20 text-black hover:bg-black/5'
                )}
              />
            ))}
          </div>
        )}

      </div>
    </section>
  )
}

// ─── Logo cloud ───────────────────────────────────────────────────────────────

const LOGOS = [
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/aftereffects-plain.svg', alt: 'aftereffects' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/almalinux-original.svg', alt: 'almalinux' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/amazonwebservices-original-wordmark.svg', alt: 'amazonwebservices' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/android-plain-wordmark.svg', alt: 'android' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/angularjs-plain-wordmark.svg', alt: 'angularjs' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/apache-line-wordmark.svg', alt: 'apache' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/apple-original.svg', alt: 'apple' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/azure-original-wordmark.svg', alt: 'azure' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/blender-original.svg', alt: 'blender' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/bootstrap-plain-wordmark.svg', alt: 'bootstrap' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/cloudflare-original-wordmark.svg', alt: 'cloudflare' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/cpanel-original-wordmark.svg', alt: 'cpanel' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/docker-plain-wordmark.svg', alt: 'docker' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/drupal-plain-wordmark.svg', alt: 'drupal' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/eslint-plain-wordmark.svg', alt: 'eslint' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/expo-original-wordmark.svg', alt: 'expo' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/figma-original.svg', alt: 'figma' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/flutter-original.svg', alt: 'flutter' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/forgejo-original.svg', alt: 'forgejo' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/fusion-original.svg', alt: 'fusion' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/gimp-original.svg', alt: 'gimp' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/github-original-wordmark.svg', alt: 'github' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/gitlab-plain-wordmark.svg', alt: 'gitlab' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/googlecloud-original-wordmark.svg', alt: 'googlecloud' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/html5-original-wordmark.svg', alt: 'html5' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/illustrator-original.svg', alt: 'illustrator' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/inkscape-plain-wordmark.svg', alt: 'inkscape' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/javascript-original.svg', alt: 'javascript' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/jira-original-wordmark.svg', alt: 'jira' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/jquery-plain-wordmark.svg', alt: 'jquery' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/kalilinux-original-wordmark.svg', alt: 'kalilinux' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/linux-original.svg', alt: 'linux' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/magento-plain-wordmark.svg', alt: 'magento' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/mongodb-original-wordmark.svg', alt: 'mongodb' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/nextjs-original-wordmark.svg', alt: 'nextjs' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/nginx-original.svg', alt: 'nginx' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/nodejs-original-wordmark.svg', alt: 'nodejs' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/opencl-original.svg', alt: 'opencl' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/photoshop-original.svg', alt: 'photoshop' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/php-original.svg', alt: 'php' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/premierepro-original.svg', alt: 'premierepro' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/prometheus-plain-wordmark.svg', alt: 'prometheus' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/proxmox-original-wordmark.svg', alt: 'proxmox' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/python-original-wordmark.svg', alt: 'python' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/rails-plain-wordmark.svg', alt: 'rails' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/reactnative-original-wordmark.svg', alt: 'reactnative' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/reactnavigation-original.svg', alt: 'reactnavigation' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/slack-original-wordmark.svg', alt: 'slack' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/swift-original-wordmark.svg', alt: 'swift' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/typescript-original.svg', alt: 'typescript' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/web3js-original.svg', alt: 'web3js' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/wordpress-original.svg', alt: 'wordpress' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/xcode-original.svg', alt: 'xcode' },
  { src: 'https://portfolio-media.s3web.bymackie.com/Skill_logo/zend-original-wordmark.svg', alt: 'zend' },
]

function LogosSection({ isDark }: { isDark: boolean }) {
  const text   = isDark ? 'text-white/40' : 'text-black/40'
  const border = isDark ? 'border-white/10' : 'border-black/10'

  return (
    <section className={cn('relative border-t py-8', border)}>
      <p className={cn('mb-6 text-center text-xs tracking-widest uppercase px-6', text)}>
        Skills
      </p>
      <div className="[mask-image:linear-gradient(to_right,transparent,black,transparent)]">
        <InfiniteSlider gap={42} duration={35}>
          {LOGOS.map((l) => (
            <img
              key={l.alt}
              src={l.src}
              alt={l.alt}
              className={cn(
                'h-5 w-auto flex-shrink-0 pointer-events-none select-none',
                isDark ? 'brightness-0 invert opacity-30' : 'brightness-0 opacity-25'
              )}
            />
          ))}
        </InfiniteSlider>
      </div>
    </section>
  )
}

// ─── Main export ──────────────────────────────────────────────────────────────

interface HeroPageProps {
  richText?: Page['hero']['richText']
  links?: Page['hero']['links']
  children?: React.ReactNode
}

export default function HeroPage({ richText, links, children }: HeroPageProps) {
  const { isDark, toggle } = useThemeMode()

  return (
    <div style={{ position: 'relative', minHeight: '100vh' }}>

      {/* Canvas background — fixed behind everything */}
      <div style={{ position: 'fixed', inset: 0, zIndex: -1 }}>
        <Background isDark={isDark} />
      </div>

      {/* Page content */}
      <div style={{ position: 'relative', zIndex: 1 }}>
        <main>
          <HeroSection isDark={isDark} richText={richText} links={links} />
          <LogosSection isDark={isDark} />
          {children && (
            <div id="skills">
              {children}
            </div>
          )}
        </main>
      </div>

    </div>
  )
}
