import React, { useEffect, useState } from "react";
import { Box, Button, Chip, Container, Stack, Typography } from "@mui/material";
import { keyframes } from "@emotion/react";
import { styled } from "@mui/system";
import heroImage from "../../assets/solo1.jpg";
import accentImage from "../../assets/bag2.jpg";
import secondHeroImage from "../../assets/solo2.jpg";
import thirdHeroImage from "../../assets/bag1.jpg";
import logo from "../../assets/logobgremove.png";

const colors = {
  mist: "#f8f1ea",
  blush: "#f4ddd4",
  peach: "#efb7a2",
  coral: "#d9826f",
  berry: "#7f4b5d",
  plum: "#4f2f42",
  gold: "#c99652",
  ivory: "#fffaf5",
};

const drift = keyframes`
  0% { transform: translate3d(0, 0, 0) scale(1); }
  50% { transform: translate3d(0, -18px, 0) scale(1.04); }
  100% { transform: translate3d(0, 0, 0) scale(1); }
`;

const rise = keyframes`
  from { opacity: 0; transform: translateY(28px); }
  to { opacity: 1; transform: translateY(0); }
`;

const scaleIn = keyframes`
  from { transform: scale(0.8); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
`;

const rotateIn = keyframes`
  from { transform: rotate(5deg) scale(0.9); opacity: 0; }
  to { transform: rotate(0deg) scale(1); opacity: 1; }
`;

const flipIn = keyframes`
  0% { transform: perspective(400px) rotateY(90deg); opacity: 0; }
  100% { transform: perspective(400px) rotateY(0deg); opacity: 1; }
`;

const fadeInImage = keyframes`
  from { opacity: 0; }
  to { opacity: 1; }
`;

const fadeOutImage = keyframes`
  from { opacity: 1; }
  to { opacity: 0; }
`;

const float = keyframes`
  0% { transform: translateY(0px); }
  50% { transform: translateY(-10px); }
  100% { transform: translateY(0px); }
`;

const glow = keyframes`
  0% { box-shadow: 0 0 0 0 rgba(201, 150, 82, 0.35); }
  70% { box-shadow: 0 0 0 18px rgba(201, 150, 82, 0); }
  100% { box-shadow: 0 0 0 0 rgba(201, 150, 82, 0); }
`;

const shimmer = keyframes`
  0% { transform: translateX(-120%); }
  100% { transform: translateX(120%); }
`;

const HeroShell = styled(Box)({
  position: "relative",
  overflow: "hidden",
  borderRadius: "36px",
  background: `linear-gradient(135deg, ${colors.ivory} 0%, ${colors.blush} 42%, ${colors.mist} 100%)`,
  border: `1px solid ${colors.peach}55`,
  boxShadow: "0 30px 70px rgba(79, 47, 66, 0.12)",
});

const GlassCard = styled(Box)({
  position: "relative",
  borderRadius: "28px",
  overflow: "hidden",
  background: "rgba(255, 250, 245, 0.72)",
  backdropFilter: "blur(14px)",
  border: "1px solid rgba(255, 255, 255, 0.55)",
  boxShadow: "0 24px 50px rgba(79, 47, 66, 0.12)",
});

const VintageImageFrame = styled(Box)({
  border: `12px solid ${colors.ivory}`,
  boxShadow: `8px 8px 0 ${colors.berry}45, 0 4px 8px rgba(0,0,0,0.1)`,
  position: "relative",
  overflow: "hidden",
  borderRadius: "28px",
  "&::before": {
    content: '""',
    position: "absolute",
    top: "-15px",
    left: "-15px",
    right: "-15px",
    bottom: "-15px",
    border: `1px solid ${colors.peach}88`,
    zIndex: -1,
    opacity: 0.7,
    borderRadius: "34px",
  },
});

