"use client";

import Link from "next/link";
import Image from "next/image";
import { useCtas } from "@/hooks/useData";
import { motion, useScroll, useTransform } from "motion/react";
import { useRef } from "react";

const CtaView = ({ cta, order, parallax }) => {
  const containerRef = useRef(null);

  // Parallax scroll animation
  const { scrollYProgress } = useScroll({
    target: containerRef,
    offset: ["start end", "end start"],
  });

  const y = useTransform(scrollYProgress, [0, 1], [100, -100]);
  const opacity = useTransform(scrollYProgress, [0, 0.3, 0.7, 1], [0, 1, 1, 0]);

  const {
    title,
    image,
    description,
    button_link,
    alignment = 0,
    visibility = {},
  } = cta;

  // Use DB value if exists, otherwise fallback to prop (or default false)
  const isParallax = visibility?.is_parallax === 1;

  // Alignment logic
  const isLeft = +alignment === 1;
  const isRight = +alignment === 2;
  const isCenter = !isLeft && !isRight;

  const justifyContent = isLeft
    ? "justify-start"
    : isRight
      ? "justify-end"
      : "justify-center";

  const textAlign = isLeft
    ? "text-left items-start"
    : isRight
      ? "text-right items-end"
      : "text-center items-center";

  const img = cta?.image?.replace("/api", "");

  // Content Component with enhanced luxury design and improved mobile responsiveness
  const Content = () => (
    <div
      className={`relative z-10 container mx-auto px-4 sm:px-6 lg:px-12 xl:px-20 flex ${justifyContent} items-center h-full py-12 sm:py-20 md:py-28 lg:py-36 xl:py-44`}
    >
      <motion.div
        initial={{ opacity: 0, y: 40 }}
        whileInView={{ opacity: 1, y: 0 }}
        viewport={{ once: true, margin: "-100px" }}
        transition={{
          duration: 0.8,
          ease: [0.22, 1, 0.36, 1], // Custom easing for elegance
        }}
        className={`max-w-2xl flex flex-col gap-4 sm:gap-6 lg:gap-8 ${textAlign}`}
      >
        {/* Decorative Line Accent */}
        <motion.div
          initial={{ scaleX: 0 }}
          whileInView={{ scaleX: 1 }}
          viewport={{ once: true }}
          transition={{ duration: 1, delay: 0.3, ease: "easeInOut" }}
          className={`h-[1px] w-16 sm:w-20 lg:w-24 bg-gradient-to-r from-brand-gold/0 via-brand-gold to-brand-gold/0 ${
            isLeft ? "origin-left" : isRight ? "origin-right" : "origin-center"
          }`}
        />

        <div className="flex flex-col gap-3 sm:gap-4 lg:gap-6">
          {visibility?.show_content === 1 && (
            <>
              {/* Small Overline Label */}
              <motion.span
                initial={{ opacity: 0 }}
                whileInView={{ opacity: 1 }}
                viewport={{ once: true }}
                transition={{ delay: 0.2, duration: 0.6 }}
                className="uppercase tracking-[0.2em] sm:tracking-[0.25em] text-[10px] sm:text-[11px] font-semibold text-brand-gold/90 font-lato"
              >
                Timeless Elegance
              </motion.span>

              <h2 className="font-cormorant text-3xl xs:text-4xl sm:text-5xl md:text-6xl lg:text-7xl xl:text-8xl font-light text-white leading-[1.1] tracking-tight">
                <motion.span
                  initial={{ opacity: 0, y: 20 }}
                  whileInView={{ opacity: 1, y: 0 }}
                  viewport={{ once: true }}
                  transition={{ delay: 0.3, duration: 0.7 }}
                  className="inline-block"
                  dangerouslySetInnerHTML={{ __html: title }}
                />

                {/* Decorative Flourish */}
                <motion.svg
                  initial={{ opacity: 0, pathLength: 0 }}
                  whileInView={{ opacity: 1, pathLength: 1 }}
                  viewport={{ once: true }}
                  transition={{ delay: 0.8, duration: 1.2, ease: "easeInOut" }}
                  className={`mt-2 sm:mt-3 lg:mt-4 w-24 sm:w-32 lg:w-40 ${isCenter ? "mx-auto" : ""}`}
                  viewBox="0 0 160 8"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <motion.path
                    d="M0 4C40 4 40 1 80 1C120 1 120 4 160 4"
                    stroke="#ddbc5f"
                    strokeWidth="0.5"
                    strokeLinecap="round"
                  />
                  <motion.circle cx="80" cy="1.5" r="1.5" fill="#ddbc5f" />
                </motion.svg>
              </h2>
            </>
          )}

          {visibility?.show_description === 1 && description && (
            <motion.p
              initial={{ opacity: 0 }}
              whileInView={{ opacity: 1 }}
              viewport={{ once: true }}
              transition={{ delay: 0.5, duration: 0.8 }}
              className="text-white/85 font-lato text-sm sm:text-base lg:text-lg xl:text-xl font-light leading-relaxed max-w-lg tracking-wide"
              style={{ textShadow: "0 2px 8px rgba(0,0,0,0.3)" }}
            >
              {description}
            </motion.p>
          )}
        </div>

        {visibility?.show_button === 1 && button_link && (
          <motion.div
            // initial={{ opacity: 0, y: 20 }}
            // whileInView={{ opacity: 1, y: 0 }}
            // transition={{ delay: 0.7, duration: 0.8 }}
            className="pt-2 sm:pt-3 lg:pt-4"
          >
            <Link
              href={`/${button_link}`}
              className="group relative inline-flex items-center gap-3 overflow-hidden"
            >
              {/* Animated background */}
              <span className="absolute inset-0 bg-brand-gold/10 backdrop-blur-sm border border-brand-gold/30 -z-10 group-hover:bg-brand-gold/20 transition-all duration-500" />

              {/* Button content */}
              <span className="relative flex items-center gap-2 sm:gap-3 px-5 py-3 sm:px-6 sm:py-3.5 lg:px-8 lg:py-4">
                <span className="font-lato text-xs sm:text-sm uppercase tracking-[0.15em] sm:tracking-[0.2em] font-semibold text-white group-hover:text-brand-gold transition-colors duration-300">
                  Discover Collection
                </span>

                {/* Arrow with animation */}
                <motion.svg
                  className="w-4 h-4 sm:w-5 sm:h-5 text-brand-gold"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  initial={{ x: 0 }}
                  whileHover={{ x: 5 }}
                  transition={{ duration: 0.3 }}
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={1.5}
                    d="M17 8l4 4m0 0l-4 4m4-4H3"
                  />
                </motion.svg>
              </span>

              {/* Shine effect on hover */}
              <span className="absolute inset-0 -z-10 opacity-0 group-hover:opacity-100 transition-opacity duration-700">
                <span className="absolute inset-0 bg-gradient-to-r from-transparent via-white/10 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-1000" />
              </span>
            </Link>
          </motion.div>
        )}
      </motion.div>
    </div>
  );

  if (isParallax) {
    return (
      <section
        ref={containerRef}
        className="relative w-full h-[300px] sm:h-[350px] md:h-[400px] lg:h-[600px] overflow-hidden"
      >
        {/* Parallax Background - Fixed Attachment */}
        <div
          className="absolute inset-0 w-full h-full"
          style={{
            backgroundImage: `url(${img})`,
            backgroundAttachment: "fixed",
            backgroundPosition: "center",
            backgroundSize: "cover",
            backgroundRepeat: "no-repeat",
          }}
        />

        {visibility?.show_content === 1 && (
          <>
           
            <div className="absolute inset-0 bg-gradient-to-b from-primary/40 to-primary/60 z-0" />
            {/* <div className="absolute inset-0 bg-gradient-to-r from-primary/30  to-primary/30 z-0" /> */}

            
            <div
              className="absolute inset-0 z-0 opacity-20 mix-blend-overlay"
              style={{
                backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.05'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
              }}
            />
          </>
        )}

        {/* Content */}
        <motion.div style={{ opacity }} className="relative z-10 h-full">
          {visibility?.show_content === 1 && <Content />}
        </motion.div>

        {/* Decorative corner accents - smaller on mobile */}
        {visibility?.show_content === 1 && (
          <>
            <div className="absolute top-0 left-0 w-20 h-20 sm:w-24 sm:h-24 lg:w-32 lg:h-32 border-l border-t border-brand-gold/20 z-20" />
            <div className="absolute bottom-0 right-0 w-20 h-20 sm:w-24 sm:h-24 lg:w-32 lg:h-32 border-r border-b border-brand-gold/20 z-20" />
          </>
        )}
      </section>
    );
  }

  // Normal Mode - Enhanced with better mobile responsiveness
  return (
    <section ref={containerRef} className="relative w-full overflow-hidden">
      <div className="relative w-full h-[300px] sm:h-[350px] md:h-[400px] lg:h-[600px]">
        {/* Image with Ken Burns effect on scroll */}
        <motion.div
          // style={{ scale: useTransform(scrollYProgress, [0, 0.5], [1.1, 1]) }}
          className="absolute inset-0"
        >
          <Image
            src={img}
            alt={cta?.title || "Luxury Jewelry Collection"}
            fill
            priority={order === "top"}
            className="object-cover w-full h-full"
            sizes="100vw"
            quality={95}
          />
        </motion.div>

        {visibility?.show_content === 1 && (
          <>
            <div className="absolute inset-0 bg-gradient-to-b from-primary/50 via-primary/20 to-primary/70 z-0" />
            <div className="absolute inset-0 bg-gradient-to-r from-primary/40 via-transparent to-primary/40 z-0" />

            <div
              className="absolute inset-0 z-0 opacity-[0.15] mix-blend-soft-light"
              style={{
                backgroundImage: `url("data:image/svg+xml,%3Csvg viewBox='0 0 400 400' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='2.5' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)'/%3E%3C/svg%3E")`,
              }}
            />
          </>
        )}

        {/* Content */}
        {visibility?.show_content === 1 && (
          <div className="absolute inset-0 z-20">
            <Content />
          </div>
        )}

        {/* Elegant corner frames - responsive sizing */}
        {visibility?.show_content === 1 && (
          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            whileInView={{ opacity: 1, scale: 1 }}
            viewport={{ once: true }}
            transition={{ delay: 1, duration: 0.8 }}
            className="absolute inset-0 z-30 pointer-events-none"
          >
            {/* Top left corner */}
            <div className="absolute top-4 left-4 sm:top-6 sm:left-6 lg:top-8 lg:left-8 xl:top-12 xl:left-12">
              <svg
                width="40"
                height="40"
                viewBox="0 0 60 60"
                fill="none"
                className="sm:w-[50px] sm:h-[50px] lg:w-[60px] lg:h-[60px]"
              >
                <path d="M0 0V60M0 0H60" stroke="#ddbc5f" strokeWidth="0.5" />
                <circle cx="0" cy="0" r="2" fill="#ddbc5f" />
              </svg>
            </div>

            {/* Top right corner */}
            <div className="absolute top-4 right-4 sm:top-6 sm:right-6 lg:top-8 lg:right-8 xl:top-12 xl:right-12">
              <svg
                width="40"
                height="40"
                viewBox="0 0 60 60"
                fill="none"
                className="sm:w-[50px] sm:h-[50px] lg:w-[60px] lg:h-[60px]"
              >
                <path d="M60 0V60M60 0H0" stroke="#ddbc5f" strokeWidth="0.5" />
                <circle cx="60" cy="0" r="2" fill="#ddbc5f" />
              </svg>
            </div>

            {/* Bottom left corner */}
            <div className="absolute bottom-4 left-4 sm:bottom-6 sm:left-6 lg:bottom-8 lg:left-8 xl:bottom-12 xl:left-12">
              <svg
                width="40"
                height="40"
                viewBox="0 0 60 60"
                fill="none"
                className="sm:w-[50px] sm:h-[50px] lg:w-[60px] lg:h-[60px]"
              >
                <path d="M0 60V0M0 60H60" stroke="#ddbc5f" strokeWidth="0.5" />
                <circle cx="0" cy="60" r="2" fill="#ddbc5f" />
              </svg>
            </div>

            {/* Bottom right corner */}
            <div className="absolute bottom-4 right-4 sm:bottom-6 sm:right-6 lg:bottom-8 lg:right-8 xl:bottom-12 xl:right-12">
              <svg
                width="40"
                height="40"
                viewBox="0 0 60 60"
                fill="none"
                className="sm:w-[50px] sm:h-[50px] lg:w-[60px] lg:h-[60px]"
              >
                <path d="M60 60V0M60 60H0" stroke="#ddbc5f" strokeWidth="0.5" />
                <circle cx="60" cy="60" r="2" fill="#ddbc5f" />
              </svg>
            </div>
          </motion.div>
        )}
      </div>
    </section>
  );
};

const Cta = ({ order, parallax = false }) => {
  const { data } = useCtas();

  // Determine which CTA to show based on order
  const value = order === "top" ? 0 : 1;
  const cta = data?.rows?.[value];

  if (!cta) return null;

  return <CtaView cta={cta} order={order} parallax={parallax} />;
};

export default Cta;
