'use client'

import * as React from 'react'
import { motion, useInView, useReducedMotion } from 'framer-motion'
import { cn } from '@/lib/utils'

/* ------------------------------------------------------------------ */
/* Reveal — animates children into view on scroll                     */
/*                                                                    */
/* To avoid SSR/client hydration mismatches we render a PLAIN <Tag>    */
/* (no motion props, no inline styles) until the component has         */
/* mounted on the client. After mount, we switch to <MotionTag> with   */
/* the initial/animate props. The plain tag and the motion tag both    */
/* render the same HTML element type (e.g. <div>), so React preserves  */
/* the DOM node and `useInView` keeps tracking the same element.       */
/* ------------------------------------------------------------------ */
export function Reveal({
  children,
  className,
  delay = 0,
  y = 24,
  as = 'div',
}: {
  children: React.ReactNode
  className?: string
  delay?: number
  y?: number
  as?: 'div' | 'section' | 'article' | 'li' | 'span'
}) {
  const ref = React.useRef<HTMLDivElement>(null)
  const inView = useInView(ref, { once: true, margin: '-80px' })
  const reduce = useReducedMotion()
  const [mounted, setMounted] = React.useState(false)

  React.useEffect(() => {
    setMounted(true)
  }, [])

  // Before mount (SSR + first client render) OR when reduced motion is
  // requested, render a plain tag with NO inline animation styles.
  // This guarantees that the SSR HTML and first client render match.
  if (!mounted || reduce) {
    const Tag = as as 'div'
    return (
      <Tag ref={ref as React.RefObject<HTMLDivElement>} className={className}>
        {children}
      </Tag>
    )
  }

  const MotionTag = motion[as] as typeof motion.div

  return (
    <MotionTag
      ref={ref}
      initial={{ opacity: 0, y }}
      animate={inView ? { opacity: 1, y: 0 } : { opacity: 0, y }}
      transition={{ duration: 0.7, delay, ease: [0.2, 0.8, 0.2, 1] }}
      className={className}
    >
      {children}
    </MotionTag>
  )
}

/* ------------------------------------------------------------------ */
/* Eyebrow — small uppercase label                                    */
/* ------------------------------------------------------------------ */
export function Eyebrow({
  children,
  className,
  tone = 'emerald',
}: {
  children: React.ReactNode
  className?: string
  tone?: 'emerald' | 'sage' | 'light'
}) {
  const tones: Record<string, string> = {
    emerald: 'text-[#0d5d50] dark:text-[#8fb9ad]',
    sage: 'text-[#6f9f91]',
    light: 'text-[#83aa9f]',
  }
  return (
    <span
      className={cn(
        'text-[11px] font-bold uppercase tracking-[0.22em]',
        tones[tone],
        className
      )}
    >
      {children}
    </span>
  )
}

/* ------------------------------------------------------------------ */
/* PageShell — top-level wrapper for every interior page              */
/* ------------------------------------------------------------------ */
export function PageShell({ children }: { children: React.ReactNode }) {
  return (
    <div className="pt-[120px] pb-0">{children}</div>
  )
}

/* ------------------------------------------------------------------ */
/* PageHero — cinematic hero for interior pages                       */
/* ------------------------------------------------------------------ */
export function PageHero({
  index,
  eyebrow,
  title,
  highlight,
  lead,
  image,
  align = 'left',
}: {
  index: string
  eyebrow: string
  title: string
  highlight?: string
  lead: string
  image?: string
  align?: 'left' | 'center'
}) {
  return (
    <section
      className={cn(
        'relative overflow-hidden bg-[#101715] text-white',
        align === 'center' && 'text-center'
      )}
    >
      {image && (
        <div className="absolute inset-0">
          <img
            src={image}
            alt=""
            className="h-full w-full object-cover opacity-40"
            loading="eager"
          />
          <div className="absolute inset-0 bg-gradient-to-r from-[#071815]/95 via-[#071815]/70 to-[#071815]/30" />
        </div>
      )}
      {!image && (
        <>
          <div className="absolute -right-32 -top-32 h-[420px] w-[420px] rounded-full bg-[#15584e]/25 blur-3xl" />
          <div className="absolute -left-20 bottom-0 h-[320px] w-[320px] rounded-full bg-[#0d5d50]/15 blur-3xl" />
          <div className="mesh absolute inset-0 opacity-20" />
        </>
      )}

      <div className="relative mx-auto max-w-[1440px] px-5 py-20 sm:px-8 lg:px-12 lg:py-28">
        <Reveal>
          <Eyebrow tone="sage" className={cn(align === 'center' && 'justify-center')}>
            {eyebrow} / {index}
          </Eyebrow>
        </Reveal>
        <Reveal delay={0.1}>
          <h1 className="mt-6 max-w-4xl text-4xl font-semibold leading-[1.02] tracking-[-0.05em] sm:text-6xl lg:text-7xl">
            {title}{' '}
            {highlight && (
              <span className="font-normal text-[#bdd4cd]">{highlight}</span>
            )}
          </h1>
        </Reveal>
        <Reveal delay={0.2}>
          <p
            className={cn(
              'mt-7 max-w-2xl text-base leading-7 text-white/75 sm:text-lg',
              align === 'center' && 'mx-auto'
            )}
          >
            {lead}
          </p>
        </Reveal>
      </div>
      <div className="absolute bottom-0 left-0 h-px w-full bg-white/15" />
    </section>
  )
}

