import { useState, useEffect, useRef } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import { useLanguage } from "@/contexts/LanguageContext";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useScrollAnimation } from "@/hooks/useScrollAnimation";
import Chatbot from "@/components/Chatbot";
import SEO from "@/components/SEO";
import { ArrowRight, Settings, ShieldCheck, Gauge, ArrowUpFromLine, Layers, ChevronDown, ChevronUp, X, Download, Calendar, Tag, Hash, Info } from "lucide-react";

// Import product images
import pneumaticPds from "@/assets/products/pneumatic-pds.png";
import pneumaticHd from "@/assets/products/pneumatic-hd.jpg";
import pneumaticPlds from "@/assets/products/pls1-series.png";
import pneumaticMplds from "@/assets/products/mpld.png";
import electricalItq from "@/assets/products/electrical-itq.jpg";
import electricalIql from "@/assets/products/electrical-iql.jpg";
import electricalItl from "@/assets/products/electrical-itl.jpg";
import electricalItm from "@/assets/products/electrical-itm.png";
import mechanicalBevel from "@/assets/products/mechanical-bevel.png";
import mechanicalWorm from "@/assets/products/worm-gearboxes.png";
import accessoriesIt from "@/assets/products/accessories-it.png";
import accessoriesHandwheels from "@/assets/products/handwheels.png";
import hydraulicActuator from "@/assets/products/hydralic.png"; 
import heroVideo from "@/assets/susini tork.mp4";

/* ===========================================================
   INTERFACE UPDATE
   =========================================================== */
interface Product {
  id: string;
  name: string;
  type: string;
  image: string;
  models: string[];
  description: string;
  torque?: string;
  thrust?: string;
  features?: string[];
  applications?: string[];
  certifications?: string[];
  seriesLinks?: { label: string; path: string }[];
}

/* ===========================================================
   MODEL DETAILS INTERFACE
   =========================================================== */
interface ModelDetails {
  modelNumber: string;
  productName: string;
  specifications: {
    torque?: string;
    thrust?: string;
    pressure?: string;
    temperature?: string;
    speed?: string;
    weight?: string;
    [key: string]: string | undefined;
  };
  description: string;
  features: string[];
  datasheetUrl?: string;
  cadUrl?: string;
}

/* ===========================================================
   MODEL DETAILS MODAL COMPONENT
   =========================================================== */
const ModelDetailsModal = ({
  isOpen,
  onClose,
  details
}: {
  isOpen: boolean;
  onClose: () => void;
  details: ModelDetails | null;
}) => {
  if (!isOpen || !details) return null;

  return (
   <div className="fixed inset-0 z-50 flex items-center justify-center p-0 sm:p-6 bg-slate-950/90 backdrop-blur-md">
  <div className="relative w-full max-w-5xl max-h-[100vh] sm:max-h-[92vh] overflow-hidden bg-white shadow-[0_0_50px_-12px_rgba(185,28,28,0.3)] animate-in fade-in zoom-in-98 duration-300 flex flex-col border border-red-900/10">
    
    {/* Professional Header: Industrial Red Panel */}
    <div className="flex items-center justify-between p-6 bg-red-700 text-white relative">
      <div className="flex items-center gap-5">
        <div className="hidden sm:flex p-3 bg-white/10 border border-white/20 backdrop-blur-md rounded-sm">
          <Info className="w-6 h-6" />
        </div>
        <div>
          <span className="text-[10px] font-black uppercase tracking-[0.3em] opacity-80 mb-1 block">Engineering Data Sheet</span>
          <h2 className="text-3xl font-light tracking-tight flex items-center gap-3">
            {details.productName} 
            <span className="h-6 w-[1px] bg-white/30 hidden sm:block"></span>
            <span className="text-sm font-mono bg-black/20 px-3 py-1 rounded-sm border border-white/10 uppercase">
              ID: {details.modelNumber}
            </span>
          </h2>
        </div>
      </div>
      
      <button
        onClick={onClose}
        className="group flex items-center gap-2 p-2 hover:bg-white/10 transition-all border border-transparent hover:border-white/20"
      >
        <span className="text-[10px] uppercase font-bold tracking-widest hidden sm:block">Close</span>
        <X className="w-6 h-6" />
      </button>
    </div>

    {/* Main Scrollable Content */}
    <div className="flex-1 overflow-y-auto p-6 sm:p-10 space-y-12">
      
      {/* Description Section: Clean & Focused */}
      <section className="max-w-3xl">
        <h3 className="text-[11px] font-black uppercase tracking-widest text-red-700 mb-4 flex items-center gap-2">
          <div className="w-8 h-[2px] bg-red-700"></div> Product Overview
        </h3>
        <p className="text-xl text-slate-600 font-light leading-relaxed italic">
          "{details.description}"
        </p>
      </section>

      {/* Specifications Grid: Precision Thin-Border Layout */}
      {Object.keys(details.specifications).length > 0 && (
        <section>
          <div className="flex items-center gap-3 mb-6">
            <Settings className="w-5 h-5 text-red-700" />
            <h3 className="text-[11px] font-black uppercase tracking-widest text-slate-900">Technical Parameters</h3>
            <div className="flex-1 h-[1px] bg-slate-100"></div>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-3 gap-px bg-slate-200 border border-slate-200 shadow-sm">
            {Object.entries(details.specifications).map(([key, value], idx) => (
              value && (
                <div key={idx} className="bg-white p-6 hover:bg-red-50/50 transition-colors">
                  <div className="text-[10px] font-bold text-slate-400 uppercase tracking-tighter mb-2">
                    {key.replace(/_/g, ' ')}
                  </div>
                  <div className="text-lg font-bold text-red-700">
                    {value}
                  </div>
                </div>
              )
            ))}
          </div>
        </section>
      )}

      {/* Key Features: Two Column Checklist */}
      {details.features.length > 0 && (
        <section>
          <h3 className="text-[11px] font-black uppercase tracking-widest text-slate-900 mb-6 flex items-center gap-2">
            <div className="w-8 h-[2px] bg-red-700"></div> Key Performance Features
          </h3>
          <ul className="grid grid-cols-1 md:grid-cols-2 gap-x-12 gap-y-4">
            {details.features.map((feature, idx) => (
              <li key={idx} className="flex items-start gap-4 p-3 border-l-2 border-slate-100 hover:border-red-600 hover:bg-slate-50 transition-all group">
                <span className="text-red-600 font-bold group-hover:scale-125 transition-transform">0{idx + 1}</span>
                <span className="text-slate-700 text-sm leading-snug">{feature}</span>
              </li>
            ))}
          </ul>
        </section>
      )}

      {/* Action Footer: Fixed at bottom for high visibility */}
      <div className="flex flex-col sm:flex-row gap-4 pt-10 border-t border-slate-100">
        <Button
          size="lg"
          className="flex-1 bg-red-700 hover:bg-red-800 text-white rounded-none py-8 text-sm uppercase tracking-[0.2em] font-bold shadow-lg shadow-red-900/20 transition-all"
          onClick={() => window.open(`/contact?model=${details.modelNumber}`, '_blank')}
        >
          <Calendar className="w-5 h-5 mr-3" />
          Request Quotation
        </Button>
        
        <Button
          size="lg"
          variant="outline"
          className="flex-1 border-slate-200 text-slate-500 hover:bg-slate-50 rounded-none py-8 text-sm uppercase tracking-[0.2em] font-bold"
          onClick={onClose}
        >
          Close Specification
        </Button>
      </div>
    </div>
  </div>
</div>
  );
};

