import { Link, useLocation } from "wouter";
import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import AppBar from "@mui/material/AppBar";
import Toolbar from "@mui/material/Toolbar";
import Box from "@mui/material/Box";
import Container from "@mui/material/Container";
import IconButton from "@mui/material/IconButton";
import { Menu, X, Instagram, Facebook, Twitter, ChevronDown, Flame, Sparkles, Star } from "lucide-react";
import { ScrollCandle } from "./ScrollCandle";
import "./Layout.css";

const logoPath = "/opengraph.jpg";

// ── Ticker messages ──────────────────────────────────────
const TICKER_ITEMS = [
  { icon: <Flame size={12} />, text: "Free shipping on orders over $50" },
  { icon: <Sparkles size={12} />, text: "New Collection — Summer Solstice" },
  { icon: <Star size={12} />, text: "Handpoured in small batches" },
  { icon: <Flame size={12} />, text: "100% Natural Soy Wax" },
  { icon: <Sparkles size={12} />, text: "Phthalate-free fragrance oils" },
  { icon: <Star size={12} />, text: "Gift wrapping available at checkout" },
];

// ── Nav structure with dropdowns ─────────────────────────
const NAV_LINKS = [
  { name: "Home", path: "/", dropdown: null },
  {
    name: "Products",
    path: "/products",
    dropdown: [
      { label: "All Collections", path: "/products" },
      null, // divider
      { label: "Floral Scents", path: "/products" },
      { label: "Fresh Scents", path: "/products" },
      { label: "Woody Scents", path: "/products" },
      { label: "Sweet Scents", path: "/products" },
    ],
  },
  {
    name: "About",
    path: "/about",
    dropdown: [
      { label: "Our Story", path: "/about" },
      { label: "Our Process", path: "/about" },
      { label: "Meet the Maker", path: "/about" },
    ],
  },
  {
    name: "Contact",
    path: "/contact",
    dropdown: [
      { label: "Send a Message", path: "/contact" },
      { label: "Wholesale Inquiries", path: "/contact" },
      null,
      { label: "Follow on Instagram", path: "/contact" },
    ],
  },
];