/* ------------------------------------------------------------------ */
/* Section — consistent vertical rhythm                               */
/* ------------------------------------------------------------------ */
export function Section({
  children,
  className,
  tone = 'light',
  id,
}: {
  children: React.ReactNode
  className?: string
  tone?: 'light' | 'dark' | 'pearl' | 'emerald'
  id?: string
}) {
  const tones: Record<string, string> = {
    light: 'bg-background text-foreground',
    dark: 'bg-[#101715] text-white',
    pearl: 'bg-[#eef1ec] dark:bg-[#0f1715] text-foreground',
    emerald: 'bg-[#0b3b34] text-white',
  }
  return (
    <section id={id} className={cn('py-20 sm:py-28 lg:py-32', tones[tone], className)}>
      <div className="mx-auto max-w-[1440px] px-5 sm:px-8 lg:px-12">
        {children}
      </div>
    </section>
  )
}

/* ------------------------------------------------------------------ */
/* SectionHeading — title + optional lead                             */
/* ------------------------------------------------------------------ */
export function SectionHeading({
  index,
  eyebrow,
  title,
  highlight,
  lead,
  tone = 'light',
  className,
}: {
  index?: string
  eyebrow: string
  title: string
  highlight?: string
  lead?: string
  tone?: 'light' | 'dark'
  className?: string
}) {
  return (
    <Reveal className={cn('grid gap-8 lg:grid-cols-[0.7fr_1.3fr]', className)}>
      <div>
        <Eyebrow tone={tone === 'dark' ? 'sage' : 'emerald'}>
          {eyebrow}
          {index && ` / ${index}`}
        </Eyebrow>
      </div>
      <div>
        <h2
          className={cn(
            'max-w-4xl text-3xl font-semibold leading-[1.05] tracking-[-0.045em] sm:text-5xl lg:text-6xl',
            tone === 'dark' && 'text-white'
          )}
        >
          {title}{' '}
          {highlight && (
            <span className={tone === 'dark' ? 'text-[#7a9a91]' : 'text-[#6e837c]'}>
              {highlight}
            </span>
          )}
        </h2>
        {lead && (
          <p
            className={cn(
              'mt-6 max-w-2xl text-base leading-7',
              tone === 'dark' ? 'text-white/70' : 'text-muted-foreground'
            )}
          >
            {lead}
          </p>
        )}
      </div>
    </Reveal>
  )
}

/* ------------------------------------------------------------------ */
/* Card — base card with hover lift                                   */
/* ------------------------------------------------------------------ */
export function Card({
  children,
  className,
  tone = 'light',
}: {
  children: React.ReactNode
  className?: string
  tone?: 'light' | 'dark' | 'glass'
}) {
  const tones: Record<string, string> = {
    light: 'bg-card border border-[#dce2dd] dark:border-[#253630] text-foreground',
    dark: 'bg-white/[0.045] border border-white/15 text-white backdrop-blur-sm',
    glass: 'glass border border-white/20 text-foreground',
  }
  return (
    <article className={cn('card-hover rounded-[26px] p-7 sm:p-9', tones[tone], className)}>
      {children}
    </article>
  )
}

/* ------------------------------------------------------------------ */
/* StatBlock — large number + label                                   */
/* ------------------------------------------------------------------ */
export function StatBlock({
  value,
  label,
  suffix,
  tone = 'light',
}: {
  value: string
  label: string
  suffix?: string
  tone?: 'light' | 'dark'
}) {
  return (
    <div>
      <b
        className={cn(
          'block text-3xl font-semibold tracking-[-0.04em] sm:text-4xl',
          tone === 'dark' ? 'text-white' : 'text-foreground'
        )}
      >
        {value}
        {suffix && <span className="text-2xl">{suffix}</span>}
      </b>
      <span
        className={cn(
          'mt-2 block text-[10px] font-semibold uppercase tracking-[0.16em]',
          tone === 'dark' ? 'text-white/55' : 'text-muted-foreground'
        )}
      >
        {label}
      </span>
    </div>
  )
}