/* ===========================================================
   HD ACTUATOR – SERIES WISE MODELS
=========================================================== */
const hdSeriesModels = [
  {
    series: "A1 Series",
    models: ["A1-10", "A1-12", "A1-16", "A1-20"],
  },
  {
    series: "01 Series",
    models: ["01-10", "01-12", "01-16", "01-18", "01-20", "01-25"],
  },
  {
    series: "02 Series",
    models: ["02-20", "02-23", "02-25", "02-28", "02-30", "02-35", "02-38"],
  },
  {
    series: "03 Series",
    models: ["03-35", "03-38", "03-43", "03-48"],
  },
  {
    series: "04 Series",
    models: ["04-43", "04-48", "04-53", "04-58", "04-63"],
  },
  {
    series: "05 Series",
    models: ["05-43", "05-48", "05-53", "05-58", "05-63", "05-73"],
  },
  {
    series: "06 Series",
    models: ["06-53", "06-58", "06-63", "06-68", "06-73", "06-78", "06-83", "06-88"],
  },
  {
    series: "07 Series",
    models: ["07-73", "07-78", "07-83", "07-88", "07-93"],
  },
];

/* ===========================================================
   PRODUCT DATA
   =========================================================== */
const pneumaticProducts: Product[] = [
  {
    id: "pds-rotary",
    name: "PDS Actuator (Rotary)",
    type: "Pneumatic",
    image: pneumaticPds,
    models: ["PDS 45", "PDS 50", "PDS 55", "PDS 70", "PDS 75", "PDS 85", "PDS 100", "PDS 125", "PDS 160", "PDS 200"],
    description:
      "We specialize in providing the best & reliable flow control solutions in the most challenging environments. PDS series Pneumatic Actuators are designed using Scotch-Yoke technology for superior torque.",
    torque: "5 Nm - 5,000 Nm", 
    features: [
      "Scotch-Yoke mechanism for high break-out torque",
      "Hard anodized aluminum body for corrosion resistance",
      "Operating pressure: 3.5 - 8 Bar",
      "Temperature range: -20°C to +80°C",
      "Adjustable travel stops ±5°",
      "Pre-compressed spring packages for safety",
      "ISO 5211, NAMUR & VDI/VDE 3845 compliant",
      "SIL 3 Capable (IEC 61508)"
    ],
    applications: ["Oil & Gas", "Chemical Processing", "Power Plants", "Water Treatment", "Food & Beverage"],
    certifications: ["ATEX", "SIL 3", "PED", "ISO 9001", "IP67"],
    seriesLinks: [
      { label: "PD Series (Double Acting)", path: "/products/pds-rotary/pd-series" },
      { label: "PS Series (Single Acting)", path: "/products/pds-rotary/ps-series" }
    ]
  },
  {
    id: "hd-rotary",
    name: "HD Actuator (Rotary)",
    type: "Pneumatic",
    image: pneumaticHd,
   models: [
  "02-20",
  "02-25",
  "02-30",
  "02-35",
  "03-35",
  "03-38",
  "03-43",
  "04-43",
  "04-48",
  "04-53",
  "05-53",
  "05-58",
  "05-63",
  "06-63",
  "06-68",
  "06-73"
],
    description:
      "Our flagship heavy-duty scotch yoke actuators deliver exceptional torque for the most demanding valve automation applications.",
    torque: "200 Nm - 120,867 Nm",
    features: [
      "High torque capacity up to 120,867 Nm",
      "Extended service life (>2 million cycles)",
      "Operating pressure: 2.8 - 10 bar",
      "Spring return or double acting configurations",
      "Custom bracket designs for any valve",
      "Ideal for ball, butterfly & plug valves",
      "ATEX/IECEx certified for hazardous areas",
      "Corrosion-resistant coating options"
    ],
    applications: ["Oil & Gas", "Power Generation", "Petrochemical", "Offshore FPSO"],
    certifications: ["ISO 5211", "NAMUR", "ATEX", "API 609"],
    seriesLinks: [
       { label: "ISD Series", path: "/products/hd-rotary/isd-series" },
       { label: "ICD Series", path: "/products/hd-rotary/icd-series" },
       { label: "ISR Series", path: "/products/hd-rotary/isr-series" },
       { label: "ICR Series", path: "/products/hd-rotary/icr-series" }
    ]
  },
  {
    id: "plds-linear",
    name: "PLDS Actuator (Linear)",
    type: "Pneumatic",
    image: pneumaticPlds,
    models: ["PLDS-100", "PLDS-125", "PLDS-160", "PLDS-200", "PLDS-250", "PLDS-300"],
    description:
      "The PLDS series of Pneumatic Linear Double Acting Cylinders are meticulously designed to provide superior performance for tasks requiring precise linear motion control.",
    thrust: "1 KN - 500 KN",
    features: [
      "Double Acting & Spring Return configurations",
      "Bore sizes from 100mm to 980mm",
      "Operating Pressure: 2.8 to 10 Bar",
      "High thrust capability for Gate & Globe valves",
      "Standard Temp: -20°C to +80°C (Options up to +100°C)",
      "Hard chrome plated piston rod for durability",
      "Manual override options: Hydraulic or Gearbox",
      "Field reversible action (Fail Open/Close)"
    ],
    applications: ["Linear Valve Automation (Gate/Globe)", "Dampers", "Material Handling", "Power Generation"],
    certifications: ["SIL 3", "ATEX", "PED", "IP66/IP67"],
    seriesLinks: [
       { label: "PLD Series", path: "/products/plds-linear/pld-series" },
       { label: "PLS Series", path: "/products/plds-linear/pls-series" }
    ]
  },
  {
    id: "mplds-linear",
    name: "MPLDS Actuator (Linear)",
    type: "Pneumatic",
    image: pneumaticMplds,
    models: ["50mm", "75mm", "100mm", "150mm", "200mm", "250mm"],
    description:
      "The MPLDS series of Micro Pneumatic Double Acting Linear Cylinders are designed for precision and compact applications where space is limited but performance cannot be compromised.",
    thrust: "1 KN - 50 KN",
    features: [
      "Micro cylinder design for tight spaces",
      "Double Acting mechanism for controlled motion",
      "Operating Pressure: 2.1 to 6.2 Bar",
      "Standard Temperature: -10°C to +60°C",
      "IP66 Protection against dust and water",
      "High-quality construction for long service life",
      "Ideal for fine automation systems",
      "Modular design for easy maintenance"
    ],
    applications: ["Fine Automation", "Small-scale Machinery", "Linear Valve Control", "Material Handling"],
    certifications: ["IP66", "ISO 9001", "CE"],
    seriesLinks: [
      { label: "MPLD Series", path: "/products/mplds-linear/mpld-series" },
      { label: "MPLS Series", path: "/products/mplds-linear/mpls-series" }
    ]
  },
];

