'use client';

import { useRef } from 'react';
import { motion } from 'framer-motion';
import Image from 'next/image';
import Link from 'next/link';
import { 
  Info, 
  BookOpen, 
  Download, 
  ShieldCheck, 
  Activity, 
  Car, 
  Gauge, 
  LayoutGrid, 
  Cpu, 
  Zap, 
  Layers, 
  Server, 
  Bluetooth, 
  FileText, 
  ExternalLink,
  ChevronRight,
  Settings,
  CircleCheck,
  Smartphone,
  AlertTriangle,
  ShieldAlert,
  Thermometer,
  Lightbulb,
  Radio
} from 'lucide-react';
import styles from './KPro.module.css';

export default function KPro() {
  const infoRef = useRef<HTMLDivElement>(null);
  const guidesRef = useRef<HTMLDivElement>(null);
  const downloadRef = useRef<HTMLDivElement>(null);

  const scrollTo = (ref: React.RefObject<HTMLDivElement | null>) => {
    ref.current?.scrollIntoView({ behavior: 'smooth' });
  };

  const coreFeatures = [
    { title: 'Live Engine Tuning', desc: 'Modify and calibrate fuel, ignition, and cam timing maps in real-time.', icon: <Activity size={24} /> },
    { title: 'Live Sensors Logging', desc: 'High-speed data streaming of all critical engine sensors for precision analysis.', icon: <Gauge size={24} /> },
    { title: 'Boost Features', desc: 'Boost tables, boost control, and custom MAP sensor support.', icon: <Zap size={24} /> },
    { title: 'Engine Protection', desc: 'Failsafe logic for lean AFR, overboost, and overheat conditions.', icon: <ShieldCheck size={24} /> },
    { title: 'Launch Control', desc: 'Programmable launch parameters with integrated anti-lag systems.', icon: <Settings size={24} /> },
    { title: 'Nitrous & Methanol', desc: 'Support for Nitrous or Methanol injection systems.', icon: <Thermometer size={24} /> },
    { title: 'MIL ShiftLight', desc: 'Configurable shift light via the Check Engine (MIL) light.', icon: <Lightbulb size={24} /> },
    { title: 'Programmable Outputs', desc: 'Customizable outputs for relays and accessories.', icon: <Layers size={24} /> },
    { title: 'Full System Compatibility', desc: 'Fully compatible with all vehicle systems, ABS, Climate Control, etc.', icon: <Car size={24} /> },
  ];

  const advancedFeatures = [
    { title: 'Bluetooth', desc: 'Wireless tuning and datalogging.', image: '/adv_bluetooth.png' },
    { title: 'Onboard Datalog (100Hz)', desc: 'High-precision onboard logging for standalone capture.', image: '/adv_datalog.png' },
    { title: 'FlexFuel Support', desc: 'Ethanol sensor input for automatic fuel scaling.', image: '/adv_flexfuel.png' },
    { title: '8 Analog Inputs', desc: 'Additional analog inputs for custom sensors.', image: '/adv_analog.png' },
    { title: 'External Wideband', desc: 'Input for aftermarket wideband oxygen sensors.', image: '/adv_wideband.png' },
    { title: 'Speed Sensor Output', desc: 'Alternate speed sensor input and Dashboard Speed Output (EG/EK/DC K Swap).', image: '/adv_speed.png' },
    { title: 'Live Autotune', desc: 'Live Autotune Tables for rapid calibration.', image: '/adv_autotune.png' },
    { title: 'Target Lambda', desc: 'Closed-loop target lambda tables.', image: '/adv_lambda.png' },
    { title: 'Advanced Protection', desc: 'Advanced engine protection logic.', image: '/adv_protection.png' },
  ];

  const ecuRevisions = [
    { name: '001DD-L5005-A0', type: 'OKI 66Q592 MCU' },
    { name: '001DD-L5003-00', type: 'OKI 66Q592 MCU' },
  ];

  const factoryModels = [
    { name: '02-05 Honda Civic Si', years: '02-05' },
    { name: '01-05 Honda Civic TypeR', years: '01-05' },
    { name: '01-06 Honda Integra DC5', years: '01-06' },
    { name: '02-06 Honda Integra TypeR', years: '02-06' },
    { name: '02-04 Acura RSX Base', years: '02-04' },
    { name: '02-04 Acura RSX TypeS', years: '02-04' },
  ];

  const replacementModels = [
    { name: '99-03 Honda S2000 AP1', years: '99-03' },
    { name: '02-05 Honda Civic D17 MT', years: '02-05' },
    { name: 'Various EG/EK/DC K-Swapped Vehicles', years: 'Various' },
  ];

  return (
    <div className={styles.wrapper}>
      {/* 1. HERO SECTION */}
      <section className={styles.hero}>
        <div className={styles.bgWrapper}>
          <Image src="/engine_bay.png" alt="Engine Bay" fill className={styles.heroImg} priority />
        </div>
        <div className={styles.heroOverlay}></div>
        <div className={styles.container}>
          <div className={styles.heroGrid}>
            <motion.div 
              className={styles.heroContent}
              initial={{ opacity: 0, x: -50 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.8, ease: "easeOut" }}
            >
              <span className={styles.heroLabel}>ULTIMATE ECU UPGRADE INTERFACE</span>
              <h1 className={styles.heroTitle}>
                K<span className={styles.red}>PRO</span>
              </h1>
              <p className={styles.heroDesc}>
                Daughterboard for Honda K-Series ECU – Expand your ECU Capabilities. 
                Unlock live tuning, advanced engine protection, and professional motorsport features.
              </p>
              <div className={styles.heroActions}>
                <button 
                  className={styles.primaryBtn}
                  onClick={() => scrollTo(infoRef)}
                >
                  <Info size={18} />
                  <span>INFORMATION</span>
                </button>
                <button 
                  className={styles.secondaryBtn}
                  onClick={() => scrollTo(guidesRef)}
                >
                  <BookOpen size={18} />
                  <span>GUIDES</span>
                </button>
                <button 
                  className={styles.secondaryBtn}
                  onClick={() => scrollTo(downloadRef)}
                >
                  <Download size={18} />
                  <span>DOWNLOAD</span>
                </button>
              </div>
            </motion.div>

            <motion.div 
              className={styles.heroSpecs}
              initial={{ opacity: 0, x: 50 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.8, delay: 0.2, ease: "easeOut" }}
            >
               <div className={styles.specBox}>
                  <div className={styles.progressLine}></div>
                  <div className={styles.specItem}>
                    <span className={styles.specLabel}>PLATFORM SUPPORT</span>
                    <h3>K-SERIES / VTC</h3>
                  </div>
                  <div className={styles.specItem}>
                    <span className={styles.specLabel}>DATALOG RATE</span>
                    <h3>100Hz REALTIME</h3>
                  </div>
                  <div className={styles.specItem}>
                    <span className={styles.specLabel}>CONNECTIVITY</span>
                    <h3>USB / BLUETOOTH</h3>
                  </div>
               </div>
            </motion.div>
          </div>
        </div>
      </section>

      {/* 2. OVERVIEW & FEATURES */}
      <section ref={infoRef} className={styles.overview}>
        <div className={styles.container}>
          <div className={styles.overviewGrid}>
            <motion.div 
              className={styles.overviewContent}
              initial={{ opacity: 0, y: 30 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true }}
              transition={{ duration: 0.6 }}
            >
              <h2>INFORMATION & <br /><span className={styles.red}>CAPABILITIES</span></h2>
              <div className={styles.featuresGrid}>
                {coreFeatures.map((feature, i) => (
                  <motion.div 
                    key={i} 
                    className={styles.featureItem}
                    initial={{ opacity: 0, y: 20 }}
                    whileInView={{ opacity: 1, y: 0 }}
                    viewport={{ once: true }}
                    transition={{ duration: 0.5, delay: i * 0.1 }}
                  >
                    <div className={styles.fIcon}>{feature.icon}</div>
                    <h3>{feature.title}</h3>
                    <p>{feature.desc}</p>
                  </motion.div>
                ))}
              </div>
            </motion.div>
            <motion.div 
              className={styles.overviewImage}
              initial={{ opacity: 0, scale: 0.95 }}
              whileInView={{ opacity: 1, scale: 1 }}
              viewport={{ once: true }}
              transition={{ duration: 0.8 }}
            >
              <Image src="/kpro_daughterboard.png" alt="KPro Daughterboard" width={600} height={600} className={styles.hwImg} />
              <div className={styles.imageOverlay}></div>
            </motion.div>
          </div>
        </div>
      </section>

      {/* 3. ADVANCED FEATURES (SUBSCRIPTION) */}
      <section className={styles.advanced}>
        <div className={styles.container}>
          <motion.div 
            className={styles.advHeader}
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
          >
            <p>REV.4 EXCLUSIVE FEATURES (ACTIVE SUBSCRIPTION REQUIRED)</p>
            <h2>ADVANCED ENGINE <span className={styles.red}>MANAGEMENT</span></h2>
          </motion.div>
          <div className={styles.advGrid}>
            {advancedFeatures.map((adv, i) => (
              <motion.div 
                key={i} 
                className={`
                  ${styles.advCard} 
                  ${(i === 0 || i === 8) ? styles.advCardWide : ''} 
                  ${i === 1 ? styles.advCardTall : ''}
                `}
                initial={{ opacity: 0, scale: 0.95 }}
                whileInView={{ opacity: 1, scale: 1 }}
                viewport={{ once: true }}
                transition={{ duration: 0.5, delay: i * 0.1 }}
              >
                <div className={styles.cardImage}>
                   {adv.image && (
                     <Image 
                      src={adv.image} 
                      alt={adv.title} 
                      fill 
                      className={styles.advImg} 
                      sizes="(max-width: 768px) 100vw, 50vw"
                     />
                   )}
                   <div className={styles.cardOverlay}></div>
                </div>
                <div className={styles.cardContent}>
                   <h3>{adv.title}</h3>
                   <p>{adv.desc}</p>
                </div>
              </motion.div>
            ))}
          </div>
        </div>
      </section>

      {/* 4. COMPATIBILITY */}
      <section className={styles.compatibility}>
        <div className={styles.container}>
          <div className={styles.compGrid}>
            <motion.div 
              className={styles.compBox}
              initial={{ opacity: 0, x: -30 }}
              whileInView={{ opacity: 1, x: 0 }}
              viewport={{ once: true }}
            >
              <h2>FACTORY EQUIPPED</h2>
              <div className={styles.vList}>
                {factoryModels.map((m, i) => (
                  <div key={i} className={styles.vItem}>
                    <span>{m.name}</span>
                    <span className={styles.vTag}>{m.years}</span>
                  </div>
                ))}
              </div>
            </motion.div>
            <motion.div 
              className={styles.compBox}
              initial={{ opacity: 0, x: 30 }}
              whileInView={{ opacity: 1, x: 0 }}
              viewport={{ once: true }}
            >
              <h2>COMPATIBLE WITH VEHICLES AFTER ECU REPLACEMENT</h2>
              <div className={styles.vList}>
                {replacementModels.map((m, i) => (
                  <div key={i} className={styles.vItem}>
                    <span>{m.name}</span>
                    <span className={styles.vTag}>{m.years}</span>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: '2rem', display: 'flex', gap: '1rem', color: '#ff4444', fontSize: '0.75rem', lineHeight: '1.5' }}>
                <AlertTriangle size={24} style={{ flexShrink: 0 }} />
                <p>The OEM ECUs in these vehicles are not compatible with the KPro daughterboard. Installation is only possible by replacing the original ECU with one from the vehicles listed in the Factory Equipped section.</p>
              </div>
            </motion.div>
          </div>

          <motion.div 
            style={{ marginTop: '4rem', padding: '3rem', backgroundColor: 'var(--secondary)', borderRadius: '4px', border: '1px solid var(--border)' }}
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
          >
            <h3 style={{ fontSize: '1rem', marginBottom: '1.5rem', fontWeight: 900 }}>SUPPORTED K-SERIES ECU BOARDS</h3>
            <div style={{ display: 'flex', gap: '3rem', alignItems: 'center', flexWrap: 'wrap' }}>
              <div style={{ flex: 1, minWidth: '300px' }}>
                <p style={{ color: '#888', fontSize: '0.85rem', marginBottom: '1.5rem' }}>The following ECU revisions based on the OKI 66Q592 MCU are supported. Board version is marked on the ECU PCB.</p>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '2rem' }}>
                  {ecuRevisions.map((rev, i) => (
                    <div key={i} style={{ padding: '1.5rem', border: '1px solid var(--border)', borderRadius: '4px' }}>
                      <p style={{ fontSize: '0.65rem', color: '#555', fontWeight: 800, marginBottom: '0.5rem' }}>BOARD REVISION</p>
                      <p style={{ fontFamily: 'monospace', fontWeight: 900, fontSize: '1.1rem' }}>{rev.name}</p>
                    </div>
                  ))}
                </div>
              </div>
              <div style={{ flex: 1, minWidth: '300px', position: 'relative', height: '250px' }}>
                <Image src="/kpro_ecu_board.jpg" alt="ECU PCB Revision" fill style={{ objectFit: 'contain' }} />
              </div>
            </div>
          </motion.div>
        </div>
      </section>

      {/* 5. TECH SUITE / INSTALLATION */}
      <section ref={guidesRef} className={styles.techSuite}>
        <div className={styles.container}>
          <motion.div 
            className={styles.techHeader}
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
          >
            <h2>TECHNICAL <span className={styles.red}>INTELLIGENCE</span></h2>
          </motion.div>

          <div className={styles.guideGrid}>
             <motion.div 
              className={styles.guideCard}
              initial={{ opacity: 0, scale: 0.9 }}
              whileInView={{ opacity: 1, scale: 1 }}
              viewport={{ once: true }}
             >
                <div className={styles.cardBg}>
                   <Image src="/tech_install.png" alt="Hardware Installation" fill className={styles.bgImg} />
                   <div className={styles.cardOverlay}></div>
                </div>
                <div className={styles.guideContent}>
                   <div className={styles.guideIconBox}><Settings size={32} /></div>
                   <h3>Hardware Installation</h3>
                   <p>Comprehensive step-by-step soldering and seating guide for the KPro daughterboard onto your ECU PCB.</p>
                   <Link href="/KPro-HW-Install" className={styles.guideBtn} style={{ display: 'inline-block' }}>VIEW INSTALL GUIDE</Link>
                </div>
             </motion.div>

             <motion.div 
              className={styles.guideCard}
              initial={{ opacity: 0, scale: 0.9 }}
              whileInView={{ opacity: 1, scale: 1 }}
              viewport={{ once: true }}
              transition={{ delay: 0.1 }}
             >
                <div className={styles.cardBg}>
                   <Image src="/tech_bluetooth.png" alt="Bluetooth Config" fill className={styles.bgImg} />
                   <div className={styles.cardOverlay}></div>
                </div>
                <div className={styles.guideContent}>
                   <div className={styles.guideIconBox}><Bluetooth size={32} /></div>
                   <h3>Bluetooth Config</h3>
                   <p>Wireless connection protocols, pairing procedures, and list of compatible mobile tuning applications.</p>
                   <button className={styles.guideBtn}>CONNECTION GUIDE</button>
                </div>
             </motion.div>

             <motion.div 
              className={styles.guideCard}
              initial={{ opacity: 0, scale: 0.9 }}
              whileInView={{ opacity: 1, scale: 1 }}
              viewport={{ once: true }}
              transition={{ delay: 0.2 }}
             >
                <div className={styles.cardBg}>
                   <Image src="/tech_leds.png" alt="LED Indicators" fill className={styles.bgImg} />
                   <div className={styles.cardOverlay}></div>
                </div>
                <div className={styles.guideContent}>
                   <div className={styles.guideIconBox}><Activity size={32} /></div>
                   <h3>Board LEDs Meaning</h3>
                   <p>Decipher onboard DIAG LED patterns for rapid troubleshooting and system status verification.</p>
                   <button className={styles.guideBtn}>DIAGNOSTIC KEYS</button>
                </div>
             </motion.div>
          </div>
        </div>
      </section>

      {/* 6. DOWNLOADS & SOFTWARE HUB */}
      <section ref={downloadRef} className={styles.downloads}>
        <div className={styles.container}>
          <motion.div 
            className={styles.dlHeader}
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
          >
            <h2>SUPPORTED <span className={styles.red}>SOFTWARE</span></h2>
          </motion.div>
          
          <div className={styles.dlDashboard}>
            <motion.div 
              className={styles.dlCard}
              initial={{ opacity: 0, scale: 0.95 }}
              whileInView={{ opacity: 1, scale: 1 }}
              viewport={{ once: true }}
              transition={{ delay: 0.1 }}
              style={{ gridColumn: '1 / -1', maxWidth: '600px', margin: '0 auto' }}
            >
              <div className={styles.dlIconBox}><Settings size={32} /></div>
              <h3>KPro Manager</h3>
              
              <div style={{ position: 'relative', width: '100%', height: '300px', margin: '2rem 0', borderRadius: '8px', overflow: 'hidden' }}>
                <Image src="/kpro_manager.png" alt="KPro Manager Software" fill style={{ objectFit: 'contain' }} />
              </div>

              <p>Get Latest KPro Manager Software for live engine tuning and datalogging. Standard installation package for all K-Series platforms.</p>
              
              <a 
                href="/files/KProSetup.rar" 
                className={styles.dlBtn}
                download
              >
                <Download size={18} />
                DOWNLOAD SOFTWARE
              </a>
            </motion.div>
          </div>
        </div>
      </section>
    </div>
  );
}