const PrimaryButton = styled(Button)({
  borderRadius: "999px",
  padding: "14px 28px",
  textTransform: "none",
  fontSize: "1rem",
  fontWeight: 600,
  letterSpacing: "0.02em",
  background: `linear-gradient(135deg, ${colors.plum}, ${colors.berry})`,
  color: colors.ivory,
  boxShadow: "0 16px 34px rgba(79, 47, 66, 0.24)",
  animation: `${glow} 3.2s infinite`,
  "&:hover": {
    background: `linear-gradient(135deg, ${colors.berry}, ${colors.coral})`,
    transform: "translateY(-2px)",
  },
});

const SecondaryButton = styled(Button)({
  borderRadius: "999px",
  padding: "14px 28px",
  textTransform: "none",
  fontSize: "1rem",
  fontWeight: 600,
  color: colors.plum,
  border: `1px solid ${colors.peach}`,
  background: "rgba(255,255,255,0.45)",
  "&:hover": {
    background: "rgba(255,255,255,0.8)",
    borderColor: colors.gold,
  },
});

const RevealBox = styled(Box)({
  opacity: 0,
  animation: `${rise} 0.9s ease forwards`,
});

const FloatingOrb = styled(Box)<{
  delay?: string;
  size: number;
  top?: string;
  left?: string;
  right?: string;
  bottom?: string;
}>(({ delay = "0s", size, top, left, right, bottom }) => ({
  position: "absolute",
  width: size,
  height: size,
  top,
  left,
  right,
  bottom,
  borderRadius: "50%",
  background:
    "radial-gradient(circle at 30% 30%, rgba(255,255,255,0.8), rgba(217,130,111,0.18) 55%, rgba(127,75,93,0.12) 100%)",
  filter: "blur(2px)",
  animation: `${drift} 8s ease-in-out infinite`,
  animationDelay: delay,
}));

