"use client";

import React from "react";
import {
  ThreeUIDefenseLines,
  ThreeUITopoField,
  ThreeUIMatrixField,
  ThreeUIGatewayFlow,
  ThreeUIRibbonField,
  ThreeUIHalftoneRelay,
} from "@/components/threeui/dynamic-effects";
import { LazyEffect } from "@/components/threeui/lazy-effect";

export type SectionBackgroundVariant =
  | "none"
  | "defense"
  | "topo"
  | "matrix"
  | "gateway"
  | "ribbon"
  | "halftone";

export type SectionIntensity = "subtle" | "medium" | "low";

interface SectionBackgroundProps {
  variant?: SectionBackgroundVariant;
  intensity?: SectionIntensity;
  className?: string;
}

const EFFECTS: Record<Exclude<SectionBackgroundVariant, "none">, React.ComponentType> = {
  defense: ThreeUIDefenseLines,
  topo: ThreeUITopoField,
  matrix: ThreeUIMatrixField,
  gateway: ThreeUIGatewayFlow,
  ribbon: ThreeUIRibbonField,
  halftone: ThreeUIHalftoneRelay,
};

/**
 * ThreeUI section background. The heavy WebGL effect is mounted only while the
 * section is on (or near) screen and the tab is visible — see LazyEffect — so a
 * long page never runs several render loops at once (§20–25). Reduced-motion and
 * small phones get a cheap static monochrome wash instead (§44, §46).
 */
export function SectionBackground({
  variant = "none",
  intensity = "subtle",
  className = "",
}: SectionBackgroundProps) {
  if (!variant || variant === "none") return null;

  const opacityMap: Record<SectionIntensity, string> = {
    low: "opacity-20",
    subtle: "opacity-35",
    medium: "opacity-50",
  };
  const selectedOpacity = opacityMap[intensity] || "opacity-35";
  const Effect = EFFECTS[variant];

  // Static, animation-free depth wash for gated-off states (monochrome).
  const staticFallback = (
    <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_50%_0%,rgba(255,255,255,0.06),transparent_60%)]" />
  );

  return (
    <div
      aria-hidden="true"
      className={`pointer-events-none absolute inset-0 z-0 overflow-hidden select-none ${selectedOpacity} ${className}`}
    >
      <LazyEffect className="absolute inset-0 size-full" fallback={staticFallback}>
        <Effect />
      </LazyEffect>
    </div>
  );
}