/* ------------------------------------------------------------------ */
/* Pill — small chip                                                  */
/* ------------------------------------------------------------------ */
export function Pill({
  children,
  className,
  tone = 'light',
}: {
  children: React.ReactNode
  className?: string
  tone?: 'light' | 'dark' | 'emerald'
}) {
  const tones: Record<string, string> = {
    light: 'bg-[#e8ece8] dark:bg-[#1c2926] text-[#4c5c57] dark:text-[#a5b3ae]',
    dark: 'bg-white/10 text-white border border-white/15',
    emerald: 'bg-[#0d5d50]/10 text-[#0d5d50] dark:text-[#8fb9ad]',
  }
  return (
    <span
      className={cn(
        'inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[11px] font-bold uppercase tracking-[0.12em]',
        tones[tone],
        className
      )}
    >
      {children}
    </span>
  )
}

/* ------------------------------------------------------------------ */
/* LinkButton — link styled as button                                 */
/* ------------------------------------------------------------------ */
export function LinkButton({
  children,
  onClick,
  href,
  variant = 'primary',
  className,
  ariaLabel,
}: {
  children: React.ReactNode
  onClick?: () => void
  href?: string
  variant?: 'primary' | 'outline' | 'ghost' | 'light'
  className?: string
  ariaLabel?: string
}) {
  const variants: Record<string, string> = {
    primary:
      'bg-[#0d5d50] text-white hover:bg-[#0b3b34] dark:bg-[#8fb9ad] dark:text-[#0c1311] dark:hover:bg-[#a8c8be]',
    outline: 'border border-current/30 bg-transparent hover:bg-white/10',
    ghost: 'bg-transparent hover:bg-white/10',
    light: 'bg-white text-[#123a33] hover:bg-[#dcebe6] dark:bg-white dark:text-[#0c1311]',
  }
  const base =
    'inline-flex items-center gap-2 rounded-full px-6 py-3.5 text-sm font-bold transition-all duration-300 cursor-pointer'

  if (href) {
    return (
      <a href={href} className={cn(base, variants[variant], className)} aria-label={ariaLabel}>
        {children}
      </a>
    )
  }
  return (
    <button
      type="button"
      onClick={onClick}
      className={cn(base, variants[variant], className)}
      aria-label={ariaLabel}
    >
      {children}
    </button>
  )
}

/* ------------------------------------------------------------------ */
/* Divider with label                                                 */
/* ------------------------------------------------------------------ */
export function LabeledDivider({
  label,
  tone = 'light',
}: {
  label: string
  tone?: 'light' | 'dark'
}) {
  return (
    <div
      className={cn(
        'flex items-center gap-4 border-t pt-6',
        tone === 'dark' ? 'border-white/15' : 'border-border'
      )}
    >
      <span
        className={cn(
          'text-[11px] font-bold uppercase tracking-[0.2em]',
          tone === 'dark' ? 'text-white/55' : 'text-muted-foreground'
        )}
      >
        {label}
      </span>
      <span className={cn('h-px flex-1', tone === 'dark' ? 'bg-white/10' : 'bg-border')} />
    </div>
  )
}

/* ------------------------------------------------------------------ */
/* Definition list row                                                */
/* ------------------------------------------------------------------ */
export function DefRow({
  term,
  children,
  tone = 'light',
}: {
  term: string
  children: React.ReactNode
  tone?: 'light' | 'dark'
}) {
  return (
    <div className="grid gap-3 border-b border-border py-5 last:border-0 sm:grid-cols-[220px_1fr] sm:gap-8">
      <dt
        className={cn(
          'text-xs font-bold uppercase tracking-[0.14em]',
          tone === 'dark' ? 'text-[#83aa9f]' : 'text-[#0d5d50] dark:text-[#8fb9ad]'
        )}
      >
        {term}
      </dt>
      <dd
        className={cn(
          'text-sm leading-6',
          tone === 'dark' ? 'text-white/75' : 'text-muted-foreground'
        )}
      >
        {children}
      </dd>
    </div>
  )
}

/* ------------------------------------------------------------------ */
/* NumberedStep — large ordinal + title + body                        */
/* ------------------------------------------------------------------ */
export function NumberedStep({
  n,
  title,
  children,
  tone = 'light',
}: {
  n: string
  title: string
  children: React.ReactNode
  tone?: 'light' | 'dark'
}) {
  return (
    <div
      className={cn(
        'border-l pl-6',
        tone === 'dark' ? 'border-[#4e776d]' : 'border-[#0d5d50]/40'
      )}
    >
      <b
        className={cn(
          'text-xl font-semibold tracking-[-0.02em] sm:text-2xl',
          tone === 'dark' ? 'text-white' : 'text-foreground'
        )}
      >
        {n}. {title}
      </b>
      <p
        className={cn(
          'mt-2 text-sm leading-6',
          tone === 'dark' ? 'text-white/60' : 'text-muted-foreground'
        )}
      >
        {children}
      </p>
    </div>
  )
}