const StoryHeader: React.FC = () => {
  const heroImages = [heroImage, secondHeroImage, thirdHeroImage, accentImage];
  const heroAnimations = [scaleIn, rotateIn, flipIn];
  const [currentHeroImage, setCurrentHeroImage] = useState(0);
  const [previousHeroImage, setPreviousHeroImage] = useState<number | null>(null);

  useEffect(() => {
    const interval = setInterval(() => {
      setCurrentHeroImage((prev) => {
        setPreviousHeroImage(prev);
        return (prev + 1) % heroImages.length;
      });
    }, 8000);

    return () => clearInterval(interval);
  }, [heroImages.length]);

  useEffect(() => {
    if (previousHeroImage === null) {
      return;
    }

    const timeout = setTimeout(() => {
      setPreviousHeroImage(null);
    }, 2000);

    return () => clearTimeout(timeout);
  }, [previousHeroImage]);

  return (
    <Container
      maxWidth="xl"
      sx={{ position: "relative", zIndex: 1, pt: { xs: 3, md: 4 }, pb: { xs: 4, md: 6 } }}
    >
      <HeroShell>
        <FloatingOrb size={180} top="-40px" right="-30px" />
        <FloatingOrb size={130} bottom="18%" left="-45px" delay="1.2s" />
        <FloatingOrb size={96} top="20%" right="42%" delay="2.1s" />

        <Box
          sx={{
            position: "absolute",
            inset: 0,
            background:
              "linear-gradient(120deg, rgba(255,255,255,0) 20%, rgba(255,255,255,0.38) 50%, rgba(255,255,255,0) 80%)",
            opacity: 0.6,
            animation: `${shimmer} 5.8s linear infinite`,
          }}
        />

        <Box
          sx={{
            position: "relative",
            zIndex: 1,
            px: { xs: 2.5, sm: 4, md: 6 },
            py: { xs: 4, md: 5 },
          }}
        >
          <RevealBox sx={{ animationDelay: "0.05s" }}>
            <Stack
              direction={{ xs: "column", sm: "row" }}
              alignItems={{ xs: "flex-start", sm: "center" }}
              justifyContent="space-between"
              spacing={2}
              sx={{ mb: { xs: 4, md: 5 } }}
            >
              <Stack direction="row" alignItems="center" spacing={1.5}>
                <Box
                  component="img"
                  src={logo}
                  alt="The Kalawati"
                  sx={{
                    width: 54,
                    height: 54,
                    objectFit: "contain",
                    filter: "drop-shadow(0 8px 16px rgba(79,47,66,0.16))",
                  }}
                />
                <Box sx={{ textAlign: "left" }}>
                  <Typography
                    sx={{
                      fontFamily: '"Playfair Display", serif',
                      fontSize: "1.15rem",
                      color: colors.plum,
                      letterSpacing: "0.08em",
                    }}
                  >
                    THE KALAWATI
                  </Typography>
                  <Typography
                    sx={{
                      color: colors.berry,
                      fontSize: "0.86rem",
                      letterSpacing: "0.14em",
                      textTransform: "uppercase",
                    }}
                  >
                    Artisanal Storytelling Goods
                  </Typography>
                </Box>
              </Stack>

              <Stack direction="row" spacing={1} flexWrap="wrap" useFlexGap>
                {["Hand-dyed", "Slow-made", "Soulful color"].map((item) => (
                  <Chip
                    key={item}
                    label={item}
                    sx={{
                      borderRadius: "999px",
                      background: "rgba(255,255,255,0.55)",
                      color: colors.plum,
                      border: `1px solid ${colors.peach}88`,
                      fontWeight: 500,
                    }}
                  />
                ))}
              </Stack>
            </Stack>
          </RevealBox>

          <Box
            sx={{
              display: "grid",
              gridTemplateColumns: { xs: "1fr", lg: "1.05fr 0.95fr" },
              alignItems: "center",
              gap: { xs: 4, md: 5 },
            }}
          >
            <RevealBox sx={{ animationDelay: "0.18s" }}>
              <Typography
                sx={{
                  mb: 2,
                  color: colors.coral,
                  fontSize: "0.95rem",
                  letterSpacing: "0.22em",
                  textTransform: "uppercase",
                }}
              >
                A poetic storefront for crafted living
              </Typography>
              <Typography
                sx={{
                  fontFamily: '"Playfair Display", serif',
                  color: colors.plum,
                  fontSize: { xs: "2.8rem", sm: "3.4rem", md: "4.9rem" },
                  lineHeight: { xs: 1.05, md: 0.98 },
                  letterSpacing: "-0.03em",
                  maxWidth: "10ch",
                }}
              >
                Stories woven into every beautiful piece.
              </Typography>
              <Typography
                sx={{
                  mt: 2.5,
                  maxWidth: "56ch",
                  color: colors.berry,
                  fontSize: { xs: "1rem", md: "1.08rem" },
                  lineHeight: 1.8,
                }}
              >
                Build desire through color, texture, and memory. This header is designed to feel cinematic,
                feminine, and premium for a story-led product brand.
              </Typography>

              <Stack direction={{ xs: "column", sm: "row" }} spacing={2} sx={{ mt: 4 }}>
                <PrimaryButton href="#collection">Explore the Collection</PrimaryButton>
                <SecondaryButton href="#story">Read Our Story</SecondaryButton>
              </Stack>

              <Stack direction={{ xs: "column", sm: "row" }} spacing={{ xs: 2, md: 3 }} sx={{ mt: 4.5 }}>
                {[
                  { value: "24+", label: "curated handcrafted drops" },
                  { value: "8", label: "signature color stories" },
                  { value: "100%", label: "visual-first storytelling" },
                ].map((item) => (
                  <Box key={item.label}>
                    <Typography
                      sx={{ fontFamily: '"Playfair Display", serif', color: colors.plum, fontSize: "1.8rem" }}
                    >
                      {item.value}
                    </Typography>
                    <Typography sx={{ color: colors.berry, fontSize: "0.92rem" }}>{item.label}</Typography>
                  </Box>
                ))}
              </Stack>
            </RevealBox>

            <RevealBox sx={{ animationDelay: "0.32s" }}>
              <Box sx={{ position: "relative", minHeight: { xs: 440, md: 560 } }}>
                <GlassCard
                  sx={{
                    position: "absolute",
                    inset: { xs: "72px 0 0 0", md: "90px 16px 0 24px" },
                    transform: { md: "rotate(-4deg)" },
                    background: "transparent",
                    backdropFilter: "none",
                    border: "none",
                    boxShadow: "none",
                    overflow: "visible",
                  }}
                >
                  {previousHeroImage !== null && (
                    <VintageImageFrame
                      sx={{
                        position: "absolute",
                        inset: 0,
                        width: "100%",
                        height: "100%",
                        minHeight: { xs: 320, md: 420 },
                        backgroundImage: `url(${heroImages[previousHeroImage]})`,
                        backgroundSize: "cover",
                        backgroundPosition: "center",
                        filter: "sepia(0.2) contrast(1.05)",
                        animation: `${fadeOutImage} 2s ease-in-out forwards`,
                      }}
                    >
                      <Box
                        sx={{
                          position: "absolute",
                          inset: 0,
                          background: "linear-gradient(to top, rgba(79,47,66,0.42), transparent 45%)",
                        }}
                      />
                    </VintageImageFrame>
                  )}

                  <VintageImageFrame
                    key={heroImages[currentHeroImage]}
                    sx={{
                      position: "relative",
                      zIndex: 1,
                      width: "100%",
                      height: "100%",
                      minHeight: { xs: 320, md: 420 },
                      backgroundImage: `url(${heroImages[currentHeroImage]})`,
                      backgroundSize: "cover",
                      backgroundPosition: "center",
                      filter: "sepia(0.2) contrast(1.05)",
                      animation: `${heroAnimations[currentHeroImage % heroAnimations.length]} 1.5s ease, ${fadeInImage} 2s ease-in-out, ${float} 6s ease-in-out infinite`,
                    }}
                  >
                    <Box
                      sx={{
                        position: "absolute",
                        inset: 0,
                        background: "linear-gradient(to top, rgba(79,47,66,0.42), transparent 45%)",
                      }}
                    />
                  </VintageImageFrame>
                </GlassCard>

                <GlassCard
                  sx={{
                    position: "absolute",
                    top: 0,
                    right: { xs: 12, md: 0 },
                    width: { xs: "54%", md: "46%" },
                    p: 1.2,
                    transform: { xs: "rotate(4deg)", md: "rotate(6deg)" },
                  }}
                >
                  {/* <Box
                    component="img"
                    src={accentImage}
                    alt="Aesthetic accessory detail"
                    sx={{ width: "100%", height: { xs: 168, md: 220 }, objectFit: "cover", borderRadius: "22px" }}
                  /> */}
                </GlassCard>

                <GlassCard
                  sx={{
                    position: "absolute",
                    left: { xs: 12, md: -12 },
                    bottom: { xs: 10, md: 26 },
                    width: { xs: "76%", md: "54%" },
                    p: 2.4,
                  }}
                >
                  <Typography
                    sx={{
                      color: colors.coral,
                      textTransform: "uppercase",
                      letterSpacing: "0.16em",
                      fontSize: "0.82rem",
                      mb: 1,
                    }}
                  >
                    Featured chapter
                  </Typography>
                  <Typography
                    sx={{
                      fontFamily: '"Playfair Display", serif',
                      color: colors.plum,
                      fontSize: { xs: "1.35rem", md: "1.55rem" },
                      mb: 1,
                    }}
                  >
                    Dusty rose, gold accents, soft heirloom drama
                  </Typography>
                  <Typography sx={{ color: colors.berry, lineHeight: 1.7, fontSize: "0.95rem" }}>
                    Layered cards and floating light create the feeling of a living editorial spread instead of a
                    standard ecommerce banner.
                  </Typography>
                </GlassCard>
              </Box>
            </RevealBox>
          </Box>
        </Box>
      </HeroShell>
    </Container>
  );
};

export default StoryHeader;