const electricalProducts: Product[] = [
  {
    id: "itq-rotary",
    name: "ITQ SERIES (Rotary)",
    type: "Electrical",
    image: electricalItq,
    models: ["ITQ 0020 (25Nm)", "ITQ 0040 (40Nm)", "ITQ 0080 (80Nm)"],
    description:
      "A compact and robust quarter-turn electric actuator designed for the automation of ball, butterfly, and plug valves. Features a self-locking double worm gear drive and advanced control options.",
    torque: "25 Nm - 9,000 Nm",
    features: [
      "Hard anodized aluminum housing with powder coating",
      "Self-locking double worm gearing (no brake required)",
      "Auto-declutching manual override handwheel",
      "Weatherproof IP67 enclosure (IP68 optional)",
      "High starting torque induction motor",
      "Mechanical torque sensing system",
      "Modulating control options (4-20mA, 0-10V)",
      "ISO 5211 mounting base for easy installation"
    ],
    applications: ["Water Treatment", "Chemical Processing", "HVAC Automation", "Power Plants", "Oil & Gas"],
    certifications: ["IP67", "IP68", "ATEX", "ISO 9001", "CE"]
  },
  {
    id: "iql-linear",
    name: "IQL SERIES (Linear)",
    type: "Electrical",
    image: electricalIql,
    models: ["IQL 04", "IQL 06", "IQL 08", "IQL 10", "IQL 12", "IQL 20", "IQL 25"],
    description:
      "A robust linear electric actuator designed for precise modulating control of globe and control valves. Features intelligent positioning, fail-safe options, and a high thrust capacity.",
    thrust: "4 KN - 25 KN",
    features: [
      "Wide thrust range from 4 KN to 25 KN",
      "Stroke range: 40mm to 100mm",
      "Modulating control (4-20mA / 0-10V)",
      "Weatherproof IP66 enclosure (IP68 optional)",
      "Auto-declutching manual override handwheel",
      "Digital display for position monitoring",
      "Mechanical thrust sensing system for overload protection",
      "Battery backup for fail-safe operation"
    ],
    applications: ["Globe Control Valves", "Gate Valves", "Damper Automation", "Power Plants", "Water Treatment"],
    certifications: ["CE", "IP66", "IP68", "Ex d II B T4", "ISO 9001"]
  },
  {
    id: "itl-linear",
    name: "ITL SERIES (Linear)",
    type: "Electrical",
    image: electricalItl,
    models: ["ITL01", "ITL02", "ITL04", "ITL06"],
    description:
      "A compact and powerful linear electric actuator featuring a 100% duty cycle motor. Designed for high-frequency modulating control in sophisticated automation systems.",
    thrust: "1 KN - 6 KN",
    features: [
      "100% Duty Cycle (Continuous Duty) Motor",
      "Thrust range: 1 KN to 6 KN",
      "Stroke range: 20mm to 50mm",
      "Compact design with hard anodized aluminum housing",
      "Input/Output Isolation for signal safety",
      "Built-in manual override with storable handwheel",
      "Wide voltage support (AC 100-240V, DC 24V)",
      "High resolution position control (4-20mA / 0-10V)"
    ],
    applications: ["Control Valves (2-way/3-way)", "Industrial Dampers", "Process Automation", "High-Frequency Modulation"],
    certifications: ["IP67", "CE", "ISO 9001"]
  },
  {
    id: "itm-multiturn",
    name: "ITM SERIES (Multiturn)",
    type: "Electrical",
    image: electricalItm,
    models: ["ITM 0180", "ITM 0450", "ITM 0750", "ITM 1800", "ITM 3000"],
    description:
      "A high-efficiency multi-turn electric actuator designed for gate and globe valves. Features a digitalized torque sensing system and robust IP68 watertight enclosure.",
    torque: "177 Nm - 3,000 Nm", 
    features: [
      "Digitalized torque sensing system (30-100% adjustable)",
      "Watertight IP68 enclosure (10m for 100 hours)",
      "High efficiency motor with thermal protection",
      "Top-mounted handwheel for easy manual operation",
      "Battery backup for position detecting system",
      "Fieldbus communication (Profibus, CANopen)",
      "Explosion-proof Ex d II C T4 option available",
      "Non-intrusive setting via remote control"
    ],
    applications: ["Gate Valves", "Globe Valves", "Sluice Gates", "Penstocks", "Power Plants"],
    certifications: ["IP68", "Ex d II C T4", "CE", "ISO 9001"]
  },
];

