import { useState, useEffect, useMemo } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  ArrowRight, TrendingUp, PoundSterling, Users, Building2, ChevronDown,
} from "lucide-react";
import { useTheme } from "@/hooks/use-theme";

type Study = {
  id: number;
  category: string;
  sector: string;
  title: string;
  summary: string;
  outcome: string;
  impact: string;
  details: string[];
};

const CATEGORIES: { id: string; label: string }[] = [
  { id: "all", label: "All Projects" },
  { id: "enterprise-software", label: "Enterprise Software" },
  { id: "financial-services", label: "Financial Services" },
  { id: "healthcare", label: "Healthcare" },
  { id: "innovation", label: "Innovation" },
  { id: "product-innovation", label: "Product Innovation" },
  { id: "risk-mitigation", label: "Risk Mitigation" },
  { id: "corporate-restructuring", label: "Corporate Restructuring" },
];

const STUDIES: Study[] = [
  { id: 1, category: "enterprise-software", sector: "Global Manufacturing", title: "Microsoft estate transformation across 91 sites, 60 countries",
    summary: "Aggressive Microsoft licensing increases and compliance demands across a £950M enterprise.",
    outcome: "23K employees consolidated onto a unified licensing position",
    impact: "£1.9M direct savings",
    details: ["Comprehensive Microsoft estate analysis and strategic renegotiations across 60 countries", "Enterprise-wide licensing optimisation programme with enhanced support structures", "£1.9M direct savings whilst securing £190K in additional support value"] },
  { id: 2, category: "risk-mitigation", sector: "Risk Mitigation", title: "SAP compliance resolution — penalty cut from £9M to £1.5M",
    summary: "High-stakes SAP audit revealed potential compliance penalties of £9M.",
    outcome: "83% reduction in 15 days",
    impact: "£7.5M penalty avoided",
    details: ["Forensic licence analysis and defensible position identification", "Sophisticated risk management strategies with contract restructuring", "Ongoing compliance framework to prevent future audit exposure"] },
  { id: 3, category: "financial-services", sector: "UK Insurer", title: "Top 20 mutual society transformation",
    summary: "Top 20 UK mutual society facing unsustainable consultancy costs and operational inefficiencies.",
    outcome: "£100M in optimisation opportunities identified",
    impact: "£26M annual savings",
    details: ["Comprehensive operational review identifying £100M in optimisation opportunities", "Redesigned risk management framework eliminating consultancy dependencies", "Enhanced regulatory compliance posture with sustainable operating model"] },
  { id: 4, category: "healthcare", sector: "NHS Trust", title: "SmartER digital platform deployment across emergency departments",
    summary: "NHS emergency departments under pressure, requiring innovative technology to lift throughput.",
    outcome: "30 minutes shaved off average wait times",
    impact: "£3.53 ROI per £1 invested",
    details: ["Real-time analytics, patient flow optimisation, and clinical decision support", "Comprehensive training programmes across multiple NHS trusts", "Reduced average waiting times by 30 minutes per patient interaction"] },
  { id: 5, category: "financial-services", sector: "European Pension Consolidator", title: "£68B AUM consolidator — OPEX restructure",
    summary: "Strategic refocus and operational transformation across multiple European jurisdictions.",
    outcome: "£300M technology investment optimised",
    impact: "£50M OPEX reduction",
    details: ["Comprehensive programme optimisation across all business units", "Enhanced risk capital efficiency through advanced analytics", "Operational excellence framework across multiple European jurisdictions"] },
  { id: 6, category: "innovation", sector: "Technology Portfolio", title: "FDA-recognised innovation across healthcare, energy and motorsport",
    summary: "Building and scaling innovative ventures across regulated and emerging sectors.",
    outcome: "End-to-end support — ideation to deployment",
    impact: "£100M opportunity pipeline",
    details: ["FDA regulatory navigation and Global Motorsports Series partnership development", "Renewable energy project structuring and international expansion", "End-to-end support from ideation to market deployment"] },
  { id: 7, category: "healthcare", sector: "SEND Education", title: "SEND data analytics platform — 1.6M+ pupils tracked",
    summary: "Local authorities struggling to predict and budget for Special Educational Needs services.",
    outcome: "18.4% SEND coverage with real-time insights",
    impact: "Evidence-based planning for 1.6M+ pupils",
    details: ["Sophisticated analytics platform processing data for 1.6M+ pupils across England", "Real-time dashboards with predictive modelling for service demand", "Evidence-based planning supporting better resource allocation"] },
  { id: 8, category: "innovation", sector: "Housing Association", title: "Awaab's Law compliance — sensor-driven maintenance",
    summary: "Social housing providers facing stringent new requirements for damp and mould prevention.",
    outcome: "91% property sensor coverage",
    impact: "Zero damp & mould escalations in pilot",
    details: ["IoT sensors monitoring temperature, humidity, and air quality in real-time", "Automated alert system prioritising interventions based on risk levels", "Comprehensive compliance dashboard for property portfolio management"] },
  { id: 9, category: "enterprise-software", sector: "Market Intelligence", title: "Market Research Pro — 42 sectors, global coverage",
    summary: "Organisations requiring comprehensive, real-time market intelligence across multiple geographies.",
    outcome: "Predictive analytics on 1–10 year horizons",
    impact: "Global coverage, any-sector capability",
    details: ["Real-time insights across 42 sectors with automated data collection", "Live updates with predictive analytics for 1-10 year horizons", "Global coverage across all major geographic regions and industry verticals"] },
  { id: 10, category: "innovation", sector: "Leadership Development", title: "Board & leadership evaluation platform — 360° framework",
    summary: "Traditional leadership assessment failing to engage modern executives.",
    outcome: "4 competencies in 5–7min modules",
    impact: "360° assessment with gamified development",
    details: ["Gamified platform integrating proven frameworks from industry leaders", "360° competency assessments with achievement tracking", "Personalised development recommendations for leadership teams"] },
  { id: 11, category: "financial-services", sector: "European Insurer", title: "Conduct risk framework transformation",
    summary: "Leading insurance group lifting consumer outcomes whilst diversifying revenue.",
    outcome: "32 workshops delivered in 6 months",
    impact: "20% positive uptick in customer success",
    details: ["32 Conduct and Consumer Outcome workshops identifying sales and regulatory nexus", "Significantly revised RMF with dynamic data monitoring", "Customer success measures showed immediate 20% positive uptick"] },
  { id: 12, category: "financial-services", sector: "International Bank", title: "Regulatory governance unblock — group & subsidiary aligned",
    summary: "Regulatory concerns regarding governance framework and parent influence.",
    outcome: "New Target Operating Model adopted",
    impact: "Roadblock removed, growth unlocked",
    details: ["Reviewed governance arrangements working closely with Group CEO and CRO", "Developed new Target Operating Model embracing future service developments", "Group and subsidiary Boards united in single strategic vision"] },
  { id: 13, category: "healthcare", sector: "Health Tech (Family Office)", title: "System-level healthcare expansion across UK & international markets",
    summary: "Family Office portfolio venture seeking to expand into system-level healthcare.",
    outcome: "Three-year strategic roadmap delivered",
    impact: "£100M revenue target over 3 years",
    details: ["Comprehensive assessments across technology, market positioning, and M&A", "Specific Search and Acquire Strategy development", "Three-year strategic roadmap for significant scaling"] },
  { id: 14, category: "healthcare", sector: "Global Health (Africa)", title: "Voice-AI wearable for maternal health in resource-limited settings",
    summary: "US university wearable program needing turnaround on stakeholder engagement and design.",
    outcome: "Global OBGYN specialists onboarded",
    impact: "FDA recognition secured",
    details: ["Turnaround team in rural Africa reassessing design scope", "Collaboration with Kenyan midwives and clinical staff", "Voice-activated, AI-powered device with global OBGYN specialists"] },
  { id: 15, category: "innovation", sector: "Food Safety & Authentication", title: "FDA-winning blockchain traceability across 5 industries",
    summary: "Asset authentication, fraud prevention and supply chain transparency challenge.",
    outcome: "Tested across luxury, AgriFood, clothing, art, pharma",
    impact: "FDA Global Challenge winner, 2021",
    details: ["Design thinking utilising near and far field communications with distributed ledgers", "Tested across luxury goods, AgriFood, clothing, artworks, and pharmaceuticals", "Winner of US FDA's Global Challenge 'A New Era of Food Safety' in 2021"] },
  { id: 16, category: "innovation", sector: "Energy Storage", title: "Europe's #1 long-duration energy storage leader — restructure",
    summary: "Pan-European mass energy storage platform built on renewable CAES technology.",
    outcome: "Refocus on CAES for renewables integration",
    impact: "EURONext listed, #1 LDES in Europe",
    details: ["Evaluation and assessment workshops centering on UN Sustainable Development Goals", "Restructured business focusing on CAES solutions for renewables integration", "Now largest provider of LDES solutions in Europe"] },
  { id: 17, category: "innovation", sector: "Motorsport Tech", title: "Global Motorsports Series LED wheel innovation — whole-grid deal",
    summary: "LED wheel technology requiring business restructuring and investor confidence.",
    outcome: "Featured on NBC, whole-grid coverage",
    impact: "3-year supply deal secured",
    details: ["Reassessed viability with investors including well-known public figures", "Secured funding and restructured business whilst continuing technology development", "Signed three-year whole-of-grid supply deal with Global Motorsports Series"] },
  { id: 18, category: "corporate-restructuring", sector: "Global SaaS & PE", title: "VC-driven separation of global software business",
    summary: "Consolidation requiring separation and FTE reduction from ~2000 to optimised divisions.",
    outcome: "2000+ IT vendors separated in waves",
    impact: "£6.9M+ savings, 1400 final FTE",
    details: ["Separation of >2000 IT vendors with wave-led approach to cost reduction", "Optimisation for future IT TOM for both divisions", "Advanced legal separation with detailed plan for residual vendors"] },
  { id: 19, category: "product-innovation", sector: "ContractIQ", title: "Zero-to-one MVP launched in 90 days — FTSE 100 client",
    summary: "Built from concept to live product in 90 days; rapid major enterprise client adoption.",
    outcome: "Global corporate as first client",
    impact: "FTSE 100 second client, growing pipeline",
    details: ["Zero-to-one product build delivering a fully functional MVP in just 90 days", "First client secured was a global corporate enterprise", "Second client a FTSE 100 company — momentum and growth continues"] },
  { id: 20, category: "product-innovation", sector: "Fourier", title: "MVP to full launch in 3 months across schools, PE & corporate",
    summary: "From concept to market-ready product in three months, now serving diverse sectors.",
    outcome: "Active across 3 sectors",
    impact: "Live in market, continued adoption",
    details: ["Rapid MVP development and launch completed within 3 months", "Now actively deployed in schools supporting education outcomes", "Expanded into private equity and corporate client base with continued adoption"] },
];

