import React, { useState, useEffect, useCallback } from 'react';
import { X, ArrowRight, ArrowLeft, BarChart3, Target, Users, Zap, Globe, Shield, TrendingUp, Settings } from 'lucide-react';

// โ”€โ”€โ”€ Brand colors (match LandingPage) โ”€โ”€โ”€
const COLORS = {
  bg: '#0a0f1a',
  green: '#00A846',
  blue: '#00AECB',
  lime: '#C6F24E',
  cardBg: 'rgba(255,255,255,0.04)',
};

// โ”€โ”€โ”€ Step data per audience โ”€โ”€โ”€
interface Step {
  title: string;
  desc: string;
  icon: React.ElementType;
  highlight: string;
  screenshot?: string;
}

interface AudienceData {
  title: string;
  steps: Step[];
  cta: string;
}

const AUDIENCE_WALKTHROUGHS: Record<string, AudienceData> = {
  single: {
    title: 'Command Center for owner-operators',
    steps: [
      {
        title: 'Everything in one view',
        desc: 'Your CRM, ad spend, and books in a single dashboard. No tab-switching between HubSpot, Google Ads, and QuickBooks โ€” see what matters this week at a glance.',
        icon: BarChart3,
        highlight: 'Unified Dashboard',
      },
      {
        title: 'Revenue that actually makes sense',
        desc: 'Forecasting built for small teams. See your likely, best, and conservative revenue bands over the next 6 months โ€” no data science degree required.',
        icon: TrendingUp,
        highlight: 'Revenue Forecasting',
      },
      {
        title: 'Know which ads are paying',
        desc: 'Track your Google and Facebook ad spend against actual conversions. See which campaigns bring real leads and which ones burn cash, updated in real time.',
        icon: Zap,
        highlight: 'Ad Performance Tracking',
      },
      {
        title: 'Integrations that just work',
        desc: 'Connect HubSpot, QuickBooks, Google Ads, Facebook Ads, Slack, and more in minutes. No API knowledge needed โ€” paste your credentials and you\'re live.',
        icon: Users,
        highlight: '10+ Integrations',
      },
    ],
    cta: 'Start your free trial',
  },
  multi: {
    title: 'Command Center for multi-location operators',
    steps: [
      {
        title: 'Compare markets at a glance',
        desc: 'Side-by-side market comparison with close rate, CAC, margin, and pipeline value. Instantly spot which location is thriving and which needs coaching.',
        icon: Globe,
        highlight: 'Multi-Market Analytics',
      },
      {
        title: 'Smart coaching that finds problems first',
        desc: 'Automated health scores for every market and rep. Get severity alerts before a problem becomes a quarterly miss. Dismiss, track, and act โ€” all from one dashboard.',
        icon: Target,
        highlight: 'Smart Coaching',
      },
      {
        title: 'Scale with confidence',
        desc: 'ROAS, LTV:CAC, and budget recommendations across all locations. Know exactly where to shift spend for maximum revenue lift, not gut feeling.',
        icon: TrendingUp,
        highlight: 'Scale Optimization',
      },
      {
        title: 'Root cause, not just symptoms',
        desc: 'Revenue waterfall and drill-down trees show you why a market is underperforming โ€” bad close rate, high CAC, or low volume โ€” so you fix the real problem.',
        icon: Zap,
        highlight: 'Strategic Intelligence',
      },
    ],
    cta: 'See it in action',
  },
  enterprise: {
    title: 'Command Center for portfolios & enterprises',
    steps: [
      {
        title: 'Roll up every operating company',
        desc: 'Single KPI taxonomy across all portfolio companies. Compare performance, benchmark against peers, and identify value creation opportunities at scale.',
        icon: BarChart3,
        highlight: 'Portfolio Roll-up',
      },
      {
        title: 'Cascading goals that actually cascade',
        desc: 'Set org-level targets that automatically break down to department, team, and rep level. Watch progress roll up in real time โ€” no manual spreadsheet tracking.',
        icon: Target,
        highlight: 'Cascading Goals',
      },
      {
        title: 'White-label and SSO built in',
        desc: 'Custom branding, colors, logo, and domain per company. SSO/SAML for enterprise security. Give each brand its own portal while maintaining full oversight.',
        icon: Shield,
        highlight: 'Enterprise Features',
      },
      {
        title: 'Custom connectors for your stack',
        desc: 'Beyond our 10+ built-in integrations, the generic REST API connector lets you pull from any system your portfolio companies use. ServiceTitan, Salesforce, custom ERPs โ€” all wired.',
        icon: Settings,
        highlight: 'Custom Connectors',
      },
    ],
    cta: 'Book a demo',
  },
};

interface FeatureModalProps {
  audience: 'single' | 'multi' | 'enterprise';
  onClose: () => void;
}