const mechanicalProducts: Product[] = [
  {
    id: "bevel-gear",
    name: "BEVEL GEAR ACTUATORS",
    type: "Mechanical",
    image: mechanicalBevel,
    models: [
      "MAB-075 (2.5:1)", "MAB-100 (3.0:1)", "MAB-125 (3.5:1)",
      "MAB-150 (3.75:1)", "MAB-200 (4.0:1)", "MAB-300 (5.0:1)",
      "MAB-350 (5.5:1)", "MAB-400 (6.0:1)", "MAB-500 (6.5:1)"
    ],
    description:
      "Precision bevel gear actuator for manual multi-turn valve operation (Gate/Globe). Designed for high efficiency, smooth transmission, and heavy-duty industrial applications.",
    torque: "250 Nm - 18,000 Nm",
    thrust: "75 KN - 2,500 KN",
    features: [
      "Ductile Iron housing for superior strength",
      "High tensile Aluminum Bronze stem nut",
      "Heavy-duty roller bearings for high thrust loads",
      "Totally enclosed watertight IP67 design (IP68 optional)",
      "Top-entry replaceable stem nut",
      "Operating Temp: -20°C to +80°C (Options: -45°C to +120°C)",
      "Machine cut, heat-treated gears for optimum operation",
      "Motorizable options with ISO mounting flanges"
    ],
    applications: ["Gate Valves", "Globe Valves", "Sluice Gates", "Penstocks", "Power Plants", "Oil & Gas"],
    certifications: ["IP67", "IP68", "ISO 5210"],
    seriesLinks: [
      { label: "MAB Series", path: "/products/bevel-gear/mab-series" }
    ]
  },
  {
    id: "worm-gear",
    name: "WORM GEAR ACTUATORS (MAW Series)",
    type: "Mechanical",
    image: mechanicalWorm,
    models: ["MAW-012", "MAW-025", "MAW-045", "MAW-080", "MAW-100", "MAW-200", "MAW-300", "MAW-400"],
    description:
      "A rugged, industrial-grade worm gear actuator designed for manual quarter-turn valve operations. Features a ductile iron housing and high-performance gearing for smooth, reliable torque transmission.",
    torque: "100 Nm - 32,000 Nm",
    features: [
      "Rugged Ductile Iron housing for high strength",
      "Torque output range: 100 Nm to 32,000 Nm",
      "Self-locking worm gear design for safety",
      "IP67 Weatherproof protection (IP68 optional)",
      "Operating Temp: -20°C to +85°C (Options: -45°C to +120°C)",
      "Adjustable mechanical stoppers (±5°)",
      "High-performance roller bearings for smooth operation",
      "Epoxy/PU coating for corrosion resistance"
    ],
    applications: ["Ball Valves", "Butterfly Valves", "Plug Valves", "Dampers", "HVAC Systems", "Water Works"],
    certifications: ["IP67", "IP68", "ISO 5211", "ISO 9001"],
    seriesLinks: [
      { label: "MAW Series", path: "/products/worm-gear/maw-series" },
      { label: "ITG Series", path: "/products/worm-gear/itg-series" },
      { label: "MTG Series", path: "/products/worm-gear/mtg-series" }
    ]
  },
];

const accessoryProducts: Product[] = [
  {
    id: "its-series",
    name: "ITS Series Components",
    type: "Accessories",
    image: accessoriesIt,
    models: ["ITS 100", "ITS 300", "ITS 500"],
    description:
      "Precision-engineered position monitoring switches for rotary actuators. Features robust weatherproof and explosion-proof housings with visual indicators for reliable valve status feedback.",
    features: [
      "Rugged aluminum or stainless steel housing options",
      "Visual dome indicator for 0°-90° position",
      "Weatherproof (IP67) and Explosion-proof (Ex d IIC T6) versions",
      "2-SPDT mechanical switches or proximity sensors",
      "NAMUR standard shaft for easy mounting",
      "Corrosion-resistant epoxy-polyester coating",
      "Wide operating temperature range (-20°C to +80°C)",
      "Multiple cable entry options (NPT, PF, M20)"
    ],
    applications: ["Chemical Plants", "Oil & Gas", "Water Treatment", "Power Generation", "Process Automation"],
    certifications: ["IP67", "IP68", "ATEX (Ex d IIC T6)", "IECEx", "CE"],
    seriesLinks: [
      { label: "View IT Series", path: "/products/it-series" }
    ]
  },
  {
    id: "handwheels",
    name: "Handwheels",
    type: "Accessories",
    image: accessoriesHandwheels,
    models: ["100mm - 500mm (Chain)", "200mm - 400mm (Cast)", "200mm - 1000mm (Fab)"],
    description:
      "Ergonomic manual override handwheels available in Casting, Fabricated, and Chain Wheel designs. Engineered for smooth operation and durability in harsh industrial environments.",
    features: [
      "Available in Casting, Fabricated, and Chain Wheel types",
      "Size range: 100mm to 1000mm (4\" to 40\")",
      "Epoxy or Powder coated finish (RAL 5015/3011)",
      "Stainless Steel chain options for corrosive areas",
      "Keyed, Pinned, or Squared drive connections",
      "Optional locking plates and visual indicators",
      "Rugged construction for high torque transmission"
    ],
    applications: ["Manual Valve Override", "Gearbox Operation", "High-Reach Valve Control (Chain Wheels)", "Industrial Automation"],
    certifications: ["ISO 9001", "ISO 12944-2 (Painting)"]
  },
];

