import React, { useState, useEffect, useRef } from 'react';
import { Link } from 'react-router-dom';
import { Shield, Lock, Award, Activity, ArrowRight, Eye, RefreshCw, Cpu, Users, CheckCircle, AlertTriangle, ShieldCheck } from 'lucide-react';
import './Home.css';

export default function Home() {
  const [activeVertical, setActiveVertical] = useState(0);
  const cardRefs = useRef([]);

  useEffect(() => {
    const handleScroll = () => {
      let currentActive = 0;
      cardRefs.current.forEach((ref, idx) => {
        if (!ref) return;
        const rect = ref.getBoundingClientRect();
        // Sticking trigger line is roughly top: 140px + index * 24px plus a small margin
        const triggerPos = 140 + idx * 24 + 40;
        if (rect.top <= triggerPos) {
          currentActive = idx;
        }
      });
      setActiveVertical(currentActive);
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  const selectVertical = (index) => {
    const targetRef = cardRefs.current[index];
    if (targetRef) {
      const rect = targetRef.getBoundingClientRect();
      const targetScroll = window.scrollY + rect.top - (140 + index * 24);
      window.scrollTo({
        top: targetScroll - 10,
        behavior: 'smooth'
      });
    }
  };

  const verticalsData = [
    {
      id: 'sme',
      title: 'SME Support',
      icon: <Users size={28} />,
      compliance: ['Essential 8', 'CIS Controls', 'NIST CSF', 'SOC 2 Ready', 'Third Party Risk Management', 'AI Auditing'],
      threats: ['Credential Phishing', 'Business Email Compromise (BEC)', 'Unmanaged Endpoint Risks'],
      solutions: ['vCISO Consulting', 'Mobile Device Management (MDM)', 'Staff Phishing Readiness Tests', 'Third Party Risk Management Program', 'Internal AI Auditing'],
      highlighted: false,
    },
    {
      id: 'fintech',
      title: 'Fintech Grade',
      icon: <Lock size={28} />,
      compliance: ['SOC 2 Type II', 'GLBA Compliance', 'PCI DSS', 'ISO 27001', 'Third Party Risk Management', 'AI Auditing'],
      threats: ['Ledger Tampering', 'API-Based Transaction Fraud', 'Access Key Token Leakage'],
      solutions: ['Data Field Encryption', 'Strict IAM Boundaries', 'Hardware Security Module (HSM)', 'Third Party Risk Management Program', 'Internal AI Auditing'],
      highlighted: true,
    },
    {
      id: 'healthcare',
      title: 'Healthcare',
      icon: <Activity size={28} />,
      compliance: ['HIPAA Protection', 'HITRUST Readiness', 'ISO 27001 Audit', 'SOC 2 Coverage', 'Third Party Risk Management', 'AI Auditing'],
      threats: ['Ransomware Threat Vector', 'Protected Health Info (PHI) Leaks', 'Telemedicine API Exposure'],
      solutions: ['Row-Level PHI Encryption', 'Database Audit Logging', 'Secure Failover Architectures', 'Third Party Risk Management Program', 'Internal AI Auditing'],
      highlighted: true,
    },
    {
      id: 'saas',
      title: 'SaaS Cloud',
      icon: <Cpu size={28} />,
      compliance: ['SOC 2 Compliance', 'ISO 27001 Certification', 'GDPR Data Policies', 'AI Audit Standards', 'Third Party Risk Management', 'AI Auditing'],
      threats: ['CI/CD Pipeline Exploits', 'Cloud Configuration Drift', 'Multi-Tenant Isolation Flaws'],
      solutions: ['Automated Pipeline Scans', 'Cloud Posture Managers (CSPM)', 'Microsegmentation Policy', 'Third Party Risk Management Program', 'Internal AI Auditing'],
      highlighted: false,
    },
  ];

  return (
    <div className="home-page">
      {/* Hero Section */}
      <section className="hero-section">
        <div className="hero-gradient-overlay" />
        <div className="hero-bg-animation">
          <div className="animated-blob blob-1"></div>
          <div className="animated-blob blob-2"></div>
          <div className="animated-blob blob-3"></div>
          <div className="grid-lines-overlay"></div>
        </div>
        <div className="container hero-container animate-fade-in-up">
          <div className="hero-content">
            <div className="hero-badge">
              <span className="badge-pulse"></span>
              <span>24/7 Enterprise-Grade Cyber Protection</span>
            </div>
            <h1 className="hero-title">
              Robust, Compliant, and Resilient IT—Powered by <span className="highlight">Next-Gen Cybersecurity</span>
            </h1>
            <p className="hero-subtitle">
              Cynomos helps enterprises, fintechs, and high-growth startups strengthen security postures, maintain constant compliance, and keep mission-critical infrastructure running.
            </p>
            <div className="hero-actions">
              <Link to="/contact" className="btn btn-primary">
                Book Security Evaluation <ArrowRight size={18} />
              </Link>
              <Link to="/services" className="btn btn-secondary">
                Explore Our Services
              </Link>
            </div>
            <div className="hero-trust-indicators">
              <span className="trust-item"><CheckCircle size={16} className="gold-text" /> SOC 2 Ready</span>
              <span className="trust-item"><CheckCircle size={16} className="gold-text" /> HIPAA Compliant</span>
              <span className="trust-item"><CheckCircle size={16} className="gold-text" /> ISO 27001</span>
              <span className="trust-item"><CheckCircle size={16} className="gold-text" /> PCI DSS</span>
              <span className="trust-item"><CheckCircle size={16} className="gold-text" /> AI Audit</span>
            </div>
          </div>
          <div className="hero-graphic-redesign">
            <div className="mock-dashboard-wrapper">
              <div className="dashboard-header">
                <div className="window-dots">
                  <span className="dot red"></span>
                  <span className="dot yellow"></span>
                  <span className="dot green"></span>
                </div>
                <span className="dashboard-title">Cynomos Security Center v1.4</span>
              </div>
              <div className="dashboard-body">
                <div className="db-row">
                  <div className="db-col">
                    <span className="db-label">Network Status</span>
                    <span className="db-value text-green">SECURE</span>
                  </div>
                  <div className="db-col">
                    <span className="db-label">Endpoints</span>
                    <span className="db-value">1,248 Active</span>
                  </div>
                </div>
                <div className="db-status-bar">
                  <div className="status-progress-fill"></div>
                </div>
                <div className="db-console">
                  <div className="console-line text-gold">&gt; cynomos-agent --verify-compliance</div>
                  <div className="console-line">&gt; Initializing system integrity check...</div>
                  <div className="console-line text-green">&gt; SOC2 framework checks passed (142/142)</div>
                  <div className="console-line text-green">&gt; AWS Cloud configuration: Compliant</div>
                  <div className="console-line">&gt; Vulnerability scans: 0 issues found</div>
                  <div className="console-line pulse-line">&gt; Listening for threats on port 8080...</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Stats/Highlights Bar */}
      <section className="stats-section">
        <div className="container grid grid-4">
          <div className="stat-card">
            <h3 className="stat-num">99.9%</h3>
            <p className="stat-label">Infrastructure Uptime</p>
          </div>
          <div className="stat-card">
            <h3 className="stat-num">24/7</h3>
            <p className="stat-label">Active Monitoring</p>
          </div>
          <div className="stat-card">
            <h3 className="stat-num">100+</h3>
            <p className="stat-label">Compliance Audits Prepared</p>
          </div>
          <div className="stat-card">
            <h3 className="stat-num">0</h3>
            <p className="stat-label">Critical Data Breaches</p>
          </div>
        </div>
      </section>

      {/* Overview of services */}
      <section className="section section-alt home-services-overview">
        <div className="container">
          <div className="section-header">
            <span className="section-label">Expert Capabilities</span>
            <h2 className="section-title">Cybersecurity Services Tailored for Growth</h2>
            <p className="section-description">
              Secure your organization's digital assets and ensure compliance with regulatory frameworks using our remote-first execution model.
            </p>
          </div>

          <div className="grid grid-2 service-overview-grid">
            <div className="service-preview-card-redesign">
              <div className="service-icon-header">
                <div className="service-icon-circle gold">
                  <Eye size={24} />
                </div>
                <h3>Cyber Security Strategy & Advisory</h3>
              </div>
              <p>Strategic leadership and architecture designs mapped strictly to business objectives.</p>
              <div className="service-preview-tags">
                <span className="preview-tag">Threat Modeling</span>
                <span className="preview-tag">Cloud Security</span>
                <span className="preview-tag">Zero-Trust IAM</span>
              </div>
              <Link to="/services" state={{ activeTab: 0 }} className="learn-more-link">
                Learn Details <ArrowRight size={16} />
              </Link>
            </div>

            <div className="service-preview-card-redesign">
              <div className="service-icon-header">
                <div className="service-icon-circle gold">
                  <RefreshCw size={24} />
                </div>
                <h3>Security Transformation</h3>
              </div>
              <p>Active engineering to modernize infrastructure, automate compliance controls, and optimize resilience.</p>
              <div className="service-preview-tags">
                <span className="preview-tag">Automated Remediation</span>
                <span className="preview-tag">IaC Hardening</span>
                <span className="preview-tag">Secrets Manager</span>
              </div>
              <Link to="/services" state={{ activeTab: 1 }} className="learn-more-link">
                Learn Details <ArrowRight size={16} />
              </Link>
            </div>

            <div className="service-preview-card-redesign">
              <div className="service-icon-header">
                <div className="service-icon-circle gold">
                  <Shield size={24} />
                </div>
                <h3>Risk Management & Audits</h3>
              </div>
              <p>Penetration testing, vulnerability scanning, and risk assessment audits to spot vulnerabilities.</p>
              <div className="service-preview-tags">
                <span className="preview-tag">Penetration Testing</span>
                <span className="preview-tag">API Endpoint Checks</span>
                <span className="preview-tag">Vulnerability Scans</span>
              </div>
              <Link to="/services" state={{ activeTab: 2 }} className="learn-more-link">
                Learn Details <ArrowRight size={16} />
              </Link>
            </div>

            <div className="service-preview-card-redesign">
              <div className="service-icon-header">
                <div className="service-icon-circle gold">
                  <Award size={24} />
                </div>
                <h3>Compliance & GRC Consulting</h3>
              </div>
              <p>Direct prep for major certifications including SOC2, HIPAA, ISO 27001, and customized AI auditing.</p>
              <div className="service-preview-tags">
                <span className="preview-tag">SOC 2 Type II</span>
                <span className="preview-tag">HIPAA / HITRUST</span>
                <span className="preview-tag">ISO 27001 Readiness</span>
              </div>
              <Link to="/services" state={{ activeTab: 3 }} className="learn-more-link">
                Learn Details <ArrowRight size={16} />
              </Link>
            </div>
          </div>
        </div>
      </section>

      {/* Target Verticals CTA */}
      <section className="section home-industries-cta">
        <div className="container home-industries-inner grid grid-2">
          {/* Left Sticky Column */}
          <div className="sticky-timeline-container">
            <span className="section-label">Industries We Serve</span>
            <h2 className="section-title">High-Trust Verticals</h2>
            <p>
              We design defense-grade security architectures that meet specific regulatory audits without slowing down operations. Click a vertical to navigate directly, or scroll through the profiles.
            </p>

            <div className="vertical-timeline-tracker">
              <div className="timeline-progress-line">
                <div 
                  className="timeline-progress-fill" 
                  style={{ height: `${(activeVertical / 3) * 100}%` }}
                ></div>
              </div>
              <div className="timeline-nodes">
                {verticalsData.map((vertical, idx) => (
                  <button
                    key={vertical.id}
                    className={`timeline-node-btn ${activeVertical === idx ? 'active' : ''}`}
                    onClick={() => selectVertical(idx)}
                  >
                    <span className="timeline-index">0{idx + 1}</span>
                    <div className="node-text">
                      <span className="node-title">{vertical.title}</span>
                      <span className="node-sub">
                        {idx === 0 && 'Essential 8 & SOC 2'}
                        {idx === 1 && 'SOC 2, PCI DSS & GLBA'}
                        {idx === 2 && 'HIPAA & HITRUST'}
                        {idx === 3 && 'ISO 27001 & AI Auditing'}
                      </span>
                    </div>
                  </button>
                ))}
              </div>
            </div>
            
            <Link to="/industries" className="btn btn-primary cta-btn-margin">
              View Industry Solutions
            </Link>
          </div>

          {/* Right Scroll Stack Column */}
          <div className="industries-cta-scroll-stack">
            {verticalsData.map((vertical, idx) => (
              <div 
                key={vertical.id} 
                ref={el => cardRefs.current[idx] = el}
                className={`scroll-stack-card ${idx === activeVertical ? 'active-card' : ''} ${vertical.highlighted ? 'highlighted' : ''}`}
                style={{ 
                  '--card-index': idx,
                  zIndex: idx + 1
                }}
              >
                <div className="vertical-card-header">
                  <div className="vertical-card-icon-wrapper">
                    {vertical.icon}
                  </div>
                  <div className="header-title-meta">
                    <h4>{vertical.title}</h4>
                    <span className="vciso-verified-badge">vCISO Verified</span>
                  </div>
                </div>
                
                <div className="vertical-card-details">
                  <div className="vertical-detail-group">
                    <span className="detail-group-label">Standards & Audits Compliance</span>
                    <div className="vertical-badge-container">
                      {vertical.compliance.map((std, sIdx) => (
                        <span key={sIdx} className="vertical-badge">{std}</span>
                      ))}
                    </div>
                  </div>
                  
                  <div className="card-split-details-grid">
                    <div className="vertical-detail-group">
                      <span className="detail-group-label warning">Key Vulnerabilities & Threats</span>
                      <div className="micro-cards-stack">
                        {vertical.threats.map((threat, tIdx) => (
                          <div key={tIdx} className="micro-detail-card threat-card">
                            <AlertTriangle size={14} className="warning-icon" />
                            <span>{threat}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                    
                    <div className="vertical-detail-group">
                      <span className="detail-group-label success">Cynomos Security Protections</span>
                      <div className="micro-cards-stack">
                        {vertical.solutions.map((sol, solIdx) => (
                          <div key={solIdx} className="micro-detail-card solution-card">
                            <ShieldCheck size={14} className="success-icon" />
                            <span>{sol}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}
