"use client";

import { motion, useScroll, useTransform, AnimatePresence } from "framer-motion";
import Link from "next/link";
import { useState, useEffect } from "react";
import { newsItems } from "@/data/siteData";

// ── Shared Constants & Tokens ──────────────────────────────────────────
const G = "#C9A84C";
const GL = "#E8D5A3";
const DARK = "#07070A";
const DARK2 = "#0D0D12";

const goldText: React.CSSProperties = {
  background: `linear-gradient(135deg, ${G} 0%, ${GL} 45%, ${G} 100%)`,
  WebkitBackgroundClip: "text",
  WebkitTextFillColor: "transparent",
  backgroundClip: "text",
};

const GSHADOW = `0 4px 32px rgba(0,0,0,0.45), 0 0 0 1px ${G}22, 0 8px 48px rgba(198,160,79,0.18)`;

// ── Components ────────────────────────────────────────────────────────
function GoldDiamond({ size = 12, opacity = 0.5 }: { size?: number; opacity?: number }) {
  return (
    <div style={{
      width: size, height: size, transform: "rotate(45deg)",
      background: `linear-gradient(135deg, ${G}, ${GL})`, opacity, flexShrink: 0,
    }} />
  );
}

function SectionDiamonds() {
  return (
    <div style={{ position: "absolute", top: 0, left: 0, right: 0, display: "flex", justifyContent: "center", transform: "translateY(-50%)", zIndex: 20 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <div style={{ width: 80, height: 1, background: `linear-gradient(90deg, transparent, ${G}60)` }} />
        <GoldDiamond size={6} opacity={0.3} />
        <GoldDiamond size={10} opacity={0.8} />
        <GoldDiamond size={6} opacity={0.3} />
        <div style={{ width: 80, height: 1, background: `linear-gradient(270deg, transparent, ${G}60)` }} />
      </div>
    </div>
  );
}

function FloatingDiamonds() {
  return (
    <div style={{ position: "absolute", inset: 0, pointerEvents: "none", overflow: "hidden" }}>
      {[
        { x: "10%", y: "15%", size: 6, delay: 0, dur: 9 },
        { x: "85%", y: "45%", size: 8, delay: 2, dur: 11 },
        { x: "70%", y: "80%", size: 5, delay: 4, dur: 8 },
        { x: "20%", y: "75%", size: 7, delay: 1, dur: 13 },
      ].map((d, i) => (
        <motion.div
          key={i}
          animate={{ y: [0, -30, 0], opacity: [0.1, 0.35, 0.1] }}
          transition={{ duration: d.dur, repeat: Infinity, ease: "easeInOut", delay: d.delay }}
          style={{ position: "absolute", left: d.x, top: d.y, width: d.size, height: d.size, transform: "rotate(45deg)", background: `linear-gradient(135deg, ${G}, ${GL})` }}
        />
      ))}
    </div>
  );
}

// ── Data ──────────────────────────────────────────────────────────────
const allArticles = [
  {
    title: "Crown Rock Minerals Strategic Multi-Asset Vision 2026",
    date: "March 12, 2026",
    category: "News",
    excerpt: "Operational roadmap for regional expansion and technical infrastructure development across core African corridors.",
    slug: "strategic-vision-2026",
    image: "/images/blog_strategic_vision.png",
  },
  {
    title: "Greenfield Project Development in Sudan 🇸🇩: Technical Briefing",
    date: "February 28, 2026",
    category: "Insights",
    excerpt: "Deep dive into structural geology and phased exploration frameworks for high-potential mineral assets.",
    slug: "greenfield-sudan-briefing",
    image: "/images/blog_greenfield_sudan.png",
  },
  {
    title: "Annual Sustainability & ESG Performance Report 2025",
    date: "January 20, 2026",
    category: "Reports",
    excerpt: "Quantifying our commitment to environmental stewardship, social integration, and governance excellence.",
    slug: "sustainability-report-2025",
    image: "/images/blog_sustainability_report.png",
  },
  {
    title: "Crown Rock Minerals Appoints New Head of Geological Services",
    date: "February 15, 2026",
    category: "News",
    excerpt: "A seasoned geologist with 20+ years of African mining experience joins the leadership team.",
    slug: "new-head-geological-services",
    image: "/images/Image_fx (1).png",
  },
  {
    title: "Understanding Sudan's Mineral Potential: A Technical Perspective",
    date: "February 1, 2026",
    category: "Insights",
    excerpt: "An exploration-focused analysis of Sudan's geological formations and their implications for mining development.",
    slug: "sudan-mineral-potential",
    image: "/images/Image_fx (2).png",
  },
];

const realisticSliderImages = [
  { img: "/images/hero-mine-bg.png", label: "Sudan 🇸🇩 Mining Operations", desc: "Large-scale greenfield development site." },
  { img: "/images/showcase_mining.png", label: "Geological Surveying", desc: "Technical mapping of mineral-rich belts." },
  { img: "/images/sustainability_hero.png", label: "Sustainable Landscapes", desc: "Integrating operations with natural topography." },
  { img: "/images/showcase_landscape.png", label: "East African Corridors", desc: "Regional expansion initiatives." },
  { img: "/images/878787.png", label: "Operational Infrastructure", desc: "Building the foundation for sustainable mining." },
  { img: "/images/1247777.png", label: "Site Assessment", desc: "Rigorous technical inspection and evaluation." },
  { img: "/images/blog_greenfield_sudan.png", label: "Advanced Operations", desc: "Expanding robust processing capacity across multiple sites." },
  { img: "/images/showcase_tech.png", label: "Technological Integration", desc: "Utilizing modern technology for precise extraction." },
  { img: "/images/22222 (1).png", label: "Greenfield Pipeline", desc: "Scaling operations across highly prospective African zones." },
  { img: "/images/processing_technical.png", label: "Technical Processing", desc: "Delivering high-purity yields through advanced metallurgy." }
];

// ── Slider Component ──────────────────────────────────────────────────
function ImageSlider() {
  const [currentIndex, setCurrentIndex] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentIndex((prev) => (prev + 1) % realisticSliderImages.length);
    }, 5000);
    return () => clearInterval(timer);
  }, []);

  return (
    <div className="media-slider" style={{ position: "relative", width: "100%", height: "600px", borderRadius: 4, overflow: "hidden", boxShadow: GSHADOW, border: `1px solid ${G}30` }}>
      <AnimatePresence initial={false}>
        <motion.div
          key={currentIndex}
          initial={{ opacity: 0, scale: 1.05 }}
          animate={{ opacity: 1, scale: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 1.2, ease: "easeInOut" }}
          style={{ position: "absolute", inset: 0 }}
        >
          <img 
            src={realisticSliderImages[currentIndex].img} 
            alt={realisticSliderImages[currentIndex].label}
            style={{ width: "100%", height: "100%", objectFit: "cover" }}
          />
          {/* Gradients for text readability */}
          <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to top, rgba(0,0,0,0.9) 0%, rgba(0,0,0,0.4) 30%, transparent 100%)" }} />
          <div style={{ position: "absolute", inset: 0, background: "radial-gradient(ellipse at center, transparent, rgba(0,0,0,0.2))" }} />
          
          <motion.div 
            initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.5, duration: 0.7 }}
            className="slider-content"
            style={{ position: "absolute", bottom: 40, left: 40, right: 40, display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 32 }}
          >
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
                <GoldDiamond size={8} opacity={0.8} />
                <span style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.2em", color: G, fontWeight: 700 }}>Field Report {currentIndex + 1} / {realisticSliderImages.length}</span>
              </div>
              <h3 style={{ fontFamily: "'Syncopate', sans-serif", fontSize: "clamp(24px, 3vw, 36px)", color: "#FFF", textTransform: "uppercase", margin: "0 0 12px" }}>
                {realisticSliderImages[currentIndex].label}
              </h3>
              <p style={{ fontSize: 16, color: "rgba(255,255,255,0.7)", margin: 0, fontWeight: 300 }}>
                {realisticSliderImages[currentIndex].desc}
              </p>
            </div>
            
            {/* Dots */}
            <div style={{ display: "flex", gap: 12 }}>
              {realisticSliderImages.map((_, idx) => (
                <div 
                  key={idx} 
                  onClick={() => setCurrentIndex(idx)}
                  style={{ 
                    width: idx === currentIndex ? 30 : 8, height: 8, borderRadius: 4, 
                    background: idx === currentIndex ? G : "rgba(255,255,255,0.3)", 
                    cursor: "pointer", transition: "all 0.3s ease" 
                  }} 
                />
              ))}
            </div>
          </motion.div>
        </motion.div>
      </AnimatePresence>
    </div>
  );
}