const hydraulicProducts: Product[] = [
  {
    id: "hyd-rotary",
    name: "Electro-Hydraulic Rotary Actuator",
    type: "Hydraulic",
    image: hydraulicActuator,

    models: [
      "PANDA D10 – D130 (Low Pressure)",
      "PA D10 – D60 (High Pressure)"
    ],

    description:
      "Electro-hydraulic rotary actuators designed as a high-performance alternative to pneumatic and electric actuators. These compact units deliver very high torque density, fast response times, and near wear-free operation, making them ideal for severe-duty and hazardous area applications.",

    torque: "46 Nm – 10,000 Nm (Higher on request)",

    features: [
      "Electro-hydraulic compact actuator design",
      "Low pressure (PANDA) and high pressure (PA) variants",
      "Single acting (spring return – fail safe) or double acting",
      "Extremely high torque density with compact dimensions",
      "Near wear-free operation due to oil-lubricated components",
      "Fail-safe function via spring or hydraulic accumulator",
      "Adjustable stroke time via hydraulic throttle",
      "No gearbox – high efficiency, minimal power loss",
      "Block construction – no external piping required",
      "ISO 5211 & NAMUR mounting interface",
      "Suitable for continuous outdoor and marine environments"
    ],

    applications: [
      "Oil & Gas Onshore / Offshore",
      "Power Plants",
      "Water & Wastewater Treatment",
      "Chemical & Petrochemical Plants",
      "Steel & Heavy Industries",
      "Emergency Shut Down (ESD) Valves"
    ],

    certifications: [
      "ATEX (Zone 1 & 2)",
      "SIL 2 / SIL 3 (Configurable)",
      "Machinery Directive 2006/42/EC",
      "EN ISO 12100",
      "IP67 / IP68"
    ],

    seriesLinks: [
      {
        label: "PANDA Series – Low Pressure (up to 8 bar)",
        path: "/products/hydraulic-rotary/panda-series"
      },
      {
        label: "PA Series – High Pressure (up to 180 bar)",
        path: "/products/hydraulic-rotary/pa-series"
      }
    ]
  }
];

const allProducts = [
  ...pneumaticProducts,
  ...electricalProducts,
  ...mechanicalProducts,
   ...hydraulicProducts,
  ...accessoryProducts,
];

/* ===========================================================
   GET MODEL DETAILS FUNCTION
   =========================================================== */
const getModelDetails = (product: Product, modelNumber: string): ModelDetails => {
  // Default specifications based on product type
  const baseSpecs: ModelDetails['specifications'] = {
    model: modelNumber,
    type: product.type,
  };

  // Add product-specific specifications
  if (product.torque) baseSpecs.torque = product.torque;
  if (product.thrust) baseSpecs.thrust = product.thrust;
  
  // Add model-specific specifications based on model number
  switch (product.id) {
    case "pds-rotary":
      baseSpecs.pressure = "3.5 - 8 Bar";
      baseSpecs.temperature = "-20°C to +80°C";
      baseSpecs.weight = "Based on model size";
      break;
    case "hd-rotary":
      baseSpecs.pressure = "2.8 - 10 Bar";
      baseSpecs.temperature = "-20°C to +120°C";
      baseSpecs.cycles = ">2 million cycles";
      break;
    case "itq-rotary":
      baseSpecs.protection = "IP67 / IP68";
      baseSpecs.mounting = "ISO 5211";
      baseSpecs.control = "4-20mA / 0-10V";
      break;
    case "iql-linear":
      baseSpecs.stroke = "40mm - 100mm";
      baseSpecs.protection = "IP66 / IP68";
      baseSpecs.control = "Modulating";
      break;
    case "bevel-gear":
      baseSpecs.protection = "IP67 / IP68";
      baseSpecs.temperature = "-20°C to +80°C";
      baseSpecs.mounting = "ISO 5210";
      break;
    case "worm-gear":
      baseSpecs.protection = "IP67 / IP68";
      baseSpecs.temperature = "-20°C to +85°C";
      baseSpecs.mounting = "ISO 5211";
      break;
    case "hyd-rotary":
      baseSpecs.pressure = "8 - 180 Bar";
      baseSpecs.mounting = "ISO 5211 & NAMUR";
      baseSpecs.protection = "IP67 / IP68";
      break;
    default:
      baseSpecs.pressure = "Consult datasheet";
      baseSpecs.temperature = "Standard industrial range";
  }

  return {
    modelNumber,
    productName: product.name,
    specifications: baseSpecs,
    description: `${modelNumber} is part of the ${product.name} series. ${product.description}`,
    features: product.features || [],
    datasheetUrl: `/datasheets/${product.id}-${modelNumber.toLowerCase().replace(/\s+/g, '-')}.pdf`,
    cadUrl: `/cad/${product.id}-${modelNumber.toLowerCase().replace(/\s+/g, '-')}.step`,
  };
};

