"use client";

import { MeshGradient } from "@paper-design/shaders-react";
import type React from "react";
import { useEffect, useRef, useState } from "react";
import { createRenderGate } from "@/app/lib/render-gate";

interface HeroShaderBackgroundProps {
  children: React.ReactNode;
  imageSrc: string;
}

export function HeroShaderBackground({ children, imageSrc }: HeroShaderBackgroundProps) {
  const rootRef = useRef<HTMLDivElement>(null);
  const [shaderActive, setShaderActive] = useState(false);

  useEffect(() => {
    const el = rootRef.current;
    if (!el) return;
    return createRenderGate(el, setShaderActive);
  }, []);

  return (
    <div
      ref={rootRef}
      className="relative isolate overflow-hidden border-b border-[var(--surface-border)]"
    >
      <div
        aria-hidden
        className="absolute inset-0 bg-cover bg-center opacity-[0.58] saturate-[1.12] contrast-[1.04]"
        style={{ backgroundImage: `url("${imageSrc}")` }}
      />
      <div aria-hidden className="absolute inset-0 bg-[rgb(243_247_240_/_0.12)]" />

      {/* Một lớp shader duy nhất, chỉ vẽ khi hero trong tầm nhìn + tab hiển thị */}
      {shaderActive ? (
        <div aria-hidden className="absolute inset-0 overflow-hidden opacity-40">
          <MeshGradient
            className="absolute inset-0 h-full w-full"
            colors={["#f8fbf2", "#d6b468", "#e0eddf", "#245f4b", "#ffffff"]}
            speed={0.24}
          />
        </div>
      ) : null}

      <div
        aria-hidden
        className="absolute inset-0 bg-[linear-gradient(90deg,rgb(243_247_240_/_0.93)_0%,rgb(243_247_240_/_0.72)_42%,rgb(243_247_240_/_0.14)_100%)]"
      />
      <div
        aria-hidden
        className="absolute inset-x-0 bottom-0 h-44 bg-[linear-gradient(180deg,transparent,rgb(243_247_240_/_0.98))]"
      />

      {children}
    </div>
  );
}
