"use client";
import React, { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { SpotlightCard } from "@/components/SpotlightCard";
import { Globe, Shield, Activity, Landmark, Boxes, Cpu, Settings, ChevronRight, Zap, CheckCircle2 } from "lucide-react";

interface ProjectSite {
  name: string;
  latY: number; // For SVG mapping coordinates
  lngX: number; // For SVG mapping coordinates
}

interface Project {
  id: string;
  client: string;
  color: string;
  sitesCount: number;
  siteType: string;
  devices: string;
  systems: string;
  sysType: string;
  features: string[];
  sector: string;
  savings: string;
  status: "NOMINAL" | "WARNING";
  statusText?: string;
  sites: ProjectSite[];
}

const PROJECTS: Project[] = [
  {
    id: "delice",
    client: "Délice Danone",
    color: "#003F8A",
    sitesCount: 7,
    siteType: "Industrial Sites",
    devices: "480+",
    systems: "23+",
    sysType: "PLCs & AHU Control Systems",
    features: ["Cogeneration Monitoring", "Photovoltaic (PV) Integration", "24/7 Energy Monitoring"],
    sector: "Food & Beverage",
    savings: "↓ -18%",
    status: "NOMINAL",
    sites: [
      { name: "STIAL Plant – Soliman, Cap-Bon", latY: 120, lngX: 180 },
      { name: "Fromagerie – Z.I. Borj Cedria", latY: 140, lngX: 160 },
      { name: "Laiterie Nord – Bousalem", latY: 130, lngX: 100 },
      { name: "Laiterie Sidi Bouzid – Z.I. Lassouda", latY: 260, lngX: 110 },
      { name: "Headquarters – Les Berges du Lac, Tunis", latY: 110, lngX: 155 },
    ]
  },
  {
    id: "sfbt",
    client: "Coca-Cola (SFBT)",
    color: "#E61E14",
    sitesCount: 4,
    siteType: "Industrial Sites",
    devices: "240+",
    systems: "9+",
    sysType: "PLCs & AHU Control Systems",
    features: ["Quad-Generation System", "Energy Optimization", "SCADA Supervision"],
    sector: "Beverages & FMCG",
    savings: "↓ -12%",
    status: "NOMINAL",
    sites: [
      { name: "SFBT Plant – Charguia, Tunis", latY: 100, lngX: 150 },
      { name: "SGBIA Plant – Mégrine, Ben Arous", latY: 125, lngX: 155 },
      { name: "STBG Plant – Bou Argoub, Cap-Bon", latY: 145, lngX: 185 },
      { name: "SFBT Plant – Sfax", latY: 290, lngX: 190 },
    ]
  },
  {
    id: "warda",
    client: "Pâtes Warda",
    color: "#F4B41A",
    sitesCount: 5,
    siteType: "Milling & Extrusion Lines",
    devices: "420+",
    systems: "16+",
    sysType: "PLC Controllers",
    features: ["Extruder Flow Synchronization", "Energy Consumption Logging", "Predictive Motor Maintenance"],
    sector: "Food & Milling",
    savings: "↓ -15%",
    status: "NOMINAL",
    sites: [
      { name: "Warda Sousse Mill – Sousse", latY: 180, lngX: 200 },
      { name: "Warda Sfax Logistics – Sfax", latY: 295, lngX: 185 },
      { name: "Warda Tunis Packaging – Tunis", latY: 115, lngX: 145 },
    ]
  },
  {
    id: "sgba",
    client: "SGBA Cement",
    color: "#00D4FF",
    sitesCount: 3,
    siteType: "Cement Kilns",
    devices: "920+",
    systems: "45+",
    sysType: "Process PLCs & Thermal Sensors",
    features: ["Kiln Combustion Profiles", "Power Quality Analysis", "Carbon Scope Auditing"],
    sector: "Heavy Industry",
    savings: "↓ -20%",
    status: "WARNING",
    statusText: "5th-harmonic current distortion exceedance detected at Gabès raw mill feeder A",
    sites: [
      { name: "SGBA Kiln Plant – Gabès", latY: 360, lngX: 165 },
      { name: "SGBA Raw Mill Center – Tunis", latY: 110, lngX: 140 },
      { name: "SGBA Quarry Node – Djebel Ressas", latY: 130, lngX: 150 },
    ]
  }
];

export default function MultisitePage() {
  const [activeProject, setActiveProject] = useState<Project>(PROJECTS[0]);

  return (
    <div className="relative min-h-screen pt-20 pb-16 overflow-hidden">
      {/* Background Grids */}
      <div className="pointer-events-none absolute inset-0 orbit-grid-mesh opacity-80" />
      <div className="pointer-events-none absolute inset-0 orbit-radial-glow" />

      <div className="mx-auto max-w-7xl px-6 lg:px-8 relative z-10 space-y-16">
        
        {/* Breadcrumb & Cinematic Hero */}
        <div className="space-y-6">
          <div className="flex items-center gap-2 text-xs font-mono text-slate-500">
            <span>Home</span>
            <ChevronRight className="h-3 w-3" />
            <span>Solutions</span>
            <ChevronRight className="h-3 w-3" />
            <span className="text-slate-700 dark:text-slate-300">Multi-Site Monitoring</span>
          </div>

          <div className="grid gap-8 lg:grid-cols-12 lg:items-center">
            <div className="lg:col-span-7 space-y-6">
              <div className="inline-flex items-center gap-1.5 rounded-full border border-orbit-cyan/20 bg-orbit-cyan/5 px-4 py-1.5 font-mono text-xs font-bold text-orbit-cyan">
                <Globe className="h-4.5 w-4.5 animate-pulse" />
                Enterprise · Centralized Multi-Site supervision
              </div>
              <h1 className="text-4xl font-extrabold tracking-tight sm:text-6xl text-slate-900 dark:text-slate-100 leading-tight">
                Proven Engineering<br />
                <span className="bg-gradient-to-r from-orbit-cyan to-orbit-purple bg-clip-text text-transparent">Centralized Across Multi-Site</span><br />
                Mega Projects
              </h1>
              <p className="text-base md:text-lg leading-relaxed text-slate-600 dark:text-slate-400 max-w-2xl">
                Orbit deploys industrial energy monitoring, SCADA platforms, and automated control logic across Tunisia&apos;s largest enterprise networks — ranging from 4 to 300 simultaneous sites.
              </p>
              
              <div className="flex flex-wrap gap-4 pt-2">
                <a
                  href="/contact"
                  className="flex h-11 items-center justify-center rounded-full bg-gradient-to-r from-orbit-cyan to-orbit-purple px-6 text-xs font-bold font-mono text-white shadow-lg active:scale-95 transition-transform"
                >
                  Book Assessment
                </a>
                <a
                  href="#projects"
                  className="flex h-11 items-center justify-center rounded-full border border-orbit-border bg-orbit-bg-primary/50 px-6 text-xs font-bold font-mono text-slate-700 dark:text-slate-300 hover:text-white transition-colors"
                >
                  View Client Cards ↓
                </a>
              </div>
            </div>

            {/* Global Operations Live Widget */}
            <div className="lg:col-span-5">
              <div className="rounded-3xl border border-orbit-cyan/20 bg-orbit-bg-primary/80 p-5 shadow-2xl backdrop-blur-md">
                <div className="mb-4 flex items-center justify-between border-b border-orbit-border pb-3">
                  <div className="flex items-center gap-2">
                    <span className="relative flex h-2 w-2">
                      <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-orbit-green opacity-75"></span>
                      <span className="relative inline-flex h-2 w-2 rounded-full bg-orbit-green"></span>
                    </span>
                    <span className="font-mono text-xs font-bold text-slate-700 dark:text-slate-300">GLOBAL_OPERATIONS_CENTER</span>
                  </div>
                  <span className="text-[10px] text-slate-500 font-mono">LIVE TELEMETRY</span>
                </div>

                <div className="space-y-2">
                  {PROJECTS.map((p) => (
                    <button
                      key={p.id}
                      onClick={() => setActiveProject(p)}
                      className={`w-full flex justify-between items-center p-2.5 rounded-xl border text-left font-mono text-xs transition-all duration-300 ${
                        activeProject.id === p.id
                          ? "border-orbit-cyan/30 bg-orbit-cyan/10"
                          : "border-transparent bg-slate-950/20 hover:bg-slate-950/40"
                      }`}
                    >
                      <span className="font-bold text-slate-800 dark:text-slate-200">{p.client}</span>
                      <span className="text-slate-500 text-[10px]">{p.sitesCount} Sites · {p.devices} Dev</span>
                      <span className={`font-bold ${p.savings.startsWith("↓") ? "text-orbit-green" : "text-orbit-orange"}`}>
                        {p.savings}
                      </span>
                    </button>
                  ))}
                  <div className="mt-4 p-3 bg-orbit-cyan/5 border border-orbit-cyan/15 rounded-xl font-mono text-[11px] text-orbit-cyan text-center">
                    Consolidated: 469+ sites · 3,233+ devices · −16% average savings
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Global Statistics Grid */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
          {[
            { value: "469+", label: "Centralized Connected Sites", sub: "Centralized VPN Nodes" },
            { value: "3,233+", label: "Deployed Devices", sub: "Meters, Sensors & Gateways" },
            { value: "570+", label: "Active Control Systems", sub: "Centralized Overrides" },
            { value: "6 Mega", label: "Enterprise Reference Clients", sub: "Market Leaders in Tunisia" }
          ].map((stat, i) => (
            <SpotlightCard key={i} glowColor="rgba(0, 212, 255, 0.15)">
              <div className="text-center space-y-1 py-2">
                <span className="font-mono text-[10px] text-slate-500 uppercase tracking-widest block">{stat.label}</span>
                <span className="font-mono text-3xl font-extrabold text-slate-900 dark:text-white block">{stat.value}</span>
                <p className="text-[9px] text-slate-600 font-mono">{stat.sub}</p>
              </div>
            </SpotlightCard>
          ))}
        </div>

        {/* Dynamic Telemetry Dashboard Grid */}
        <div id="projects" className="scroll-margin-top-[120px] rounded-3xl border border-orbit-border bg-orbit-bg-primary overflow-hidden shadow-2xl">
          <div className="border-b border-orbit-border/60 bg-orbit-bg-deep px-6 py-4 flex justify-between items-center">
            <span className="font-mono text-xs font-bold text-slate-700 dark:text-slate-300">ENTERPRISE CENTRALIZED SCADA DECK</span>
            <div className="flex gap-2">
              {PROJECTS.map((p) => (
                <button
                  key={p.id}
                  onClick={() => setActiveProject(p)}
                  className={`px-3 py-1 rounded-full font-mono text-[9px] font-bold border transition-colors ${
                    activeProject.id === p.id
                      ? "border-orbit-cyan bg-orbit-cyan/10 text-orbit-cyan"
                      : "border-orbit-border bg-orbit-bg-deep/40 text-slate-600 dark:text-slate-400 hover:text-slate-800 dark:text-slate-200"
                  }`}
                >
                  {p.client.split(" ")[0]}
                </button>
              ))}
            </div>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-12">
            
            {/* Interactive Map (7 cols) */}
            <div className="lg:col-span-7 p-6 border-b border-orbit-border lg:border-b-0 lg:border-r border-orbit-border/60 flex flex-col justify-between space-y-6 bg-slate-950/20">
              <div className="flex justify-between items-center">
                <h3 className="font-mono text-xs font-bold text-slate-600 dark:text-slate-400 uppercase tracking-widest">
                  GEOGRAPHIC NODE DISTRIBUTIONS (TUNISIA)
                </h3>
                <span className="font-mono text-[10px] text-slate-500 uppercase">Interactive Network Map</span>
              </div>

              {/* Dynamic Interactive SVG Map of Tunisia */}
              <div className="relative w-full aspect-[4/5] max-w-[380px] mx-auto rounded-2xl bg-orbit-bg-deep/60 border border-slate-900 overflow-hidden flex items-center justify-center p-4">
                
                {/* Background Grid inside Map */}
                <div className="absolute inset-0 bg-[radial-gradient(#00d4ff_0.5px,transparent_0.5px)] [background-size:16px_16px] opacity-10" />

                {/* Tunisian Outline SVG Mock */}
                <svg viewBox="0 0 240 520" className="w-full h-full text-slate-800" fill="none" stroke="currentColor" strokeWidth="1.5">
                  {/* Bizerte & North Cap */}
                  <path d="M100 20 L125 15 L140 30 L160 50 L150 90 L165 110 L155 125 L165 140 L180 145 L200 170 L210 200 L200 215 L225 205 L220 220 L195 210" strokeDasharray="3 3" />
                  {/* Sahel & Gulf of Hammamet */}
                  <path d="M195 210 L198 220 L210 225 L220 205 L222 220 L210 240 L190 280 L185 300 L200 305 L190 320" strokeDasharray="3 3" />
                  {/* Sfax & Gulf of Gabes */}
                  <path d="M190 320 L170 340 L165 370 L190 360 L200 375 L180 395 L165 385" strokeDasharray="3 3" />
                  {/* Djerba & South */}
                  <path d="M165 385 L185 410 L210 420 L200 440 L215 480 L195 510 L120 480 L100 450 L110 380 L80 340 L30 330 L20 180 L70 120 L95 60 L100 20" stroke="rgba(255, 255, 255, 0.08)" strokeWidth="2" fill="rgba(0, 212, 255, 0.02)" />

                  {/* Pulsing Active Hotspots for Deployed Sites */}
                  <AnimatePresence>
                    {activeProject.sites.map((site, index) => (
                      <g key={site.name + index}>
                        {/* Interactive hotspot anchor point */}
                        <motion.circle
                          cx={site.lngX}
                          cy={site.latY}
                          r="12"
                          fill={activeProject.color}
                          className="opacity-15 cursor-pointer"
                          initial={{ scale: 0 }}
                          animate={{ scale: [1, 1.6, 1], opacity: [0.15, 0.4, 0.15] }}
                          transition={{ repeat: Infinity, duration: 2.5, delay: index * 0.3 }}
                        />
                        <circle
                          cx={site.lngX}
                          cy={site.latY}
                          r="4.5"
                          fill={activeProject.color}
                          className="cursor-pointer"
                        />
                      </g>
                    ))}
                  </AnimatePresence>
                </svg>

                {/* Localized Floating Map Tooltip */}
                <div className="absolute bottom-4 left-4 right-4 bg-orbit-bg-deep/95 border border-slate-800 rounded-xl p-3 text-[10px] font-mono text-slate-600 dark:text-slate-400 space-y-1">
                  <div className="font-bold text-slate-800 dark:text-slate-200 uppercase tracking-widest flex items-center gap-1.5">
                    <span className="h-1.5 w-1.5 rounded-full" style={{ backgroundColor: activeProject.color }} />
                    {activeProject.client} Node Footprint
                  </div>
                  <div>Sites Deployed: {activeProject.sites.length} Active geographic markers</div>
                  <div className="text-slate-500">Highlighting Sfax, Monastir, Cap-Bon, Tunis, Bousalem, Tozeur networks.</div>
                </div>
              </div>
            </div>

            {/* Diagnostic Control Console (5 cols) */}
            <div className="lg:col-span-5 p-6 bg-orbit-bg-deep/30 flex flex-col justify-between space-y-6">
              <div className="space-y-6">
                <div>
                  <h3 className="font-mono text-xs font-bold text-slate-600 dark:text-slate-400 uppercase tracking-widest mb-4">
                    CENTRALIZED DEPLOYMENT PARAMETERS
                  </h3>
                  
                  <div className="rounded-2xl border border-orbit-border bg-orbit-bg-deep p-5 space-y-4">
                    <div className="flex justify-between items-center border-b border-orbit-border/60 pb-2">
                      <h4 className="font-mono text-sm font-extrabold text-slate-900 dark:text-white flex items-center gap-2">
                        <span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: activeProject.color }} />
                        {activeProject.client}
                      </h4>
                      <span className="font-mono text-[9px] uppercase text-slate-500 font-bold px-2 py-0.5 rounded border border-slate-800">
                        {activeProject.sector}
                      </span>
                    </div>

                    <div className="space-y-3 font-mono text-[11px] text-slate-600 dark:text-slate-400">
                      <div className="flex justify-between">
                        <span>Centralized Network Size:</span>
                        <span className="text-slate-900 dark:text-white font-bold">{activeProject.sitesCount} {activeProject.siteType}</span>
                      </div>
                      <div className="flex justify-between">
                        <span>Deployed Modbus/OPC-UA Devices:</span>
                        <span className="text-orbit-cyan font-bold">{activeProject.devices} Devices</span>
                      </div>
                      <div className="flex justify-between">
                        <span>Connected Edge Engines:</span>
                        <span className="text-orbit-purple font-bold">{activeProject.systems} Gateways</span>
                      </div>
                      <div className="flex justify-between">
                        <span>Hardware Control Layer:</span>
                        <span className="text-slate-800 dark:text-slate-200 font-bold">{activeProject.sysType}</span>
                      </div>
                      <div className="flex justify-between">
                        <span>Verified Audited Cost Reductions:</span>
                        <span className="text-orbit-green font-bold">{activeProject.savings}</span>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Core Features list for active client */}
                <div className="space-y-3">
                  <h4 className="font-mono text-xs font-bold text-slate-600 dark:text-slate-400 uppercase tracking-widest">
                    ACTIVE PLATFORM MODULES
                  </h4>
                  <div className="grid gap-2">
                    {activeProject.features.map((f, i) => (
                      <div key={i} className="flex gap-2.5 items-center font-mono text-[10px] text-slate-700 dark:text-slate-300 bg-orbit-bg-deep border border-slate-900 p-2.5 rounded-xl">
                        <CheckCircle2 className="h-3.5 w-3.5 text-orbit-cyan shrink-0" />
                        <span>{f}</span>
                      </div>
                    ))}
                  </div>
                </div>

                {/* Active Alerts in network */}
                {activeProject.status === "WARNING" && (
                  <div className="rounded-xl border border-orange-500/15 bg-orange-950/15 p-3 flex gap-2 items-start text-xs text-orange-300 font-mono">
                    <span className="h-1.5 w-1.5 rounded-full bg-orbit-orange shrink-0 mt-1 animate-pulse" />
                    <span>Warning: {activeProject.statusText}</span>
                  </div>
                )}
              </div>

              <div className="rounded-2xl border border-orbit-border bg-orbit-bg-deep p-4 font-mono text-[10px] text-slate-500 flex gap-2.5 items-center">
                <Shield className="h-4.5 w-4.5 shrink-0 text-orbit-purple animate-pulse" />
                <span>Bank-grade secure VPN tunnels execute outbound-only MQTT TLS 1.3 telemetry synchronization in &lt;12ms.</span>
              </div>
            </div>

          </div>
        </div>

        {/* Case Study Featurette - Délice Network */}
        <section className="rounded-3xl border border-orbit-border bg-gradient-to-br from-orbit-bg-primary to-orbit-bg-secondary p-8 md:p-12 relative overflow-hidden shadow-2xl">
          <div className="absolute top-0 right-0 w-32 h-32 bg-orbit-purple/10 blur-2xl rounded-full" />
          
          <div className="grid gap-8 md:grid-cols-2 items-center">
            <div className="space-y-5">
              <div className="inline-flex rounded-full border border-orbit-green/20 bg-orbit-green/5 px-3 py-1 font-mono text-[9px] font-bold uppercase tracking-widest text-orbit-green">
                Case Study · Centralized Industrial Network
              </div>
              <h3 className="text-2xl font-bold tracking-tight text-slate-900 dark:text-white md:text-4xl">
                Délice Holding <br />
                <span className="bg-gradient-to-r from-orbit-cyan to-orbit-purple bg-clip-text text-transparent">7 Production Sites, One Console</span>
              </h3>
              <div className="flex gap-4 font-mono text-xs text-slate-600 dark:text-slate-400">
                <span>Sector: Food & Beverage</span>
                <span>·</span>
                <span>Tunisia</span>
              </div>
              
              <div className="space-y-3 font-sans text-xs text-slate-600 dark:text-slate-400 leading-relaxed">
                <p>
                  Centralized energy sub-metering and automated cooling system override control deployed across the entire Délice Holding factory network in Tunisia.
                </p>
                
                <div className="pt-2 grid grid-cols-2 gap-3">
                  <div className="p-3 bg-slate-900/50 border border-slate-800 rounded-xl">
                    <span className="font-mono font-bold text-slate-900 dark:text-white block">Phase 1</span>
                    <span className="text-[10px] text-slate-500">Continuous telemetry and thermal sensors per refrigeration compressor unit linked to SCADA supervision.</span>
                  </div>
                  <div className="p-3 bg-slate-900/50 border border-slate-800 rounded-xl">
                    <span className="font-mono font-bold text-orbit-green block">Phase 2</span>
                    <span className="text-[10px] text-slate-500">Chillers setback calendar overnight, preventing excess baseline cooling during off-production hours.</span>
                  </div>
                </div>
              </div>
            </div>

            {/* Stat Callout */}
            <div className="rounded-2xl border border-slate-800 bg-orbit-bg-deep/80 p-6 text-center space-y-4">
              <div className="text-xs font-mono font-bold text-orbit-cyan uppercase tracking-wider">Verified Audited Impact</div>
              <div className="text-4xl md:text-5xl font-black text-slate-900 dark:text-white">-28.4% cooling loads</div>
              <p className="text-xs text-slate-500 max-w-[280px] mx-auto leading-relaxed">
                Energy setbacks locked automatically during summer seasons across 7 production facilities.
              </p>
              <div className="pt-2">
                <a
                  href="/contact"
                  className="inline-flex items-center gap-1.5 font-mono text-xs text-orbit-cyan hover:underline"
                >
                  Request Similar Multi-Site Audit <ChevronRight className="h-3.5 w-3.5" />
                </a>
              </div>
            </div>
          </div>
        </section>

        {/* Detailed Solutions Grids */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-8 pt-8">
          <div className="space-y-4">
            <h2 className="text-2xl font-bold font-mono text-slate-800 dark:text-slate-200">Global Standardized OEE Benchmarks</h2>
            <p className="text-sm leading-relaxed text-slate-600 dark:text-slate-400">
              Standardize efficiency data across all facilities. Adjust metrics to compensate for localized holiday schedules, raw material latency factors, and energy tariffs to generate authentic comparative insights across your industrial sites in Tunis, Sfax, Monastir, and Bizerte.
            </p>
          </div>
          <div className="space-y-4">
            <h2 className="text-2xl font-bold font-mono text-slate-800 dark:text-slate-200">Consolidated ESG Ledgers</h2>
            <p className="text-sm leading-relaxed text-slate-600 dark:text-slate-400">
              Synthesize operational parameters into corporate carbon indices, mapping localized environmental milestones into a unified, secure database ledger. Direct one-click compliance reports exportable for EU CSRD, TCFD, and GHG Protocol standards.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

