import { useEffect, useState } from 'react';
import { Helmet } from 'react-helmet-async';
import { motion } from 'motion/react';
import { Link } from 'react-router-dom';
import { ArrowRight, CheckCircle2, ShieldCheck, ArrowLeft, Wrench, Search, ChevronLeft, ChevronRight } from 'lucide-react';
import { LazyImage } from './LazyImage';
import { WhatsAppIcon } from './icons';
import { AeoSummary } from './AeoSummary';
import { ExpertEeatPanel } from './ExpertEeatPanel';
import { InteractiveDiagnoses } from './InteractiveDiagnoses';
import { IslandwideServiceCoverage } from './IslandwideServiceCoverage';
import { useSchemaRating } from '../hooks/useSchemaRating';
import { MASTER_LOCAL_BUSINESS_SCHEMA, generateProductSchema } from '../lib/schemas';
import { useUserRegion } from '../hooks/useUserRegion';
import { troubleshootingReviews } from '../data/serviceReviews';
import { getPublicSingaporeAreaServed } from '../data/locations';
import { COMMERCIAL_PAGE_HUB_CONFIG } from '../lib/seoHubArchitecture';

export const TroubleshootingPage = () => {
  const { rating, count } = useSchemaRating();
  const { closestHub, city } = useUserRegion();
  const [currentSlide, setCurrentSlide] = useState(0);

  const targetArea = closestHub && closestHub.prominentEstates && closestHub.prominentEstates.length > 0
    ? closestHub.prominentEstates[0]
    : (city && city !== "Singapore" ? city : "Singapore");
  const latitude = closestHub?.lat || 1.352083;
  const longitude = closestHub?.lng || 103.819836;

  const seoTitle = COMMERCIAL_PAGE_HUB_CONFIG['troubleshooting'].seoTitle;
  const seoDescription = COMMERCIAL_PAGE_HUB_CONFIG['troubleshooting'].seoDescription;

  const publicAreaServed = getPublicSingaporeAreaServed();


  const slides = [
    "/Troubleshoot1.webp",
    "/Troubleshoot2.webp"
  ];

  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentSlide((prev) => (prev + 1) % slides.length);
    }, 4000);
    return () => clearInterval(timer);
  }, [slides.length]);

  useEffect(() => {
    window.scrollTo(0, 0);
  }, []);

  return (
    <div className="animate-in fade-in duration-700 bg-white">
      <Helmet>
        <title>{seoTitle}</title>
        <meta name="description" content={seoDescription} />
        <meta name="keywords" content="aircon repair singapore, aircon troubleshooting, aircon blinking light, noisy aircon repair, aircon not cold, ac trip circuit breaker" />
        <link rel="canonical" href="https://skyblueaircon.com/troubleshooting" />
        
        {/* Geo-Specific Meta Tags for Local SEO */}
        <meta name="geo.region" content="SG" />
        <meta name="geo.placename" content={`${targetArea}, Singapore`} />
        <meta name="geo.position" content={`${latitude};${longitude}`} />
        <meta name="ICBM" content={`${latitude}, ${longitude}`} />

        {/* Dublin Core metadata for explicit location coverage targeting */}
        <meta name="DC.title" content={seoTitle} />
        <meta name="DC.description" content={seoDescription} />
        <meta name="DC.creator" content="Sky Blue Aircon Engineering" />
        <meta name="DC.subject" content="Air Conditioning Servicing, Maintenance, Chemical Overhaul, and Repair" />
        <meta name="DC.coverage" content={`Singapore, ${targetArea}`} />
        <meta name="DC.language" content="en_SG" />

        {/* OpenGraph/Facebook metadata */}
        <meta property="og:title" content={seoTitle} />
        <meta property="og:description" content={seoDescription} />
        <meta property="og:type" content="website" />
        <meta property="og:image" content="https://skyblueaircon.com/PureLogo.png" />
        <meta property="og:url" content="https://skyblueaircon.com/troubleshooting" />
        <meta property="og:site_name" content="Sky Blue Aircon Engineering" />
        <meta property="og:locale" content="en_SG" />
        <meta property="og:latitude" content={latitude.toString()} />
        <meta property="og:longitude" content={longitude.toString()} />
        <meta property="og:locality" content={targetArea} />
        <meta property="og:region" content="Singapore" />
        <meta property="og:country-name" content="Singapore" />
        
        {/* Twitter Card metadata */}
        <meta name="twitter:card" content="summary_large_image" />
        <meta name="twitter:title" content={seoTitle} />
        <meta name="twitter:description" content={seoDescription} />
        <meta name="twitter:image" content="https://skyblueaircon.com/PureLogo.png" />

        <script type="application/ld+json">
          {JSON.stringify([
            {
              "@context": "https://schema.org",
              "@type": "LocalBusiness",
              "@id": "https://skyblueaircon.com/#localbusiness",
              "name": "Sky Blue Aircon Engineering Pte. Ltd.",
              "image": "https://skyblueaircon.com/PureLogo.png",
              "telephones": ["+65 6556 4042", "+65 9248 7291"],
              "telephone": "+65 6556 4042",
              "url": "https://skyblueaircon.com",
              "logo": "https://skyblueaircon.com/favicon.png",
              "priceRange": "$$",
              "address": {
                "@type": "PostalAddress",
                "streetAddress": "31 Woodlands Close, Woodlands Horizon",
                "addressLocality": "Singapore",
                "postalCode": "737855",
                "addressCountry": "SG"
              },
              "geo": {
                "@type": "GeoCoordinates",
                "latitude": latitude,
                "longitude": longitude
              },
              "openingHoursSpecification": MASTER_LOCAL_BUSINESS_SCHEMA.openingHoursSpecification,
              "priceSpecification": (MASTER_LOCAL_BUSINESS_SCHEMA as any).priceSpecification,
              "aggregateRating": {
                "@type": "AggregateRating",
                "ratingValue": rating,
                "reviewCount": count,
                "bestRating": "5",
                "worstRating": "1"
              },
              "review": troubleshootingReviews
            },
            {
              "@context": "https://schema.org",
              "@type": "Service",
              "name": "Aircon Repair and Troubleshooting Services",
              "serviceType": ["Aircon Troubleshooting", "AC Diagnosis & Repair", "HVAC Emergency Repair", "Blinking Light Diagnostics"],
              "provider": {
                "@type": "LocalBusiness",
                "@id": "https://skyblueaircon.com/#localbusiness"
              },
              "category": "Air Conditioning Sales & Service, HVAC Repair, Technical Troubleshooting",
              "brand": {
                "@type": "Brand",
                "name": "Sky Blue Aircon",
                "logo": "https://skyblueaircon.com/PureLogo.png",
                "slogan": "Singapore's Trusted HVAC Experts"
              },
              "areaServed": publicAreaServed,
              "description": `Professional troubleshooting, quick technical diagnosis, and precise repairs for aircon issues like power trips, blinking lights, noisy fans, warm air, and system boot-up failures across ${targetArea} and all locations in Singapore.`,
              "availableChannel": {
                "@type": "ServiceChannel",
                "serviceChannelType": "InPerson",
                "name": "On-site HVAC Servicing",
                "servicePhone": {
                  "@type": "ContactPoint",
                  "telephone": "+6565564042",
                  "contactType": "customer support"
                }
              },
              "hasOfferCatalog": {
                "@type": "OfferCatalog",
                "name": "Aircon Repair & Troubleshooting Capabilities",
                "itemListElement": [
                  {
                    "@type": "Offer",
                    "itemOffered": {
                      "@type": "Service",
                      "name": "Multi-Meter Electrical Diagnosis",
                      "description": "Tracing electrical failure points across the inverter motherboard, wiring, and fuses."
                    }
                  },
                  {
                    "@type": "Offer",
                    "itemOffered": {
                      "@type": "Service",
                      "name": "Power Trip & Fault Code Resolution",
                      "description": "Diagnosing why the system triggers household circuit breakers and fixing motherboard shorts."
                    }
                  },
                  {
                    "@type": "Offer",
                    "itemOffered": {
                      "@type": "Service",
                      "name": "Strange AC Noise & Vibration Isolation",
                      "description": "Locating squeaking, rattling, and clicking noises within fans and compressors to repair brackets or worn bearings."
                    }
                  },
                  {
                    "@type": "Offer",
                    "itemOffered": {
                      "@type": "Service",
                      "name": "Warm Air & Thermistor Malfunction Audit",
                      "description": "Analyzing failing cooling cycles and replacing compromised room-temp sensor probes."
                    }
                  }
                ]
              }
            },
            {
              "@context": "https://schema.org",
              "@type": "BreadcrumbList",
              "itemListElement": [
                {
                  "@type": "ListItem",
                  "position": 1,
                  "name": "Home",
                  "item": "https://skyblueaircon.com/"
                },
                {
                  "@type": "ListItem",
                  "position": 2,
                  "name": "Troubleshooting & Repair",
                  "item": "https://skyblueaircon.com/troubleshooting"
                }
              ]
            },
            {
              "@context": "https://schema.org",
              "@type": "FAQPage",
              "mainEntity": [
                {
                  "@type": "Question",
                  "name": "Why is my aircon light blinking and how do I troubleshoot it?",
                  "acceptedAnswer": {
                    "@type": "Answer",
                    "text": "A blinking indicator light on your indoor fancoil is a built-in safety alert indicating that the system's control board has logged an error code. For brands like Daikin or Panasonic, you can perform an error check sequence using the remote control. Our certified specialists carry digital manifolds and electrical multi-meters to quickly diagnose and safely repair these fault codes on-site."
                  }
                },
                {
                  "@type": "Question",
                  "name": "Why is my air conditioner blowing warm air?",
                  "acceptedAnswer": {
                    "@type": "Answer",
                    "text": "Warm air delivery can be caused by simple blockages like clogged air filters, or mechanical issues like a failed starting capacitor, a faulty thermistor sensor, outdoor condenser heat recirculation, or refrigerant imbalances. An accurate on-site thermodynamic inspection is necessary to safely pinpoint the cause before repairing or topping up refrigerant."
                  }
                },
                {
                  "@type": "Question",
                  "name": "Do you charge a diagnostic fee for aircon troubleshooting?",
                  "acceptedAnswer": {
                    "@type": "Answer",
                    "text": "We charge a standard, transparent diagnostic fee to deploy a certified HVAC technician to your property to carry out electrical, pressure, and sensor checks. Should you choose to proceed with our recommended parts replacement or repair work, this diagnostic fee is typically waived or integrated into the final service charge."
                  }
                }
              ]
            },
            generateProductSchema({
              name: "Professional Aircon Diagnostics, Repairs & Troubleshooting",
              description: `Is your aircon blinking lights, blowing warm air, or completely unresponsive? Our BCA-certified technicians use professional diagnostic tools to accurately isolate and resolve electrical, mechanical, and sensor faults safely in ${targetArea}, Singapore.`,
              url: "https://skyblueaircon.com/troubleshooting",
              rating,
              count,
              price: "50.00"
            })
          ])}
        </script>
      </Helmet>

      {/* Hero Section */}
      <section className="relative pt-32 pb-20 lg:pt-48 lg:pb-32 overflow-hidden bg-slate-50">
        <div className="absolute inset-0 bg-sky-900/5 z-0" />
        <div className="max-w-7xl mx-auto px-6 sm:px-8 relative z-10 grid md:grid-cols-2 gap-12 sm:gap-16 items-center">
          <motion.div
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.6 }}
            className="space-y-6 sm:space-y-8"
          >
            <Link to="/#services" className="inline-flex items-center gap-2 text-sky-600 font-bold text-xs uppercase tracking-widest hover:gap-3 transition-all mb-4">
              <ArrowLeft size={16} /> Back to Services
            </Link>
            
            <div>
              <h1 className="text-4xl sm:text-5xl lg:text-6xl font-extrabold text-slate-900 leading-tight tracking-tight">
                Troubleshooting <span className="text-sky-600">& Repairs</span>
              </h1>
              <p className="text-base sm:text-lg text-slate-500 mt-6 leading-relaxed font-medium">
                Quick diagnosis and repairs for aircon issues like water leaks, unusual noises, or complete system failures. Our technicians are trained to work with all major air conditioning brands to get your unit running smoothly again.
              </p>
            </div>
            
            <div className="flex flex-col sm:flex-row flex-wrap gap-4 pt-4">
              <a href="https://api.whatsapp.com/send?phone=6592487291" target="_blank" rel="noopener noreferrer" className="px-8 py-4 bg-[#003B73] hover:bg-[#0369A1] text-white rounded-xl font-bold transition-all shadow-lg shadow-[#003B73]/15 hover:shadow-xl hover:shadow-[#0369A1]/20 flex items-center justify-center gap-2.5 group text-center">
                <span>Book a Technician</span>
                <ArrowRight size={18} className="text-sky-300 group-hover:text-sky-200 group-hover:translate-x-1 transition-all" />
              </a>
              <a
                href="https://api.whatsapp.com/send?phone=6592487291&text=Hi%20Sky%20Blue%20Aircon%2C%20I%20would%20like%20to%20enquire%20about%20Aircon%20Troubleshooting%20%26%20Repairs."
                target="_blank"
                rel="noopener noreferrer"
                className="px-8 py-4 bg-white border border-slate-200/90 hover:border-[#003B73]/30 hover:bg-sky-50/40 text-[#003B73] rounded-xl font-bold shadow-xs transition-all flex items-center justify-center text-center gap-2.5 whitespace-nowrap"
              >
                <WhatsAppIcon size={18} className="text-[#25D366] shrink-0" />
                <span>WhatsApp</span>
              </a>
            </div>
          </motion.div>

          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.8 }}
            className="relative"
          >
            <div className="relative z-10 rounded-[32px] overflow-hidden shadow-2xl border-4 border-white aspect-[4/3] group">
              {slides.map((slide, idx) => (
                  <motion.div
                    key={idx}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: currentSlide === idx ? 1 : 0 }}
                    transition={{ duration: 0.5 }}
                    className="absolute inset-0"
                  >
                    <LazyImage src={slide} className="w-full h-full object-cover" alt={`Troubleshooting Gallery ${idx + 1}`} />
                  </motion.div>
              ))}
              
              {/* Navigation Arrows */}
              <button 
                onClick={() => setCurrentSlide((prev) => (prev === 0 ? slides.length - 1 : prev - 1))}
                className="absolute left-4 top-1/2 -translate-y-1/2 w-10 h-10 rounded-full bg-white/80 hover:bg-white flex items-center justify-center text-slate-800 shadow-md opacity-0 group-hover:opacity-100 transition-all z-10"
              >
                <ChevronLeft size={20} />
              </button>
              <button 
                onClick={() => setCurrentSlide((prev) => (prev + 1) % slides.length)}
                className="absolute right-4 top-1/2 -translate-y-1/2 w-10 h-10 rounded-full bg-white/80 hover:bg-white flex items-center justify-center text-slate-800 shadow-md opacity-0 group-hover:opacity-100 transition-all z-10"
              >
                <ChevronRight size={20} />
              </button>

              {/* Bullets */}
              <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2 z-10">
                {slides.map((_, idx) => (
                  <button
                    key={idx}
                    onClick={() => setCurrentSlide(idx)}
                    className={`w-2.5 h-2.5 rounded-full transition-all ${currentSlide === idx ? 'bg-white w-6' : 'bg-white/50 hover:bg-white/80'}`}
                  />
                ))}
              </div>

              <div className="absolute inset-0 bg-gradient-to-t from-black/40 to-transparent pointer-events-none flex items-end p-8">
                <span className="text-white font-bold text-sm tracking-widest uppercase shadow-sm">Expert Diagnostics</span>
              </div>
            </div>
          </motion.div>
        </div>
      </section>

      <ExpertEeatPanel topicName="Thermodynamic Diagnosis & Electrical Troubleshooting" />

      <InteractiveDiagnoses />

      {/* Common issues Section */}
      <section className="py-24 bg-white border-b border-slate-100">
        <div className="max-w-7xl mx-auto px-6 sm:px-8">
          <div className="text-center mb-16 max-w-2xl mx-auto">
            <span className="text-sky-600 font-bold uppercase tracking-widest text-[10px] px-3 py-1 bg-sky-50 rounded-md border border-sky-100">Common Issues</span>
            <h2 className="text-3xl sm:text-4xl font-extrabold text-slate-900 mt-6 tracking-tight">Symptoms of a Failing System.</h2>
          </div>

          {/* AI-Optimized Entity Summary for ChatGPT, Claude, and Gemini */}
          <AeoSummary
            entityName="Aircon Error Diagnosis"
            entityType="HVAC Fault Evaluation & Repair Support"
            summaryText="Professional HVAC troubleshooting evaluates mechanical, electrical, and cooling performance symptoms across split and multi-split systems. When a unit displays blinking LED fault codes, trips household breakers, or blows warm air, an on-site evaluation determines practical repair or component options subject to system condition."
            bulletPoints={[
              "Blinking LED timer indicators correspond to brand-specific system protection alerts.",
              "Rattling, buzzing, or whistling noises often point to worn mechanical mounts, motors, or refrigerant flow issues.",
              "Recurring circuit breaker trips require safe on-site electrical evaluation before resetting repeatedly.",
              "All repair and spare-part recommendations are quoted upfront subject to physical inspection."
            ]}
          />

          <div className="grid md:grid-cols-3 gap-8">
            {[
              { title: "Water Leakage", desc: <span className="inline">Water dripping from your indoor unit could indicate a choked drainage pipe, frozen evaporator coils, or a damaged drip pan. Read more about <Link to="/blog/aircon-drain-pipe-clogged" className="text-sky-600 hover:underline">clogged drain pipes</Link>.</span>, icon: <Search size={24} />, bg: "bg-blue-50", color: "text-blue-600" },
              { title: "Unusual Noises", desc: <span className="inline">Rattling, buzzing, or grinding sounds often point to loose parts, motor bearings wearing out, or a failing compressor. Recognize <Link to="/blog/aircon-compressor-failure-early-warning-signs" className="text-sky-600 hover:underline">compressor failure signs</Link>.</span>, icon: <Wrench size={24} />, bg: "bg-slate-100", color: "text-slate-600" },
              { title: "Blinking Lights / Complete Failure", desc: "When indicator lights start blinking or the unit does not power on at all, this is usually an electrical or PCB (Printed Circuit Board) fault that needs professional checking.", icon: <ShieldCheck size={24} />, bg: "bg-red-50", color: "text-red-500" }
            ].map((benefit, i) => (
              <div key={i} className="p-8 rounded-3xl bg-slate-50 hover:bg-white border border-transparent hover:border-slate-100 hover:shadow-[0_8px_30px_rgb(0,0,0,0.04)] transition-all">
                <div className={`w-14 h-14 rounded-2xl flex items-center justify-center mb-6 shadow-sm ${benefit.bg} ${benefit.color}`}>
                  {benefit.icon}
                </div>
                <h3 className="text-xl font-bold text-slate-900 mb-3 tracking-tight">{benefit.title}</h3>
                <p className="text-slate-500 text-sm leading-relaxed font-medium">{benefit.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Scope of Work */}
      <section className="py-24 bg-slate-50">
        <div className="max-w-5xl mx-auto px-6 sm:px-8">
          <div className="text-center mb-16 max-w-2xl mx-auto">
            <h2 className="text-3xl sm:text-4xl font-extrabold text-slate-900 tracking-tight">Our Repair Process</h2>
          </div>
          <div className="grid md:grid-cols-2 gap-8 lg:gap-12">
            <div className="space-y-4">
              {[
                "Deploying our skilled technicians directly to your location.",
                "In-depth inspection of your aircon unit components.",
                "Pinpointing the root cause of the breakdown accurately.",
                "Explaining the issue clearly without confusing technical jargon.",
                "Providing a transparent, obligation-free quotation for the repair.",
                "Swift replacement or repair of faulty parts using genuine spares.",
                "Post-repair functional testing to ensure problem is resolved."
              ].map((item, index) => (
                <div key={index} className="flex items-start gap-4 p-5 bg-white rounded-2xl shadow-[0_2px_12px_rgb(0,0,0,0.02)] border border-slate-100">
                  <div className="w-6 h-6 rounded-full bg-sky-100 flex items-center justify-center text-sky-600 shrink-0 mt-0.5">
                    <CheckCircle2 size={14} />
                  </div>
                  <p className="text-slate-700 font-medium">{item}</p>
                </div>
              ))}
            </div>
            
            <div className="flex flex-col justify-center">
              <div className="p-8 bg-white border border-slate-100 rounded-3xl shadow-[0_4px_20px_rgb(0,0,0,0.03)] h-full flex flex-col justify-center">
                 <Wrench size={48} className="text-sky-500 mb-6" />
                 <div>
                   <h4 className="font-extrabold text-slate-900 text-2xl tracking-tight mb-4">Fast & Reliable Service</h4>
                   <p className="text-slate-500 font-medium leading-relaxed mb-8">We know a broken aircon is a huge inconvenience. That’s why we prioritize efficiency and keep standard replacement parts on hand for same-day repairs.</p>
                   
                   <p className="text-sm font-bold text-slate-700 uppercase tracking-widest border-b border-slate-100 pb-2 mb-4">Diagnostics Fee</p>
                   <p className="text-slate-600 font-medium text-sm">
                     We charge a standard initial diagnostic fee for analyzing the faulty system. Should you proceed with the proposed repair, the diagnostic fee is typically waived.
                   </p>
                   <div className="mt-8">
                     <a href="https://api.whatsapp.com/send?phone=6592487291" target="_blank" rel="noopener noreferrer" className="group inline-flex items-center justify-center gap-2 px-6 py-3.5 bg-[#003B73] hover:bg-[#0369A1] text-white rounded-xl font-bold shadow-md shadow-[#003B73]/15 transition-all w-full">
                       <span>Request a Repair</span>
                       <ArrowRight size={18} className="text-sky-300 group-hover:text-sky-200 group-hover:translate-x-1 transition-all" />
                     </a>
                   </div>
                 </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <IslandwideServiceCoverage serviceSlug="troubleshooting" serviceName="Aircon Repair & Troubleshooting" />
    </div>
  );
};