export function Layout({ children }: { children: React.ReactNode }) {
  const [location] = useLocation();
  const [scrolled, setScrolled] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [mobileOpenSection, setMobileOpenSection] = useState<string | null>(null);

  useEffect(() => {
    const handleScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  useEffect(() => {
    window.scrollTo(0, 0);
    setMobileMenuOpen(false);
    setMobileOpenSection(null);
  }, [location]);

  // Duplicate ticker items to create seamless loop
  const allTickerItems = [...TICKER_ITEMS, ...TICKER_ITEMS];

  return (
    <Box sx={{ minHeight: "100vh", display: "flex", flexDirection: "column" }}>

      {/* ── Ticker Bar ── */}
      <Box
        className="ticker-bar"
        sx={{ position: "fixed", top: 0, left: 0, right: 0, zIndex: 1200 }}
      >
        <div className="ticker-track">
          {allTickerItems.map((item, i) => (
            <span className="ticker-item" key={i}>
              <span className="ticker-dot" />
              {item.icon}
              {item.text}
            </span>
          ))}
        </div>
      </Box>

      {/* ── Main AppBar ── */}
      <AppBar
        position="fixed"
        sx={{
          top: 36, // sits below the ticker bar
          background: scrolled
            ? "rgba(91,30,140,0.78)"
            : "rgba(91,30,140,0.58)",
          backdropFilter: "blur(22px) saturate(1.6)",
          WebkitBackdropFilter: "blur(22px) saturate(1.6)",
          boxShadow: scrolled ? "0 1px 0 0 rgba(212,162,76,0.5), 0 4px 24px rgba(58,18,96,0.35)" : "none",
          transition: "background 0.5s ease, box-shadow 0.5s ease",
          overflow: "visible",
        }}
      >
        <Container maxWidth="xl">
          <Toolbar
            disableGutters
            sx={{ height: 76, justifyContent: "space-between", overflow: "visible" }}
          >
            {/* Logo */}
            <Link
              href="/"
              style={{ display: "flex", alignItems: "center", gap: "0.9rem", textDecoration: "none" }}
            >
              <div className="logo-img-wrap">
                <img
                  src={logoPath}
                  alt="Mani Candles Co. Logo"
                  style={{ width: "100%", height: "100%", objectFit: "cover" }}
                />
              </div>
              <span className="logo-text">Mani Candles</span>
            </Link>

            {/* Desktop Nav */}
            <Box
              component="nav"
              sx={{
                display: { xs: "none", md: "flex" },
                gap: 4,
                alignItems: "center",
                overflow: "visible",
                position: "relative",
              }}
            >
              {NAV_LINKS.map((link) => (
                <div className="nav-item" key={link.path + link.name}>
                  <Link
                    href={link.path}
                    className={`nav-link${location === link.path ? " active" : ""}`}
                  >
                    {link.name}
                    {link.dropdown && <ChevronDown size={13} className="nav-chevron" />}
                  </Link>

                  {/* Dropdown */}
                  {link.dropdown && (
                    <div className="nav-dropdown">
                      {link.dropdown.map((item, idx) =>
                        item === null ? (
                          <div key={`div-${idx}`} className="dropdown-divider" />
                        ) : (
                          <Link key={item.label} href={item.path} className="dropdown-item">
                            {item.label}
                          </Link>
                        )
                      )}
                    </div>
                  )}
                </div>
              ))}
            </Box>

            {/* Mobile Toggle */}
            <IconButton
              sx={{ display: { md: "none" }, color: "#ffffff" }}
              onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
            >
              {mobileMenuOpen ? <X size={26} /> : <Menu size={26} />}
            </IconButton>
          </Toolbar>
        </Container>

        {/* Mobile Drawer */}
        <AnimatePresence>
          {mobileMenuOpen && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: "auto" }}
              exit={{ opacity: 0, height: 0 }}
              className="mobile-menu"
            >
              {NAV_LINKS.map((link) => (
                <div className="mobile-nav-section" key={link.name}>
                  {link.dropdown ? (
                    <>
                      <button
                        className={`mobile-nav-link${location === link.path ? " active" : ""}`}
                        style={{ background: "none", border: "none", textAlign: "left", cursor: "pointer", width: "100%", display: "flex", justifyContent: "space-between", alignItems: "center" }}
                        onClick={() => setMobileOpenSection(mobileOpenSection === link.name ? null : link.name)}
                      >
                        {link.name}
                        <ChevronDown
                          size={14}
                          style={{
                            transition: "transform 0.25s ease",
                            transform: mobileOpenSection === link.name ? "rotate(180deg)" : "rotate(0deg)",
                            opacity: 0.7,
                          }}
                        />
                      </button>
                      <AnimatePresence>
                        {mobileOpenSection === link.name && (
                          <motion.div
                            initial={{ opacity: 0, height: 0 }}
                            animate={{ opacity: 1, height: "auto" }}
                            exit={{ opacity: 0, height: 0 }}
                            className="mobile-dropdown-items"
                          >
                            {link.dropdown.map((item, i) =>
                              item === null ? (
                                <div key={i} style={{ height: 1, background: "rgba(255,255,255,0.07)", margin: "0.2rem 0" }} />
                              ) : (
                                <Link key={item.label} href={item.path} className="mobile-dropdown-item">
                                  {item.label}
                                </Link>
                              )
                            )}
                          </motion.div>
                        )}
                      </AnimatePresence>
                    </>
                  ) : (
                    <Link
                      href={link.path}
                      className={`mobile-nav-link${location === link.path ? " active" : ""}`}
                    >
                      {link.name}
                    </Link>
                  )}
                </div>
              ))}
            </motion.div>
          )}
        </AnimatePresence>
      </AppBar>

      {/* ── Page Content — offset for ticker + appbar ── */}
      <Box component="main" sx={{ flexGrow: 1, pt: "112px" }}>
        <AnimatePresence mode="wait">
          <motion.div
            key={location}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            transition={{ duration: 0.5, ease: "easeOut" }}
          >
            {children}
          </motion.div>
        </AnimatePresence>
      </Box>

      {/* ── Scroll Candle ── */}
      <ScrollCandle />

      {/* ── Footer ── */}
      <footer className="site-footer">
        <div className="footer-inner">
          <div className="footer-col">
            <div style={{ display: "flex", alignItems: "center", gap: "1rem" }}>
              <div style={{ width: 56, height: 56, borderRadius: "50%", overflow: "hidden", background: "#fff", padding: 3 }}>
                <img
                  src={logoPath}
                  alt="Mani Candles Co."
                  style={{ width: "100%", height: "100%", objectFit: "cover", borderRadius: "50%" }}
                />
              </div>
              <span className="font-script" style={{ fontSize: "2rem", color: "var(--brand-gold-light)" }}>
                Mani Candles
              </span>
            </div>
            <p className="footer-tagline">Handmade • Natural • Heartmade</p>
          </div>

          <div className="footer-col">
            <h4 className="footer-heading">Explore</h4>
            {NAV_LINKS.map((link) => (
              <Link key={link.path + link.name} href={link.path} className="footer-link">
                {link.name}
              </Link>
            ))}
          </div>

          <div className="footer-col">
            <h4 className="footer-heading">Connect</h4>
            <div style={{ display: "flex", gap: "0.75rem" }}>
              <a href="#" className="social-btn"><Instagram size={18} /></a>
              <a href="#" className="social-btn"><Facebook size={18} /></a>
              <a href="#" className="social-btn"><Twitter size={18} /></a>
            </div>
            <p className="footer-copy">
              © {new Date().getFullYear()} Mani Candles Co. All rights reserved.
            </p>
          </div>
        </div>
      </footer>
    </Box>
  );
}