const CaseStudiesSection = () => {
  const { theme } = useTheme();
  const isDark = theme === "dark";
  const [filter, setFilter] = useState("all");
  const [expanded, setExpanded] = useState<number | null>(null);
  const [metricSet, setMetricSet] = useState(0);

  // Palette
  const p = {
    bg: isDark ? "hsl(265, 32%, 5%)" : "transparent",
    panel: isDark ? "hsla(260, 25%, 10%, 0.7)" : "#ffffff",
    border: isDark ? "hsl(265, 22%, 18%)" : "hsl(214, 32%, 91%)",
    borderSoft: isDark ? "hsla(265, 22%, 22%, 0.6)" : "hsl(214, 32%, 91%)",
    text: isDark ? "hsl(40, 25%, 96%)" : "hsl(222, 47%, 11%)",
    textHeading: isDark ? "hsl(36, 22%, 94%)" : "hsl(222, 47%, 11%)",
    muted: isDark ? "hsl(265, 18%, 72%)" : "hsl(215, 16%, 47%)",
    violet: "hsl(258, 92%, 66%)",
    gold: "hsl(36, 88%, 60%)",
    peach: "hsl(20, 95%, 65%)",
    emerald: "hsl(158, 70%, 55%)",
  };
  const accents = [p.gold, p.violet, p.peach, p.emerald];

  // Rotating headline metrics (4 tiles)
  const metricSets = useMemo(() => ([
    [
      { value: "£92.3M+", label: "Savings delivered", icon: PoundSterling, accent: p.gold },
      { value: "£616.3M+", label: "Value optimised", icon: TrendingUp, accent: p.violet },
      { value: String(STUDIES.length), label: "Transformation programmes", icon: Building2, accent: p.peach },
      { value: "240+", label: "Leaders coached", icon: Users, accent: p.emerald },
    ],
    [
      { value: "£68B", label: "AUM transformed", icon: PoundSterling, accent: p.gold },
      { value: "£300M", label: "Tech investment optimised", icon: TrendingUp, accent: p.violet },
      { value: "60", label: "Countries reached", icon: Building2, accent: p.peach },
      { value: "1.6M+", label: "Pupils supported", icon: Users, accent: p.emerald },
    ],
    [
      { value: "£26M+", label: "Annual savings (UK insurer)", icon: PoundSterling, accent: p.gold },
      { value: "£190K+", label: "Monthly savings (manufacturing)", icon: TrendingUp, accent: p.violet },
      { value: "91", label: "Sites transformed", icon: Building2, accent: p.peach },
      { value: "23K", label: "Employees onboarded", icon: Users, accent: p.emerald },
    ],
  // eslint-disable-next-line react-hooks/exhaustive-deps
  ]), [isDark]);

  useEffect(() => {
    const id = setInterval(() => setMetricSet(s => (s + 1) % metricSets.length), 5000);
    return () => clearInterval(id);
  }, [metricSets.length]);

  const filtered = useMemo(
    () => (filter === "all" ? STUDIES : STUDIES.filter(s => s.category === filter)),
    [filter]
  );

  return (
    <section
      id="case-studies"
      className="relative overflow-hidden"
      style={{ background: p.bg, color: p.text, padding: "80px 0 96px" }}
    >
      {isDark && (
        <div
          aria-hidden
          className="absolute inset-0 pointer-events-none"
          style={{
            background: `
              radial-gradient(900px 600px at 10% -50px, hsla(265, 70%, 20%, 0.4) 0%, transparent 60%),
              radial-gradient(700px 500px at 90% 5%, hsla(285, 60%, 22%, 0.35) 0%, transparent 55%)
            `,
          }}
        />
      )}

      <div className="container mx-auto px-4 sm:px-6 relative">
        {/* Header */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6 }}
          viewport={{ once: true, margin: "-50px" }}
          className="max-w-5xl"
        >
          <p style={{ color: p.gold, fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase", margin: 0, fontWeight: 500 }}>
            Transformational Outcomes
          </p>
          <h2
            className="font-heading-serif"
            style={{
              fontWeight: 400,
              fontSize: "clamp(28px, 4.5vw, 52px)",
              margin: "12px 0 4px",
              color: p.textHeading,
              letterSpacing: "-0.01em",
              lineHeight: 1.1,
            }}
          >
            Results that{" "}
            <span
              style={{
                background: `linear-gradient(135deg, ${p.gold}, ${p.peach}, ${p.violet})`,
                WebkitBackgroundClip: "text",
                WebkitTextFillColor: "transparent",
                backgroundClip: "text",
                color: "transparent",
              }}
            >
              compound
            </span>
          </h2>
          <div
            style={{
              width: 140,
              height: 2,
              marginTop: 12,
              borderRadius: 2,
              background: `linear-gradient(90deg, ${p.violet}, ${p.peach}, ${p.gold})`,
            }}
          />
          <p style={{ color: p.muted, fontSize: 16, maxWidth: 720, margin: "20px 0 32px", lineHeight: 1.6 }}>
            {STUDIES.length} authenticated programmes across healthcare, education, social housing,
            finance and central government.
          </p>
        </motion.div>

        {/* Metric tiles */}
        <div className="grid gap-4" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 240px), 1fr))" }}>
          {metricSets[metricSet].map((m, i) => {
            const Icon = m.icon;
            return (
              <div
                key={i}
                style={{
                  padding: 22,
                  borderRadius: 14,
                  background: p.panel,
                  border: `1px solid ${p.border}`,
                  position: "relative",
                  overflow: "hidden",
                }}
                data-testid={`metric-tile-${i}`}
              >
                <div style={{ position: "absolute", top: 0, left: 22, right: 22, height: 1, background: `linear-gradient(90deg, transparent, ${m.accent}, transparent)`, opacity: 0.55 }} />
                <Icon size={20} color={m.accent} strokeWidth={1.6} />
                <AnimatePresence mode="wait">
                  <motion.div
                    key={`v-${metricSet}-${i}`}
                    initial={{ y: 12, opacity: 0 }}
                    animate={{ y: 0, opacity: 1 }}
                    exit={{ y: -12, opacity: 0 }}
                    transition={{ duration: 0.35 }}
                    className="font-heading-serif"
                    style={{ fontSize: 34, fontWeight: 400, color: p.textHeading, margin: "10px 0 4px", letterSpacing: "-0.01em", lineHeight: 1.1 }}
                  >
                    {m.value}
                  </motion.div>
                </AnimatePresence>
                <AnimatePresence mode="wait">
                  <motion.div
                    key={`l-${metricSet}-${i}`}
                    initial={{ y: 8, opacity: 0 }}
                    animate={{ y: 0, opacity: 1 }}
                    exit={{ y: -8, opacity: 0 }}
                    transition={{ duration: 0.3, delay: 0.05 }}
                    style={{ fontSize: 12, color: p.muted, letterSpacing: "0.02em" }}
                  >
                    {m.label}
                  </motion.div>
                </AnimatePresence>
              </div>
            );
          })}
        </div>

        {/* Category filter pills */}
        <div className="mt-10 flex flex-wrap gap-2">
          {CATEGORIES.map(c => {
            const active = filter === c.id;
            return (
              <button
                key={c.id}
                onClick={() => { setFilter(c.id); setExpanded(null); }}
                style={{
                  fontSize: 12,
                  padding: "7px 14px",
                  borderRadius: 999,
                  background: active ? p.violet : "transparent",
                  color: active ? "#fff" : p.muted,
                  border: `1px solid ${active ? p.violet : p.borderSoft}`,
                  cursor: "pointer",
                  fontWeight: active ? 500 : 400,
                  transition: "all 200ms ease",
                }}
                data-testid={`filter-${c.id}`}
              >
                {c.label}
              </button>
            );
          })}
        </div>

        {/* List */}
        <div className="mt-6 flex flex-col gap-4">
          {filtered.map((s, i) => {
            const accent = accents[i % accents.length];
            const isOpen = expanded === s.id;
            return (
              <motion.div
                key={s.id}
                layout
                initial={{ opacity: 0, y: 12 }}
                whileInView={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.4, delay: Math.min(i * 0.03, 0.3) }}
                viewport={{ once: true, margin: "-50px" }}
                style={{
                  padding: "24px 28px",
                  borderRadius: 14,
                  background: p.panel,
                  border: `1px solid ${p.border}`,
                  position: "relative",
                  overflow: "hidden",
                }}
                data-testid={`case-row-${s.id}`}
              >
                {/* Left accent bar */}
                <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 3, background: `linear-gradient(180deg, ${accent}, transparent)` }} />

                <div
                  className="grid items-center gap-4 sm:gap-6"
                  style={{ gridTemplateColumns: "minmax(120px, 180px) 1fr auto" }}
                >
                  {/* Left meta */}
                  <div>
                    <span style={{ fontSize: 10.5, color: accent, letterSpacing: "0.1em", textTransform: "uppercase", fontWeight: 500 }}>
                      {s.sector}
                    </span>
                    <div className="font-heading-serif" style={{ fontSize: 22, color: p.textHeading, marginTop: 6 }}>
                      {String(i + 1).padStart(2, "0")}
                    </div>
                  </div>

                  {/* Middle */}
                  <div className="min-w-0">
                    <h3 className="font-heading-serif" style={{ fontSize: 19, fontWeight: 500, margin: "0 0 8px", color: p.textHeading, lineHeight: 1.3 }}>
                      {s.title}
                    </h3>
                    <div className="flex flex-wrap gap-x-6 gap-y-1.5" style={{ fontSize: 13 }}>
                      <span style={{ color: p.muted }}>
                        Outcome: <span style={{ color: p.text }}>{s.outcome}</span>
                      </span>
                      <span style={{ color: p.muted }}>
                        Impact: <span style={{ color: p.gold }}>{s.impact}</span>
                      </span>
                    </div>
                  </div>

                  {/* Right CTA */}
                  <button
                    onClick={() => setExpanded(isOpen ? null : s.id)}
                    className="flex items-center gap-1.5 whitespace-nowrap"
                    style={{
                      padding: "9px 16px",
                      borderRadius: 999,
                      fontSize: 12.5,
                      fontWeight: 500,
                      background: "transparent",
                      color: p.text,
                      border: `1px solid ${p.border}`,
                      cursor: "pointer",
                    }}
                    data-testid={`button-read-study-${s.id}`}
                    aria-expanded={isOpen}
                  >
                    {isOpen ? "Hide" : "Read study"}
                    {isOpen ? <ChevronDown size={13} style={{ transform: "rotate(180deg)" }} /> : <ArrowRight size={13} />}
                  </button>
                </div>

                {/* Expanded detail */}
                <AnimatePresence initial={false}>
                  {isOpen && (
                    <motion.div
                      initial={{ height: 0, opacity: 0 }}
                      animate={{ height: "auto", opacity: 1 }}
                      exit={{ height: 0, opacity: 0 }}
                      transition={{ duration: 0.3, ease: "easeOut" }}
                      style={{ overflow: "hidden" }}
                    >
                      <div className="mt-5 pt-5" style={{ borderTop: `1px solid ${p.borderSoft}` }}>
                        <p style={{ color: p.muted, fontSize: 14, margin: "0 0 12px", lineHeight: 1.6 }}>
                          {s.summary}
                        </p>
                        <ul className="space-y-2">
                          {s.details.map((d, k) => (
                            <li key={k} className="flex items-start gap-3" style={{ fontSize: 13.5, color: p.text, lineHeight: 1.55 }}>
                              <span style={{ width: 4, height: 4, borderRadius: "50%", background: accent, marginTop: 8, flexShrink: 0 }} />
                              <span>{d}</span>
                            </li>
                          ))}
                        </ul>
                      </div>
                    </motion.div>
                  )}
                </AnimatePresence>
              </motion.div>
            );
          })}
        </div>

        {filtered.length === 0 && (
          <div className="text-center py-12" style={{ color: p.muted }}>
            No case studies in this category yet.
          </div>
        )}
      </div>
    </section>
  );
};

export default CaseStudiesSection;