// ── Hero ──────────────────────────────────────────────────────────────
function Hero() {
  const { scrollYProgress } = useScroll();
  const y = useTransform(scrollYProgress, [0, 0.4], [0, 160]);
  const scale = useTransform(scrollYProgress, [0, 0.5], [1, 1.05]);

  return (
    <section style={{ position: "relative", minHeight: "80vh", display: "flex", alignItems: "center", background: "#000", overflow: "hidden" }}>
      <motion.div style={{ position: "absolute", inset: 0, scale, opacity: 0.4 }}>
        <img src="/images/hero_bg.png" alt="Media Center Hero" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to bottom, transparent 40%, #000 100%)" }} />
      </motion.div>
      
      <FloatingDiamonds />

      <motion.div className="resp-container" style={{ y, position: "relative", zIndex: 10, width: "100%", maxWidth: 1200, margin: "0 auto", padding: "0 64px" }}>
        <motion.div initial={{ opacity: 0, x: -20 }} animate={{ opacity: 1, x: 0 }} style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 40 }}>
          <span style={{ width: 40, height: 1, background: G }} />
          <GoldDiamond size={6} opacity={0.6} />
          <span style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.22em", fontWeight: 700, color: G }}>Insights & News</span>
        </motion.div>

        <motion.h1 initial={{ opacity: 0, y: 48 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 1.1, delay: 0.1 }}
          style={{ fontFamily: "'Syncopate', sans-serif", fontSize: "clamp(36px, 6vw, 84px)", fontWeight: 700, lineHeight: 0.95, letterSpacing: "-0.03em", margin: "0 0 32px", textTransform: "uppercase", color: "#FFF" }}>
          MEDIA<br />
          <span style={goldText}>CENTER</span>
        </motion.h1>

        <motion.p initial={{ opacity: 0, y: 28 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.9, delay: 0.3 }}
          style={{ fontSize: 18, lineHeight: 1.8, maxWidth: 540, color: "rgba(255,255,255,0.6)", fontWeight: 300, margin: 0 }}>
          Documenting our journey across Africa — from technical field discoveries to institutional strategic milestones.
        </motion.p>
      </motion.div>
      
      <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, height: 250, background: `linear-gradient(to top, ${DARK}, transparent)`, zIndex: 5 }} />
    </section>
  );
}