/* ===========================================================
   PRODUCT ROW
   =========================================================== */
const ProductRow = ({ product, index }: { product: Product; index: number }) => {
  const navigate = useNavigate();
  const { ref, isVisible } = useScrollAnimation(0.1);
  const isReversed = index % 2 === 1;
  const [showAllModels, setShowAllModels] = useState(false);
  const [activeHdSeries, setActiveHdSeries] = useState<string | null>(null);
  const [selectedModelDetails, setSelectedModelDetails] = useState<ModelDetails | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  
  // Determine how many models to show initially (max 6 for compact display)
  const initialModelCount = 6;
  const hasManyModels = product.models.length > initialModelCount;
  const displayModels = showAllModels 
    ? product.models 
    : product.models.slice(0, initialModelCount);

  const handleModelClick = (modelNumber: string) => {
    const details = getModelDetails(product, modelNumber);
    setSelectedModelDetails(details);
    setIsModalOpen(true);
  };

  return (
    <>
      <div
        id={product.id}
        ref={ref}
        className={`scroll-fade-in ${isVisible ? "visible" : ""} 
        relative z-0 py-12 md:py-24 px-4 md:px-12 border-b border-red-100/50 last:border-0 scroll-mt-24`}
      >
        <div
          className={`flex flex-col ${
            isReversed ? "lg:flex-row-reverse" : "lg:flex-row"
          } gap-12 lg:gap-20 items-center max-w-7xl mx-auto`}
        >
          {/* Product Image */}
          <div className="w-full lg:w-1/2 flex justify-center items-center">
            <img
              src={product.image}
              alt={product.name}
              className="w-full h-auto max-h-[300px] md:max-h-[500px] object-contain drop-shadow-2xl transform transition-transform duration-700 hover:scale-105"
            />
          </div>

          {/* Product Details - Right Column */}
          <div className="w-full lg:w-1/2 space-y-8 text-center lg:text-left">
            
            {/* HEADER SECTION */}
            <div className="space-y-4">
              <div className="flex justify-center lg:justify-start">
                <span className="inline-block px-4 py-1 bg-red-50 text-red-700 rounded-full text-xs font-bold uppercase tracking-wider border border-red-100">
                  {product.type}
                </span>
              </div>
              
              <h2 className="text-3xl md:text-5xl font-serif font-bold text-slate-900 leading-tight">
                {product.name}
              </h2>

              {/* Torque Spec */}
              {product.torque && (
                <div className="flex items-center justify-center lg:justify-start gap-2 text-red-700 font-bold text-lg md:text-xl">
                  <Gauge className="w-6 h-6" />
                  <span>Torque: {product.torque}</span>
                </div>
              )}

               {/* Thrust Spec */}
              {product.thrust && (
                <div className="flex items-center justify-center lg:justify-start gap-2 text-red-700 font-bold text-lg md:text-xl">
                  <ArrowUpFromLine className="w-6 h-6" />
                  <span>Thrust: {product.thrust}</span>
                </div>
              )}

              <p className="text-base md:text-lg text-slate-600 leading-relaxed font-light font-sans lg:border-l-4 lg:border-red-800/20 lg:pl-6">
                {product.description}
              </p>

              {/* NEW: SERIES SELECTION BUTTONS WITH PREMIUM RED DESIGN */}
              {product.seriesLinks && product.seriesLinks.length > 0 && (
                <div className="pt-4">
                   <h4 className="text-xs font-bold text-slate-400 uppercase tracking-widest mb-4 flex items-center justify-center lg:justify-start gap-2">
                      <Layers className="w-4 h-4 text-red-700" /> Select Series
                    </h4>
                   <div className="flex flex-wrap gap-3 justify-center lg:justify-start">
                      {product.seriesLinks.map((link, idx) => (
                        <button
                          key={idx}
                          onClick={() => navigate(link.path)}
                          className="group relative overflow-hidden rounded-full bg-gradient-to-r from-red-700 to-red-600 px-6 py-2.5 
                                     text-white font-medium text-sm shadow-md transition-all duration-300
                                     hover:shadow-lg hover:shadow-red-500/30 hover:-translate-y-0.5 flex items-center gap-2"
                        >
                          {/* Shimmer Effect */}
                          <div className="absolute inset-0 -translate-x-full group-hover:animate-[shimmer_1.5s_infinite] bg-gradient-to-r from-transparent via-white/20 to-transparent z-0"></div>

                          {/* Button Content */}
                          <span className="relative z-10 tracking-wide">{link.label}</span>
                          <ArrowRight className="w-4 h-4 relative z-10 transition-transform duration-300 group-hover:translate-x-1" />
                        </button>
                      ))}
                   </div>
                </div>
              )}
            </div>

            {/* KEY FEATURES GRID */}
            {product.features && (
              <div className="bg-slate-50/50 rounded-xl p-6 border border-slate-100">
                <h3 className="text-sm font-bold text-slate-900 uppercase tracking-widest mb-4 flex items-center gap-2">
                  <Settings className="w-4 h-4 text-red-700" /> Key Features
                </h3>
                <ul className="grid grid-cols-1 md:grid-cols-2 gap-3 text-left">
                  {product.features.map((feature, idx) => (
                    <li key={idx} className="flex items-start gap-2 text-sm text-slate-700">
                      <span className="text-red-600 mt-1">▸</span>
                      <span>{feature}</span>
                    </li>
                  ))}
                </ul>
              </div>
            )}

            {/* APPLICATIONS & CERTIFICATIONS ROW */}
            {(product.applications || product.certifications) && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                
                {/* Applications */}
                {product.applications && (
                  <div>
                    <h4 className="text-xs font-bold text-slate-400 uppercase tracking-widest mb-3">
                      Applications
                    </h4>
                    <div className="flex flex-wrap gap-2 justify-center lg:justify-start">
                      {product.applications.map((app, idx) => (
                        <span key={idx} className="px-3 py-1 bg-blue-50 text-blue-800 text-xs font-semibold rounded-md border border-blue-100">
                          {app}
                        </span>
                      ))}
                    </div>
                  </div>
                )}

                {/* Certifications */}
                {product.certifications && (
                  <div>
                    <h4 className="text-xs font-bold text-slate-400 uppercase tracking-widest mb-3 flex items-center justify-center lg:justify-start gap-2">
                      <ShieldCheck className="w-3 h-3" /> Certifications
                    </h4>
                    <div className="flex flex-wrap gap-2 justify-center lg:justify-start">
                      {product.certifications.map((cert, idx) => (
                        <span key={idx} className="px-3 py-1 bg-green-50 text-green-800 text-xs font-semibold rounded-md border border-green-100">
                          {cert}
                        </span>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}

     {/* AVAILABLE MODELS */}
<div className="pt-2">

  {/* ================= HD ACTUATOR – CLICK SERIES ================= */}
  {product.id === "hd-rotary" ? (
    <div className="space-y-6">
      <h4 className="text-xs font-bold text-slate-400 uppercase tracking-widest">
        Available Models
      </h4>

      {/* SERIES BUTTONS */}
      <div className="flex flex-wrap gap-3 justify-center lg:justify-start">
        {hdSeriesModels.map((group, idx) => {
          const isActive = activeHdSeries === group.series;

          return (
            <button
              key={idx}
              onClick={() =>
                setActiveHdSeries(isActive ? null : group.series)
              }
              className={`group relative overflow-hidden
                px-5 py-2.5 text-xs md:text-sm font-semibold rounded-sm border
                transition-all duration-300 ease-out
                transform active:scale-95
                ${
                  isActive
                    ? "bg-gradient-to-r from-red-700 to-red-600 text-white border-red-700 shadow-md shadow-red-500/30"
                    : "bg-white text-slate-700 border-slate-300 hover:border-red-600 hover:text-red-700 hover:-translate-y-0.5 hover:shadow-sm"
                }`}
            >
              {/* shimmer */}
              <span className="absolute inset-0 -translate-x-full group-hover:translate-x-full transition-transform duration-700 bg-gradient-to-r from-transparent via-white/25 to-transparent" />

              <span className="relative z-10 tracking-wide">
                {group.series}
              </span>
            </button>
          );
        })}
      </div>

      {/* MODELS (SHOW ONLY WHEN SERIES CLICKED) */}
      {activeHdSeries && (
        <div className="mt-4 animate-in fade-in slide-in-from-top-2 duration-300">
          {hdSeriesModels
            .filter((g) => g.series === activeHdSeries)
            .map((group) => (
              <div
                key={group.series}
                className="flex flex-wrap gap-2 justify-center lg:justify-start"
              >
                {group.models.map((model, idx) => (
                  <button
                    key={idx}
                    onClick={() => handleModelClick(model)}
                    className="group relative
                               px-4 py-1.5 text-xs md:text-sm font-medium
                               bg-white border border-slate-300
                               text-slate-700 rounded-sm
                               transition-all duration-300 ease-out
                               hover:border-red-600 hover:text-red-700 hover:bg-red-50
                               hover:-translate-y-0.5 hover:shadow-sm
                               active:scale-95"
                  >
                    {model}
                  </button>
                ))}
              </div>
            ))}
        </div>
      )}
    </div>
  ) : (
    /* ================= NORMAL PRODUCTS ================= */
    <div>
      <div className="flex justify-between items-center mb-4">
        <span className="text-xs font-bold text-slate-400 uppercase tracking-widest">
          Available Models ({product.models.length})
        </span>

        {product.models.length > 6 && (
          <button
            onClick={() => setShowAllModels(!showAllModels)}
            className="group flex items-center gap-1
                       text-xs font-semibold text-red-700
                       px-3 py-1.5 rounded-md
                       transition-all duration-300
                       hover:text-red-800 hover:bg-red-50
                       active:scale-95"
          >
            {showAllModels ? (
              <>
                <ChevronUp className="w-3 h-3 transition-transform group-hover:-translate-y-0.5" />
                Show Less
              </>
            ) : (
              <>
                <ChevronDown className="w-3 h-3 transition-transform group-hover:translate-y-0.5" />
                Show All Models
              </>
            )}
          </button>
        )}
      </div>

      <div className="flex flex-wrap gap-2 justify-center lg:justify-start">
        {(showAllModels ? product.models : product.models.slice(0, 6)).map(
          (model, idx) => (
            <button
              key={idx}
              onClick={() => handleModelClick(model)}
              className="px-3 py-1.5 md:px-4 md:py-2
                         bg-white border border-slate-200
                         text-slate-600 text-xs md:text-sm font-medium
                         rounded-sm
                         transition-all duration-300
                         hover:border-red-300 hover:bg-red-50/40
                         hover:text-red-700 hover:shadow-sm
                         active:scale-95"
            >
              {model}
            </button>
          )
        )}
      </div>
    </div>
  )}
</div>

            {/* BUTTONS */}
            <div className="pt-4 flex flex-col md:flex-row gap-4 w-full md:w-auto">
              <Button
                size="lg"
                className="group relative overflow-hidden bg-red-700 hover:bg-red-800 text-white text-sm md:text-base font-serif tracking-wide px-8 py-6 rounded-sm shadow-xl hover:shadow-red-900/30 transition-all duration-500 w-full md:w-auto"
                onClick={() => navigate(`/products/${product.id}`)}
              >
                <span className="relative z-10 flex items-center justify-center gap-2">
                  View Details <ArrowRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
                </span>
                <div className="absolute inset-0 h-full w-full scale-0 rounded-sm transition-all duration-300 group-hover:scale-100 group-hover:bg-red-600/20"></div>
              </Button>

               {/* Request a Quote */}
      <Button
        size="lg"
        className="group bg-white border-2 border-red-700 text-red-700 hover:bg-red-50 text-sm md:text-base font-serif tracking-wide px-8 py-6 rounded-sm transition-all duration-300 shadow-sm w-full md:w-auto"
        onClick={() =>
          navigate(`/contact`)
        }
      >
        <span className="flex items-center justify-center gap-2">
          Request a Quote
          <ArrowRight className="w-4 h-4" />
        </span>
      </Button>
            </div>
          </div>
        </div>
      </div>

      {/* Model Details Modal */}
      <ModelDetailsModal
        isOpen={isModalOpen}
        onClose={() => {
          setIsModalOpen(false);
          setSelectedModelDetails(null);
        }}
        details={selectedModelDetails}
      />
    </>
  );
};

/* ===========================================================
   MAIN PAGE
   =========================================================== */
export default function Products() {
  const { t } = useLanguage();
  const [searchParams] = useSearchParams();
  const [activeTab, setActiveTab] = useState("all");
  
  const contentStartRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const category = searchParams.get("category");
    const productId = searchParams.get("id");

    if (category) {
      setActiveTab(category);
      setTimeout(() => {
        if (contentStartRef.current) {
          const yOffset = -200; 
          const element = contentStartRef.current;
          const y = element.getBoundingClientRect().top + window.pageYOffset + yOffset;
          window.scrollTo({ top: y, behavior: 'smooth' });
        }
      }, 100);
    } 
    
    if (productId) {
       const product = allProducts.find(p => p.id === productId);
       if(product) {
         setActiveTab(product.type.toLowerCase());
         setTimeout(() => {
            const element = document.getElementById(productId);
            if (element) {
               element.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
         }, 300);
       }
    }

  }, [searchParams]);

  const filteredProducts =
    activeTab === "all"
      ? allProducts
      : allProducts.filter(
          (p) => p.type.toLowerCase() === activeTab.toLowerCase()
        );

  return (
    <div className="min-h-screen bg-white text-slate-800">
      <SEO
        title="Products - Industrial Actuators"
        description="Browse our comprehensive range of industrial actuators including pneumatic actuators (PDS, HD, PLDS, MPLDS), electrical actuators (ITQ, IQL, ITL, ITM), mechanical actuators (bevel gear, worm gear), and hydraulic actuators. Premium quality actuators for power generation, oil & gas, and process industries."
        keywords="pneumatic actuators, electric actuators, mechanical actuators, hydraulic actuators, PDS actuator, ITQ actuator, bevel gear actuator, worm gear actuator, valve actuators, industrial automation actuators, Susin actuators"
        url="https://www.susingroup.com/products"
        type="website"
        structuredData={{
          "@context": "https://schema.org",
          "@type": "CollectionPage",
          name: "Industrial Actuators - Susin Group",
          description: "Comprehensive range of industrial actuators for automation",
          url: "https://www.susingroup.com/products",
          mainEntity: {
            "@type": "ItemList",
            itemListElement: allProducts.slice(0, 10).map((product, index) => ({
              "@type": "ListItem",
              position: index + 1,
              item: {
                "@type": "Product",
                name: product.name,
                description: product.description,
                url: `https://www.susingroup.com/products/${product.id}`,
              },
            })),
          },
        }}
      />
      <Navbar />

      {/* Video Hero Section */}
      <section className="relative w-full h-[50vh] md:h-[70vh] overflow-hidden bg-black border-b-8 border-red-900">
        <video
          autoPlay
          loop
          muted
          playsInline
          className="absolute inset-0 w-full h-full object-cover opacity-60"
        >
          <source src={heroVideo} type="video/mp4" />
        </video>
      </section>

      {/* Filter Tabs - Relative */}
      <div 
        ref={contentStartRef} 
        className="relative bg-white border-b py-4 shadow-sm"
      >
        <div className="container mx-auto px-4">
          <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full flex justify-center">
            <TabsList className="bg-slate-50 p-1.5 h-auto rounded-xl flex flex-wrap justify-center gap-2">
              <TabsTrigger value="all" className="data-[state=active]:bg-red-700 data-[state=active]:text-white rounded-lg px-4 py-2">All Collection</TabsTrigger>
              <TabsTrigger value="pneumatic" className="data-[state=active]:bg-red-700 data-[state=active]:text-white rounded-lg px-4 py-2">Pneumatic</TabsTrigger>
              <TabsTrigger value="electrical" className="data-[state=active]:bg-red-700 data-[state=active]:text-white rounded-lg px-4 py-2">Electrical</TabsTrigger>
              <TabsTrigger value="mechanical" className="data-[state=active]:bg-red-700 data-[state=active]:text-white rounded-lg px-4 py-2">Mechanical</TabsTrigger>
              <TabsTrigger value="accessories" className="data-[state=active]:bg-red-700 data-[state=active]:text-white rounded-lg px-4 py-2">Accessories</TabsTrigger>
              <TabsTrigger
  value="hydraulic"
  className="data-[state=active]:bg-red-700 data-[state=active]:text-white rounded-lg px-4 py-2"
>
  Hydraulic
</TabsTrigger>
            </TabsList>
          </Tabs>
        </div>
      </div>

      {/* Product List */}
      <div className="min-h-screen pb-20 relative z-0">
        <div className="container mx-auto px-0 md:px-4">
          <Tabs value={activeTab} className="w-full">
            <TabsContent value={activeTab} className="mt-0">
              {filteredProducts.map((product, index) => (
                <ProductRow key={product.id} product={product} index={index} />
              ))}
              
              {filteredProducts.length === 0 && (
                 <div className="py-20 text-center text-slate-400">
                    No products found in this category.
                 </div>
              )}
            </TabsContent>
          </Tabs>
        </div>
      </div>

      <Footer />
      <Chatbot />
    </div>
  );
}