import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "motion/react";
import { ShieldCheck, Cpu, Database, Gauge, RefreshCw, Zap, CheckCircle } from "lucide-react";
const assets = [
  { id: "tube", name: "Heat Exchanger Tubes", icon: Cpu, description: "Tubular bundles in condensers, boilers, or evaporators." },
  { id: "vessel", name: "Pressure Vessels & Shells", icon: Database, description: "Process drums, reactors, and high-pressure tanks." },
  { id: "pipe", name: "Process & Utility Piping", icon: Gauge, description: "Cross-country pipelines, dead-legs, and small-bore systems." },
  { id: "tank", name: "Storage Tank Bottoms", icon: ShieldCheck, description: "Crude and product storage tanks with potential ground-side corrosion." }
];
const concerns = [
  { id: "thinning", name: "Wall Thinning & Erosion", description: "Internal or external metal loss from corrosive flow." },
  { id: "cracks", name: "Surface & Welds Micro-cracks", description: "Fatigue cracking or thermal stress in weld joints." },
  { id: "coating", name: "Coating Holiday / Voids", description: "Microscopic pinholes in protective epoxy layers." },
  { id: "alloy", name: "Alloy Composition Mix-up", description: "Incorrect filler metal or grade installation." }
];
const getRecommendation = (assetId, concernId) => {
  if (assetId === "tube") {
    if (concernId === "thinning") {
      return {
        technique: "Remote Field Eddy Current Testing (RFET) & NFT",
        techCode: "RFET / NFT / IRIS",
        standards: ["ASME Section V Article 8", "ASTM E2096", "API 570"],
        prepRequired: ["Hydro-jetting cleaning (280\u2013560 kg/cm\xB2)", "Dummy probe sizing check", "Drying of tubes"],
        advantage: "Highly sensitive to wall loss in ferromagnetic boiler and air-cooler tubes.",
        simulatedSignalName: "Impedance Phase Shift Anomaly",
        simulatedSignalDesc: "Indicates localized pitting near support baffle.",
        dangerLevel: "High"
      };
    }
    if (concernId === "cracks") {
      return {
        technique: "Eddy Current Testing (ECT)",
        techCode: "ECT Tube Inspection",
        standards: ["ASME Section V Article 8", "ASTM E309", "API 510"],
        prepRequired: ["Internal brushing", "Calibration reference standard match", "Removal of scale"],
        advantage: "Extremely fast (up to 2m/s) detection of fine longitudinal cracks in non-ferrous tubing.",
        simulatedSignalName: "Lissajous Loop Phase Deflection",
        simulatedSignalDesc: "Reveals shallow inner-diameter surface breaking cracks.",
        dangerLevel: "High"
      };
    }
    if (concernId === "coating") {
      return {
        technique: "Specialized Internal Visual & Boroscopic Scan",
        techCode: "VT-Boroscopy",
        standards: ["ASME Section V Article 9", "API 510"],
        prepRequired: ["Total de-watering", "Dual-axis high-definition probe calibration"],
        advantage: "Visual verification of surface scaling and protective lining discoloration.",
        simulatedSignalName: "Optical Surface Mapping Anomaly",
        simulatedSignalDesc: "Visible pinhole lining breach with iron-sulfide deposits.",
        dangerLevel: "Medium"
      };
    }
    return {
      technique: "Positive Material Identification (PMI Spectroscopy)",
      techCode: "XRF / LIBS PMI",
      standards: ["API RP 578", "ASME Section II"],
      prepRequired: ["Oxide film sanding", "Surface temperature stability"],
      advantage: "Direct chemical verification of tube-to-tubesheet alloy grades.",
      simulatedSignalName: "X-Ray Emission Spectrum Peak",
      simulatedSignalDesc: "Identified trace elements conforming to Monel 400 specification.",
      dangerLevel: "Medium"
    };
  }
  if (assetId === "vessel") {
    if (concernId === "thinning") {
      return {
        technique: "Ultrasonic Corrosion Mapping & Thickness Testing",
        techCode: "UT-Corrosion Mapping",
        standards: ["ASME Section V Article 5", "API 510", "API 579-1 FFS"],
        prepRequired: ["Removal of loose rust/peeling paint", "High-temp couplant application", "Grid marking"],
        advantage: "Provides absolute remaining wall thickness calculations for Fitness-For-Service.",
        simulatedSignalName: "A-Scan Signal Time-of-Flight Shift",
        simulatedSignalDesc: "Significant shift in back-wall echo indicates localized wear loop.",
        dangerLevel: "High"
      };
    }
    if (concernId === "cracks") {
      return {
        technique: "Wet Fluorescent Magnetic Particle Testing (WFMT) or PAUT",
        techCode: "WFMT / Phased Array UT",
        standards: ["ASME Section V Article 4 & 7", "ASTM E1444", "API 510"],
        prepRequired: ["Grease degreasing", "UV black-light assembly setup", "Yoke calibration check"],
        advantage: "Detects extreme fine environmental stress corrosion cracks (SCC) in vessel welds.",
        simulatedSignalName: "Linear Magnetic Particle Indication",
        simulatedSignalDesc: "Fine transverse weld toe crack highlighted under UV spectrum.",
        dangerLevel: "High"
      };
    }
    if (concernId === "coating") {
      return {
        technique: "High-Voltage Holiday / Spark Testing",
        techCode: "HV Holiday Detection",
        standards: ["NACE SP0188", "ASTM D5162"],
        prepRequired: ["Lining curing verification", "Ground wire connection to bare steel", "Dry surface state"],
        advantage: "Uncovers invisible microscopic voids in internal rubber/glass-flake linings.",
        simulatedSignalName: "Audible Continuous Spark Arc",
        simulatedSignalDesc: "Voltage drop at 15kV identifies lining puncture.",
        dangerLevel: "Medium"
      };
    }
    return {
      technique: "Portable PMI Spectroscopy",
      techCode: "PMI Verification",
      standards: ["API RP 578", "ASME Section II"],
      prepRequired: ["Bare metal contact grinding", "Standards reference calibration"],
      advantage: "Ensures replacement shell plate or weld filler matches material datasheet specifications.",
      simulatedSignalName: "Chromium-Nickel Spectral Signal",
      simulatedSignalDesc: "Conforms to SS316L; matches code verification guidelines.",
      dangerLevel: "Medium"
    };
  }
  if (assetId === "pipe") {
    if (concernId === "thinning") {
      return {
        technique: "Manual & Automated Ultrasonic Thickness Testing (UT-T)",
        techCode: "UT Wall-Thickness",
        standards: ["ASME Section V Article 5", "API 570", "API 574"],
        prepRequired: ["Couplant brush-on", "Scale scraping of test point", "Zero-block calibration"],
        advantage: "Fast, precise remaining-life estimations in designated corrosion monitoring locations (CML).",
        simulatedSignalName: "UT Echo Loss",
        simulatedSignalDesc: "Reduced wall-thickness detected inside dead-leg bend.",
        dangerLevel: "High"
      };
    }
    if (concernId === "cracks") {
      return {
        technique: "Ultrasonic Shear-Wave / PAUT Inspections",
        techCode: "PAUT Weld Inspection",
        standards: ["ASME Section V Article 4", "API 570", "AWS D1.1"],
        prepRequired: ["Weld crown preparation", "Couplant liquid application", "Wedge scan path design"],
        advantage: "Volumetric weld-integrity scan; maps complete flaw depth, length, and slope.",
        simulatedSignalName: "B-Scan Cross-Section Reflection",
        simulatedSignalDesc: "Lack of root fusion anomaly identified at the 4-inch weld seam.",
        dangerLevel: "High"
      };
    }
    if (concernId === "coating") {
      return {
        technique: "Low-Voltage Sponge / Wet Sponge Holiday Testing",
        techCode: "LV Holiday Testing",
        standards: ["ASTM G62", "NACE SP0188"],
        prepRequired: ["Tap water wetting with surfactant", "Lining surface drying"],
        advantage: "Non-destructive testing for delicate pipeline paint or thin epoxy liners.",
        simulatedSignalName: "Audio Signal Indicator Trigger",
        simulatedSignalDesc: "Resistance drop reveals pinhole breach on the external pipe wrap.",
        dangerLevel: "Medium"
      };
    }
    return {
      technique: "Alloy Verification & Weld PMI Check",
      techCode: "XRF Alloy Analyzer",
      standards: ["API RP 578", "ASME Section IX"],
      prepRequired: ["Sanding of paint down to bare steel", "Analyzer sensor clean"],
      advantage: "Rapid verification of pipe fitting schedules and flange material compatibility.",
      simulatedSignalName: "Spectral Peak Verification",
      simulatedSignalDesc: "Conforms to ASTM A106 Grade B carbon steel specification.",
      dangerLevel: "Low"
    };
  }
  if (concernId === "thinning") {
    return {
      technique: "Magnetic Flux Leakage (MFL) Tank Bottom Floor Scanner",
      techCode: "MFL Scanning",
      standards: ["API 653 Annex C", "ASME Section V Article 16"],
      prepRequired: ["Comprehensive tank cleaning & sludge removal", "Floor drying", "Removal of heavy scale"],
      advantage: "Rapidly scans 100% of tank bottom plates for soil-side or product-side pitting.",
      simulatedSignalName: "MFL Flux Leakage Peak",
      simulatedSignalDesc: "High flux escape indicates ~45% bottom plate loss from the bottom soil side.",
      dangerLevel: "High"
    };
  }
  if (concernId === "cracks") {
    return {
      technique: "Vacuum Box Testing & Dye Penetrant (PT)",
      techCode: "Vacuum Box & PT Weld",
      standards: ["ASME Section V Article 10", "API 653"],
      prepRequired: ["Weld slag wire-brushing", "Liquid soap-bubble detergent prep", "Sufficient lighting"],
      advantage: "Provides 100% immediate bubble verification of potential annular plate weld seam leaks.",
      simulatedSignalName: "Detergent Bubble Indication",
      simulatedSignalDesc: "Active bubble train stream points to a fine through-wall pinhole weld leak.",
      dangerLevel: "High"
    };
  }
  if (concernId === "coating") {
    return {
      technique: "High-Voltage Pulse Holiday Testing",
      techCode: "Pulse Holiday NDT",
      standards: ["NACE SP0188", "API 652"],
      prepRequired: ["Coating curing check", "Continuous wire loop ground installation", "Dust wipe down"],
      advantage: "Safely checks heavy, multi-layer reinforced tank fiber lining systems.",
      simulatedSignalName: "High-Voltage Arc Spark",
      simulatedSignalDesc: "Discharge arc points to holiday location in sump lining weld.",
      dangerLevel: "Medium"
    };
  }
  return {
    technique: "XRF Alloy Analysis & Hardness Audit",
    techCode: "PMI Hardness Testing",
    standards: ["API 653", "ASTM E110"],
    prepRequired: ["Sanding weld crown flat", "Surface cleaning"],
    advantage: "Validates mechanical strength properties of heavy structural shell plate welds.",
    simulatedSignalName: "Brinell Hardness Value Return",
    simulatedSignalDesc: "185 HBW reading confirms material toughness falls in safe operating zone.",
    dangerLevel: "Medium"
  };
};
export default function InteractiveNdtAdvisor() {
  const [selectedAsset, setSelectedAsset] = useState("tube");
  const [selectedConcern, setSelectedConcern] = useState("thinning");
  const [isScanning, setIsScanning] = useState(false);
  const [scanProgress, setScanProgress] = useState(0);
  const [showResult, setShowResult] = useState(true);
  const [scanComplete, setScanComplete] = useState(false);
  const recommendation = getRecommendation(selectedAsset, selectedConcern);
  const handleScan = () => {
    setIsScanning(true);
    setScanProgress(0);
    setScanComplete(false);
  };
  useEffect(() => {
    let interval;
    if (isScanning) {
      interval = setInterval(() => {
        setScanProgress((prev) => {
          if (prev >= 100) {
            clearInterval(interval);
            setIsScanning(false);
            setScanComplete(true);
            return 100;
          }
          return prev + 4;
        });
      }, 50);
    }
    return () => clearInterval(interval);
  }, [isScanning]);
  const CurrentAssetIcon = assets.find((a) => a.id === selectedAsset)?.icon || Cpu;
  return <div id="ndt-advisor-widget" className="bg-white border border-slate-200 rounded-3xl shadow-xl overflow-hidden max-w-6xl mx-auto my-6">
      <div className="grid lg:grid-cols-12">
        
        {
    /* Left Side: Control Center (7 cols) */
  }
        <div className="lg:col-span-7 p-6 sm:p-10 border-b lg:border-b-0 lg:border-r border-slate-100 flex flex-col justify-between">
          <div>
            <div className="flex items-center gap-2 mb-4">
              <span className="w-2.5 h-2.5 bg-orange-500 rounded-full animate-pulse" />
              <span className="font-mono text-[10px] font-bold text-orange-500 uppercase tracking-widest">
                Interactive Engineering System
              </span>
            </div>
            
            <h3 className="font-heading text-2xl sm:text-3xl font-extrabold text-slate-900 tracking-tight">
              NDT Strategy & Calibration Configurator
            </h3>
            <p className="text-xs text-slate-500 font-light mt-2 max-w-xl leading-relaxed">
              Select an industrial asset category and primary mechanical concern to generate a compliant code procedure recommendation and execute a simulated instrument calibration scan.
            </p>

            {
    /* Asset Selector */
  }
            <div className="mt-8">
              <label className="text-[11px] font-bold text-slate-400 uppercase tracking-wider font-heading block mb-3">
                1. Select Asset Geometry
              </label>
              <div className="grid grid-cols-2 gap-3">
                {assets.map((asset) => {
    const IconComp = asset.icon;
    const isSelected = selectedAsset === asset.id;
    return <button
      key={asset.id}
      onClick={() => {
        setSelectedAsset(asset.id);
        setScanComplete(false);
      }}
      className={`p-4 rounded-2xl border text-left transition-all duration-200 ${isSelected ? "bg-slate-900 text-white border-slate-900 shadow-md" : "bg-slate-50 text-slate-700 border-slate-200/60 hover:bg-slate-100/70"}`}
    >
                      <div className="flex items-center gap-3">
                        <div className={`p-2 rounded-xl ${isSelected ? "bg-orange-500 text-white" : "bg-slate-200/60 text-slate-600"}`}>
                          <IconComp className="w-4 h-4" />
                        </div>
                        <div>
                          <p className="text-xs font-bold font-heading">{asset.name}</p>
                        </div>
                      </div>
                    </button>;
  })}
              </div>
            </div>

            {
    /* Concern Selector */
  }
            <div className="mt-6">
              <label className="text-[11px] font-bold text-slate-400 uppercase tracking-wider font-heading block mb-3">
                2. Primary Concern or Damage Loop
              </label>
              <div className="grid grid-cols-2 gap-3">
                {concerns.map((concern) => {
    const isSelected = selectedConcern === concern.id;
    return <button
      key={concern.id}
      onClick={() => {
        setSelectedConcern(concern.id);
        setScanComplete(false);
      }}
      className={`p-4 rounded-2xl border text-left transition-all duration-200 ${isSelected ? "bg-orange-500 text-white border-orange-500 shadow-md" : "bg-slate-50 text-slate-700 border-slate-200/60 hover:bg-slate-100/70"}`}
    >
                      <h4 className="text-xs font-bold font-heading">{concern.name}</h4>
                      <p className={`text-[10px] mt-1 leading-normal ${isSelected ? "text-orange-100" : "text-slate-400"}`}>
                        {concern.description}
                      </p>
                    </button>;
  })}
              </div>
            </div>
          </div>

          {
    /* Action Footer */
  }
          <div className="mt-10 pt-6 border-t border-slate-100 flex flex-col sm:flex-row items-center justify-between gap-4">
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 rounded-full bg-slate-100 flex items-center justify-center text-slate-500 text-xs font-mono font-bold">
                i
              </div>
              <p className="text-[10px] text-slate-400 font-light max-w-xs leading-normal">
                Recommendations are vetted by our ASNT Level III and API 510/570 planning committees.
              </p>
            </div>

            <button
    onClick={handleScan}
    disabled={isScanning}
    className={`w-full sm:w-auto bg-slate-900 text-white hover:bg-slate-800 disabled:opacity-50 font-bold text-xs px-6 py-3.5 rounded-xl uppercase tracking-wider transition-all duration-200 flex items-center justify-center gap-2 shadow-md`}
  >
              {isScanning ? <>
                  <RefreshCw className="w-4 h-4 animate-spin text-white" />
                  <span>Scanning Instrument...</span>
                </> : <>
                  <Zap className="w-4 h-4 text-orange-400 fill-orange-400 animate-pulse" />
                  <span>Calibrate & Test Probe</span>
                </>}
            </button>
          </div>
        </div>

        {
    /* Right Side: Compliance Sheet & Live Scan Screen (5 cols) */
  }
        <div className="lg:col-span-5 p-6 sm:p-10 bg-slate-950 text-white flex flex-col justify-between relative overflow-hidden">
          
          {
    /* Subtle tech grid background */
  }
          <div className="absolute inset-0 bg-[linear-gradient(to_right,#1e293b_1px,transparent_1px),linear-gradient(to_bottom,#1e293b_1px,transparent_1px)] bg-[size:4rem_4rem] [mask-image:radial-gradient(ellipse_60%_50%_at_50%_50%,#000_70%,transparent_100%)] opacity-20 pointer-events-none" />
          
          <div className="relative z-10 space-y-6">
            <div className="flex items-center justify-between border-b border-slate-800 pb-4">
              <span className="font-mono text-xs font-bold text-orange-400 uppercase tracking-widest">
                Compliance Spec Sheet
              </span>
              <span className={`text-[9px] font-mono uppercase tracking-widest px-2 py-0.5 rounded border ${recommendation.dangerLevel === "High" ? "bg-red-500/10 text-red-400 border-red-500/20" : "bg-amber-500/10 text-amber-400 border-amber-500/20"}`}>
                Critical Level: {recommendation.dangerLevel}
              </span>
            </div>

            {
    /* Simulated Live Scan Screen */
  }
            <div className="bg-slate-900/90 border border-slate-800 rounded-2xl p-5 overflow-hidden font-mono relative">
              <div className="flex items-center justify-between text-[10px] text-slate-400 mb-4 pb-2 border-b border-slate-800/60">
                <span className="flex items-center gap-1.5">
                  <span className={`w-1.5 h-1.5 rounded-full ${isScanning ? "bg-orange-500 animate-ping" : "bg-green-500"}`} />
                  {isScanning ? "SIGNAL ACQUISITION ACTIVE" : "CALIBRATED & READY"}
                </span>
                <span>CH_A: 5.0 MHz</span>
              </div>

              {
    /* Scan visualization box */
  }
              <div className="h-28 flex items-center justify-center relative bg-slate-950 rounded-lg overflow-hidden border border-slate-800/40">
                
                {
    /* Simulated wave or scan line */
  }
                <AnimatePresence>
                  {isScanning ? <motion.div
    key="scanning"
    className="absolute inset-0 flex flex-col justify-center px-4"
  >
                      {
    /* Animated wave path */
  }
                      <svg viewBox="0 0 300 80" className="w-full h-full text-orange-500 stroke-2 fill-none">
                        <path d={`M 0,40 Q 30,20 60,40 T 120,40 T 180,${40 - scanProgress / 3} T 240,40 T 300,40`} className="animate-pulse" stroke="currentColor" />
                      </svg>
                      {
    /* Scanning laser sweep */
  }
                      <motion.div
    className="absolute top-0 bottom-0 w-0.5 bg-orange-400 shadow-[0_0_10px_#f97316] z-10"
    animate={{ left: ["0%", "100%", "0%"] }}
    transition={{ repeat: Infinity, duration: 1.5, ease: "linear" }}
  />
                    </motion.div> : scanComplete ? <motion.div
    initial={{ opacity: 0 }}
    animate={{ opacity: 1 }}
    className="absolute inset-0 bg-orange-500/5 p-3 flex flex-col justify-between"
  >
                      <div className="flex items-start justify-between text-[9px]">
                        <span className="text-orange-400 font-bold">⚠️ DETECTED ANOMALY</span>
                        <span className="text-slate-400">POS: 184.2 mm</span>
                      </div>
                      
                      {
    /* Anomaly wave signal with a massive spike */
  }
                      <svg viewBox="0 0 300 60" className="w-full h-10 text-orange-500 stroke-2 fill-none">
                        <path d="M 0,30 L 80,30 L 100,10 L 115,50 L 130,30 L 160,30 L 175,5 L 185,55 L 195,5 L 210,30 L 300,30" stroke="currentColor" />
                      </svg>

                      <div className="text-[10px] text-orange-300 leading-normal font-sans bg-orange-500/10 border border-orange-500/20 rounded p-1.5 mt-1">
                        <strong>{recommendation.simulatedSignalName}:</strong> {recommendation.simulatedSignalDesc}
                      </div>
                    </motion.div> : <div className="text-center text-xs text-slate-500 flex flex-col items-center gap-2">
                      <CurrentAssetIcon className="w-8 h-8 text-slate-600 animate-pulse" />
                      <span>Press Calibrate & Test Probe to capture NDT signals</span>
                    </div>}
                </AnimatePresence>

                {
    /* Progress Overlay */
  }
                {isScanning && <div className="absolute inset-0 bg-slate-950/80 flex flex-col items-center justify-center p-4">
                    <span className="text-xs font-bold text-orange-400 mb-2 font-mono">SWEEPING ASSET... {scanProgress}%</span>
                    <div className="w-44 h-1.5 bg-slate-800 rounded-full overflow-hidden">
                      <div className="h-full bg-orange-500" style={{ width: `${scanProgress}%` }} />
                    </div>
                  </div>}
              </div>
            </div>

            {
    /* Core Recommendation Specs */
  }
            <div className="space-y-4">
              <div>
                <span className="text-[10px] text-slate-400 font-bold uppercase tracking-wider block">Recommended NDT Technique</span>
                <p className="text-sm font-bold text-white mt-1 flex items-center gap-1.5">
                  <CheckCircle className="w-4.5 h-4.5 text-orange-500 shrink-0" />
                  {recommendation.technique}
                </p>
                <p className="text-xs text-slate-400 font-light mt-1">{recommendation.advantage}</p>
              </div>

              <div className="grid grid-cols-2 gap-4 pt-2 border-t border-slate-900">
                <div>
                  <span className="text-[10px] text-slate-400 font-bold uppercase tracking-wider block">Procedural Standards</span>
                  <div className="mt-1 flex flex-col gap-1">
                    {recommendation.standards.map((s) => <span key={s} className="font-mono text-[10px] text-orange-300 block bg-orange-500/5 py-0.5 px-1.5 rounded border border-orange-500/10 w-fit">
                        {s}
                      </span>)}
                  </div>
                </div>
                <div>
                  <span className="text-[10px] text-slate-400 font-bold uppercase tracking-wider block">Calibration Code</span>
                  <span className="font-mono text-xs font-bold text-slate-200 mt-1 block">
                    {recommendation.techCode}
                  </span>
                </div>
              </div>

              {
    /* Prep Work Required */
  }
              <div className="pt-4 border-t border-slate-900">
                <span className="text-[10px] text-slate-400 font-bold uppercase tracking-wider block">Mandatory Field Preparations</span>
                <ul className="mt-2 space-y-1.5 text-xs text-slate-300 font-light list-none">
                  {recommendation.prepRequired.map((p, idx) => <li key={idx} className="flex items-start gap-2">
                      <span className="w-1.5 h-1.5 rounded-full bg-orange-500 mt-1.5 shrink-0" />
                      <span>{p}</span>
                    </li>)}
                </ul>
              </div>
            </div>
          </div>

          <div className="mt-8 pt-4 border-t border-slate-800 text-center relative z-10">
            <p className="text-[11px] text-slate-400 font-light">
              Need custom procedures drafted for this asset configuration?
            </p>
            <a
    href="/contact"
    className="inline-flex items-center gap-1.5 text-[11px] font-bold text-orange-400 hover:text-orange-300 uppercase tracking-wider mt-2 group"
  >
              <span>Consult Our Level III Engineers</span>
              <span className="group-hover:translate-x-1 transition-transform">→</span>
            </a>
          </div>
        </div>

      </div>
    </div>;
}