// ── Main Page ─────────────────────────────────────────────────────────
export default function MediaContent() {
  return (
    <div style={{ background: DARK, color: "#FFF", overflow: "hidden" }}>
      <style>{`
        @media(max-width: 1024px) {
          .resp-section { padding: 80px 0 !important; }
          .resp-container { padding: 0 24px !important; }
          .child-grid { grid-template-columns: 1fr !important; }
          .media-slider { height: 450px !important; }
          .slider-content { bottom: 20px !important; left: 24px !important; right: 24px !important; flex-direction: column !important; align-items: flex-start !important; }
        }
        @media(max-width: 480px) {
          .media-slider { height: 400px !important; }
        }
      `}</style>
      <Hero />

      {/* ── LATEST ARTICLES ── */}
      <section className="resp-section" style={{ padding: "120px 0", background: DARK, position: "relative" }}>
        <div style={{ position: "absolute", left: "10%", top: 0, bottom: 0, width: 1, background: `linear-gradient(to bottom, transparent, ${G}15, transparent)` }} />
        <div className="resp-container" style={{ maxWidth: 1200, margin: "0 auto", padding: "0 64px", position: "relative", zIndex: 10 }}>
          <div style={{ marginBottom: 80, display: "flex", flexDirection: "column", gap: 20 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <span style={{ width: 32, height: 1, background: G }} />
              <GoldDiamond size={6} opacity={0.6} />
              <span style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.22em", color: G, fontWeight: 700 }}>Editorial Feed</span>
            </div>
            <h2 style={{ fontFamily: "'Syncopate', sans-serif", fontSize: "clamp(28px, 3.5vw, 44px)", textTransform: "uppercase", color: "#FFF", margin: 0 }}>
              NEWS & <span style={goldText}>INSIGHTS</span>
            </h2>
          </div>

          <div className="child-grid" style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(340px, 1fr))", gap: 32 }}>
            {allArticles.map((article, i) => (
              <ArticleCard key={article.slug} article={article} index={i} />
            ))}
          </div>
        </div>
      </section>

      {/* ── PHOTO GALLERY SLIDER ── */}
      <section className="resp-section" style={{ padding: "160px 0", background: DARK2, borderTop: "1px solid rgba(255,255,255,0.05)", position: "relative" }}>
        <SectionDiamonds />
        <FloatingDiamonds />
        
        <div style={{ position: "absolute", inset: 0, opacity: 0.1 }}>
          <img src="/images/20 (8).png" alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
          <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to right, #0D0D12 10%, transparent 50%, #0D0D12 90%)" }} />
        </div>

        <div className="resp-container" style={{ maxWidth: 1200, margin: "0 auto", padding: "0 64px", position: "relative", zIndex: 10 }}>
          <div style={{ textAlign: "center", marginBottom: 80 }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 12, marginBottom: 20 }}>
              <span style={{ width: 32, height: 1, background: G }} />
              <GoldDiamond size={6} opacity={0.6} />
              <span style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.22em", color: G, fontWeight: 700 }}>Visual Assets</span>
              <GoldDiamond size={6} opacity={0.6} />
              <span style={{ width: 32, height: 1, background: G }} />
            </div>
            <h2 style={{ fontFamily: "'Syncopate', sans-serif", fontSize: "clamp(28px, 3.5vw, 44px)", textTransform: "uppercase", color: "#FFF", margin: 0 }}>
              PROFESSIONAL <span style={goldText}>GALLERY</span>
            </h2>
          </div>

          <ImageSlider />
        </div>
      </section>

      {/* Decorative Ornaments */}
      <section style={{ padding: "80px 0", textAlign: "center", background: DARK }}>
        <SectionDiamonds />
      </section>
    </div>
  );
}