export function FeatureModal({ audience, onClose }: FeatureModalProps) {
  const [currentStep, setCurrentStep] = useState(0);
  const data = AUDIENCE_WALKTHROUGHS[audience];

  const nextStep = useCallback(() => {
    if (data && currentStep < data.steps.length - 1) {
      setCurrentStep((prev) => prev + 1);
    }
  }, [currentStep, data]);

  const prevStep = useCallback(() => {
    if (currentStep > 0) {
      setCurrentStep((prev) => prev - 1);
    }
  }, [currentStep]);

  // Close on Escape
  useEffect(() => {
    const handleKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', handleKey);
    return () => window.removeEventListener('keydown', handleKey);
  }, [onClose]);

  // Lock body scroll when open
  useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);

  if (!data) return null;

  const step = data.steps[currentStep];
  const StepIcon = step.icon;

  return (
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center p-4"
      role="dialog"
      aria-modal="true"
    >
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/80 backdrop-blur-sm"
        onClick={onClose}
      />

      {/* Modal */}
      <div
        className="relative w-full max-w-2xl rounded-3xl border border-white/10 overflow-hidden"
        style={{ background: COLORS.bg }}
      >
        {/* Close button */}
        <button
          onClick={onClose}
          className="absolute top-4 right-4 z-10 p-2 rounded-full text-white/50 hover:text-white hover:bg-white/10 transition-colors min-w-[44px] min-h-[44px] flex items-center justify-center"
          aria-label="Close"
        >
          <X size={20} />
        </button>

        {/* Header */}
        <div className="px-8 pt-8 pb-4">
          <p className="text-xs font-semibold uppercase tracking-wider mb-2" style={{ color: COLORS.blue }}>
            Walkthrough ยท Step {currentStep + 1} of {data.steps.length}
          </p>
          <h2 className="text-2xl md:text-3xl font-black text-white">
            {data.title}
          </h2>
        </div>

        {/* Progress bar */}
        <div className="px-8 mb-6">
          <div className="h-1 rounded-full bg-white/10 overflow-hidden">
            <div
              className="h-full rounded-full transition-all duration-300"
              style={{
                background: `linear-gradient(90deg, ${COLORS.green}, ${COLORS.blue})`,
                width: `${((currentStep + 1) / data.steps.length) * 100}%`,
              }}
            />
          </div>
        </div>

        {/* Step content */}
        <div className="px-8 pb-6">
          <div className="flex gap-5">
            {/* Icon */}
            <div
              className="flex-shrink-0 w-14 h-14 rounded-2xl flex items-center justify-center"
              style={{ background: 'rgba(0,168,70,0.15)' }}
            >
              <StepIcon size={24} style={{ color: COLORS.green }} />
            </div>

            {/* Text */}
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 mb-1">
                <span
                  className="text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full"
                  style={{ background: 'rgba(0,174,203,0.15)', color: COLORS.blue }}
                >
                  {step.highlight}
                </span>
              </div>
              <h3 className="text-lg font-bold text-white mb-2">{step.title}</h3>
              <p className="text-sm text-white/60 leading-relaxed">{step.desc}</p>
            </div>
          </div>
        </div>

        {/* Step dots */}
        <div className="px-8 pb-4 flex items-center justify-center gap-2">
          {data.steps.map((_, i) => (
            <button
              key={i}
              onClick={() => setCurrentStep(i)}
              className={`w-2 h-2 rounded-full transition-all ${
                i === currentStep ? 'bg-white' : 'bg-white/20 hover:bg-white/40'
              }`}
              aria-label={`Go to step ${i + 1}`}
            />
          ))}
        </div>

        {/* Navigation */}
        <div className="px-8 pb-8 flex items-center justify-between">
          <button
            onClick={prevStep}
            disabled={currentStep === 0}
            className="flex items-center gap-2 text-sm text-white/50 hover:text-white transition-colors disabled:opacity-30 disabled:cursor-not-allowed min-h-[44px] px-3 py-2 rounded-lg"
          >
            <ArrowLeft size={16} />
            Back
          </button>

          {currentStep < data.steps.length - 1 ? (
            <button
              onClick={nextStep}
              className="flex items-center gap-2 text-sm font-semibold min-h-[44px] px-5 py-2.5 rounded-xl transition-colors"
              style={{ background: COLORS.green, color: 'white' }}
            >
              Next
              <ArrowRight size={16} />
            </button>
          ) : (
            <button
              onClick={onClose}
              className="flex items-center gap-2 text-sm font-semibold min-h-[44px] px-5 py-2.5 rounded-xl transition-colors"
              style={{ background: COLORS.blue, color: 'white' }}
            >
              {data.cta}
              <ArrowRight size={16} />
            </button>
          )}
        </div>
      </div>
    </div>
  );
}