function ArticleCard({ article, index }: { article: any; index: number }) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 24 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true }} transition={{ duration: 0.6, delay: index * 0.1 }}
    >
      <Link href={`/media/${article.slug}`} style={{ display: "block", background: "rgba(255,255,255,0.02)", borderRadius: 4, overflow: "hidden", border: "1px solid rgba(255,255,255,0.08)", transition: "all 0.5s cubic-bezier(0.23, 1, 0.32, 1)", textDecoration: "none", position: "relative" }} className="hover:border-brand-gold/40 hover:-translate-y-2 group">
        <div style={{ position: "absolute", top: 12, right: 12, zIndex: 10 }}><GoldDiamond size={5} opacity={0.3} /></div>
        
        <div style={{ position: "relative", height: 220, overflow: "hidden" }}>
          <img src={article.image} alt={article.title} style={{ width: "100%", height: "100%", objectFit: "cover", transition: "transform 1s cubic-bezier(0.25, 1, 0.5, 1)" }} className="group-hover:scale-105" />
          <div style={{ position: "absolute", top: 20, left: 20 }}>
            <span style={{ background: "rgba(7,7,10,0.8)", backdropFilter: "blur(4px)", padding: "4px 12px", borderRadius: 2, fontSize: 10, textTransform: "uppercase", letterSpacing: "0.15em", color: G, fontWeight: 700, border: `1px solid ${G}30` }}>
              {article.category}
            </span>
          </div>
        </div>
        <div style={{ padding: "32px" }}>
          <div style={{ fontSize: 12, color: "rgba(255,255,255,0.4)", marginBottom: 16, display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ width: 20, height: 1, background: "rgba(255,255,255,0.1)" }} />
            {article.date}
          </div>
          <h3 style={{ fontSize: 20, fontWeight: 600, color: "#FFF", marginBottom: 16, lineHeight: 1.4, transition: "color 0.3s" }}>
            {article.title}
          </h3>
          <p style={{ fontSize: 14, color: "rgba(255,255,255,0.45)", lineHeight: 1.7, margin: 0 }}>
            {article.excerpt}
          </p>
        </div>
      </Link>
    </motion.div>
  );
}
