
'use client';

import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { TrustBadge } from '@/components/trust-badge';
import { LocationPicker } from '@/components/location-picker';
import { ChatbotWidget } from '@/components/chatbot/chatbot-widget';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import Image from 'next/image';
import Link from 'next/link';
import { useState } from 'react';
import { 
  ArrowRight, 
  CheckCircle, 
  MapPin, 
  Star, 
  Phone, 
  Mail,
  Shield,
  Clock,
  Award,
  TrendingUp,
  MessageCircle,
  Upload,
  FileText,
  Camera,
  Home,
  Droplets,
  Sun,
  Waves,
  Fence,
  Building,
  Construction,
  Video
} from 'lucide-react';
import { toast } from 'sonner';

interface Testimonial {
  name: string;
  location: string;
  rating: number;
  text: string;
  project: string;
}

import type { ServiceCategory } from '@/lib/services-config';

interface RegionalLandingPageProps {
  region: string;
  flag: string;
  contractor: string;
  heroTitle: string;
  heroDescription: string;
  currency: string;
  phonePrefix: string;
  contactPhone?: string;
  features: string[];
  testimonials: Testimonial[];
  popularServices: string[];
  cities: string[];
  detailedServices?: ServiceCategory[];
}

export function RegionalLandingPage({
  region,
  flag,
  contractor,
  heroTitle,
  heroDescription,
  currency,
  phonePrefix,
  contactPhone,
  features,
  testimonials,
  popularServices,
  cities,
  detailedServices
}: RegionalLandingPageProps) {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    serviceType: '',
    address: '',
    latitude: null as number | null,
    longitude: null as number | null
  });
  const [files, setFiles] = useState<File[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showMap, setShowMap] = useState(false);
  const [mapCenter, setMapCenter] = useState({ lat: -26.2041, lng: 28.0473 }); // Johannesburg default
  const [currentTestimonial, setCurrentTestimonial] = useState(0);
  const [showSuccessModal, setShowSuccessModal] = useState(false);
  const [submittedEmail, setSubmittedEmail] = useState('');

  // Service type icons mapping
  const getServiceIcon = (service: string) => {
    const serviceLower = service.toLowerCase();
    if (serviceLower.includes('roof')) return <Home className="w-6 h-6" />;
    if (serviceLower.includes('gutter')) return <Droplets className="w-6 h-6" />;
    if (serviceLower.includes('solar')) return <Sun className="w-6 h-6" />;
    if (serviceLower.includes('pool')) return <Waves className="w-6 h-6" />;
    if (serviceLower.includes('irrigation')) return <Droplets className="w-6 h-6" />;
    if (serviceLower.includes('paving') || serviceLower.includes('driveway')) return <Construction className="w-6 h-6" />;
    if (serviceLower.includes('fence') || serviceLower.includes('wall')) return <Fence className="w-6 h-6" />;
    if (serviceLower.includes('renovation')) return <Building className="w-6 h-6" />;
    return <Building className="w-6 h-6" />;
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFiles = Array.from(e.target.files || []);
    const validFiles = selectedFiles.filter(file => {
      const isValidType = 
        file.type === 'application/pdf' ||
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.name.endsWith('.dwg');
      
      const isValidSize = file.size <= 10 * 1024 * 1024; // 10MB max
      
      if (!isValidType) {
        toast.error(`${file.name} is not a valid file type. Please upload PDF, DWG, or images.`);
        return false;
      }
      if (!isValidSize) {
        toast.error(`${file.name} exceeds 10MB size limit.`);
        return false;
      }
      return true;
    });
    
    setFiles(prev => [...prev, ...validFiles]);
  };

  const removeFile = (index: number) => {
    setFiles(prev => prev.filter((_, i) => i !== index));
  };

  const handleLocationSelect = (lat: number, lng: number, address: string) => {
    setFormData({ ...formData, latitude: lat, longitude: lng, address });
    setShowMap(false);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.latitude || !formData.longitude) {
      toast.error('Please select your location on the map');
      return;
    }
    
    setIsSubmitting(true);

    try {
      // Create FormData for file uploads
      const submitData = new FormData();
      submitData.append('name', formData.name);
      submitData.append('email', formData.email);
      submitData.append('phone', formData.phone);
      submitData.append('serviceType', formData.serviceType);
      submitData.append('address', formData.address);
      submitData.append('latitude', formData.latitude.toString());
      submitData.append('longitude', formData.longitude.toString());
      submitData.append('source', `regional-${region.toLowerCase().replace(/\s+/g, '-')}`);
      submitData.append('priority', 'HIGH'); // High priority for landing page leads
      
      // Append files
      files.forEach((file) => {
        submitData.append('files', file);
      });

      const response = await fetch('/api/leads', {
        method: 'POST',
        body: submitData
      });

      if (response.ok) {
        const lead = await response.json();
        
        // Store email before resetting
        setSubmittedEmail(formData.email);
        
        // Show success modal
        setShowSuccessModal(true);
        
        // Reset form
        setFormData({ name: '', email: '', phone: '', serviceType: '', address: '', latitude: null, longitude: null });
        setFiles([]);
        
        // Show toast with CRM link
        toast.success('Quote request submitted successfully!', {
          description: 'Our team will contact you within 24 hours.',
          duration: 8000,
        });

        // Log success for tracking
        console.log('Lead created successfully:', lead.id);
      } else {
        const error = await response.json();
        console.error('Failed to create lead:', error);
        throw new Error(error.error || 'Failed to submit');
      }
    } catch (error) {
      console.error('Error submitting form:', error);
      toast.error('Failed to submit request. Please try again or call us directly.');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-brand-off-white to-white">
      {/* Navigation */}
      <nav className="border-b bg-white/80 backdrop-blur-md sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <Link href="/" className="flex items-center gap-3">
              <div className="relative w-10 h-10">
                <Image
                  src="/brand-logo.png"
                  alt="Quote2Contract"
                  fill
                  className="object-contain"
                />
              </div>
              <span className="text-xl font-bold text-brand-dark-blue">Quote2Contract</span>
            </Link>
            <div className="flex items-center gap-4">
              <Badge className="bg-gradient-to-r from-brand-green to-brand-teal text-white border-0">
                <span className="mr-2">{flag}</span>
                {region}
              </Badge>
              <Link href="/auth/signin">
                <Button variant="ghost" size="sm">Sign In</Button>
              </Link>
            </div>
          </div>
        </div>
      </nav>

      {/* Hero Section */}
      <section className="relative py-20 lg:py-32 overflow-hidden">
        {/* Background Image/Video */}
        <div className="absolute inset-0 bg-gradient-to-br from-brand-dark-blue/95 via-brand-teal/90 to-brand-green/85" />
        <div className="absolute inset-0 opacity-20">
          <div className="w-full h-full bg-[url('https://images.unsplash.com/photo-1504307651254-35680f356dfd?w=1920')] bg-cover bg-center" />
        </div>
        
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 relative z-10">
          <div className="grid lg:grid-cols-2 gap-12 items-center">
            <div className="space-y-8 text-white">
              <div className="flex items-center gap-3">
                <span className="text-6xl">{flag}</span>
                <div>
                  <p className="text-sm text-white/80 font-medium">Trusted in</p>
                  <h2 className="text-2xl font-bold">{region}</h2>
                </div>
              </div>
              
              <h1 className="text-5xl lg:text-6xl font-bold leading-tight">
                From Quote to Contract — Fast, Fair & Verified
              </h1>
              
              <p className="text-xl text-white/90">
                Get up to 3 free quotes from vetted local contractors in {region}.<br />
                <span className="font-semibold">Roofing • Renovations • Solar • Paving • More</span>
              </p>

              {/* Trust Badges */}
              <div className="flex flex-wrap gap-3">
                <Badge className="bg-white/20 backdrop-blur-sm text-white border-white/40 px-4 py-2">
                  ✅ NHBRC Registered
                </Badge>
                <Badge className="bg-white/20 backdrop-blur-sm text-white border-white/40 px-4 py-2">
                  🔒 Insurance Covered
                </Badge>
                <Badge className="bg-white/20 backdrop-blur-sm text-white border-white/40 px-4 py-2">
                  📜 COC Certified
                </Badge>
              </div>

              <div className="space-y-4">
                <div className="flex flex-wrap gap-4">
                  <Link href="#quote-form">
                    <Button size="lg" className="bg-brand-green hover:bg-brand-green/90 text-white shadow-xl">
                      Get Free Quote <ArrowRight className="ml-2 w-5 h-5" />
                    </Button>
                  </Link>
                  {contactPhone && (
                    <a 
                      href={`https://wa.me/${contactPhone.replace(/\+/g, '').replace(/\s/g, '')}`}
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      <Button size="lg" variant="outline" className="border-white text-white hover:bg-white hover:text-brand-dark-blue">
                        <MessageCircle className="mr-2 w-5 h-5" />
                        Chat on WhatsApp
                      </Button>
                    </a>
                  )}
                </div>
              </div>

              <div className="pt-4">
                <p className="text-sm text-white/70 mb-2">🏆 Verified Contractors Since 2020</p>
                <TrustBadge variant="compact" />
              </div>
            </div>

            {/* Quote Form Card */}
            <Card id="quote-form" className="p-8 shadow-brand-lg border-2 border-brand-green/20 bg-white">
              <h3 className="text-2xl font-bold text-brand-dark-blue mb-2">
                Get Your Free Quote — No Hidden Fees
              </h3>
              <p className="text-sm text-gray-500 mb-6">Fill out the form below and we&apos;ll get back to you</p>
              
              <form onSubmit={handleSubmit} className="space-y-4">
                <div>
                  <label className="text-sm font-medium text-gray-700 mb-1 block">Full Name</label>
                  <Input
                    placeholder="John Smith"
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    required
                  />
                </div>
                
                <div>
                  <label className="text-sm font-medium text-gray-700 mb-1 block">Email Address</label>
                  <Input
                    type="email"
                    placeholder="john@example.com"
                    value={formData.email}
                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    required
                  />
                </div>
                
                <div>
                  <label className="text-sm font-medium text-gray-700 mb-1 block">Phone Number</label>
                  <Input
                    type="tel"
                    placeholder={phonePrefix}
                    value={formData.phone}
                    onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                    required
                  />
                </div>

                <div>
                  <label className="text-sm font-medium text-gray-700 mb-1 block">Select Service Type</label>
                  <Select value={formData.serviceType} onValueChange={(value) => setFormData({ ...formData, serviceType: value })}>
                    <SelectTrigger>
                      <SelectValue placeholder="Choose a service..." />
                    </SelectTrigger>
                    <SelectContent>
                      {popularServices.map((service, index) => (
                        <SelectItem key={index} value={service}>
                          {service}
                        </SelectItem>
                      ))}
                      <SelectItem value="other">Other</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                
                <div>
                  <label className="text-sm font-medium text-gray-700 mb-1 block">Project Location</label>
                  <div className="space-y-2">
                    <Button
                      type="button"
                      variant="outline"
                      className="w-full justify-start text-left"
                      onClick={() => setShowMap(true)}
                    >
                      <MapPin className="mr-2 w-4 h-4" />
                      {formData.address || 'Click to select location on map'}
                    </Button>
                    {formData.address && (
                      <p className="text-xs text-gray-500 flex items-center gap-1">
                        <CheckCircle className="w-3 h-3 text-brand-green" />
                        Location selected
                      </p>
                    )}
                  </div>
                </div>

                {/* File Upload Section */}
                <div>
                  <label className="text-sm font-medium text-gray-700 mb-1 block">
                    Upload Photos or Plans (optional)
                  </label>
                  <div className="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center hover:border-brand-green transition-colors">
                    <input
                      type="file"
                      multiple
                      accept=".pdf,.dwg,.jpg,.jpeg,.png"
                      onChange={handleFileChange}
                      className="hidden"
                      id="file-upload"
                    />
                    <label htmlFor="file-upload" className="cursor-pointer">
                      <Upload className="w-8 h-8 text-gray-400 mx-auto mb-2" />
                      <p className="text-sm text-gray-600">
                        <span className="text-brand-green font-semibold">Click to upload</span> or drag and drop
                      </p>
                      <p className="text-xs text-gray-500 mt-1">
                        PDF, DWG, or images (max 10MB each)
                      </p>
                    </label>
                  </div>
                  
                  {/* File List */}
                  {files.length > 0 && (
                    <div className="mt-3 space-y-2">
                      {files.map((file, index) => (
                        <div key={index} className="flex items-center justify-between p-2 bg-gray-50 rounded border">
                          <div className="flex items-center gap-2 flex-1 min-w-0">
                            {file.type.includes('image') ? (
                              <Camera className="w-4 h-4 text-brand-green flex-shrink-0" />
                            ) : (
                              <FileText className="w-4 h-4 text-brand-green flex-shrink-0" />
                            )}
                            <span className="text-sm text-gray-700 truncate">{file.name}</span>
                            <span className="text-xs text-gray-500 flex-shrink-0">
                              ({(file.size / 1024 / 1024).toFixed(2)} MB)
                            </span>
                          </div>
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={() => removeFile(index)}
                            className="text-red-500 hover:text-red-700 hover:bg-red-50 flex-shrink-0"
                          >
                            ✕
                          </Button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
                
                <Button 
                  type="submit" 
                  className="w-full bg-brand-green hover:bg-brand-green/90 text-white py-6 text-lg font-semibold"
                  disabled={isSubmitting}
                >
                  {isSubmitting ? 'Submitting...' : 'Get My Free Quote'}
                  <ArrowRight className="ml-2 w-5 h-5" />
                </Button>

                {/* Trust Indicators Below Button */}
                <div className="pt-3 space-y-2 border-t">
                  <div className="flex items-center gap-2 text-sm text-gray-600">
                    <Clock className="w-4 h-4 text-brand-green" />
                    <span>Average response time: <strong>under 30 minutes</strong></span>
                  </div>
                  <div className="flex items-center gap-2 text-sm text-gray-600">
                    <Shield className="w-4 h-4 text-brand-green" />
                    <span>Your data is 100% private — <strong>no spam, ever</strong></span>
                  </div>
                </div>
              </form>
            </Card>
          </div>
        </div>
      </section>

      {/* Features */}
      <section className="py-20 bg-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-16">
            <h2 className="text-4xl font-bold text-brand-dark-blue mb-4">
              Why Choose Quote2Contract?
            </h2>
            <p className="text-xl text-gray-600 mb-4">Your trusted partner in {region}.</p>
            <div className="max-w-3xl mx-auto text-left space-y-4">
              <p className="text-gray-700 leading-relaxed">
                At Quote2Contract, we make getting your project done simple, safe, and stress-free. Whether you need roofing, gutters, fencing, paving, irrigation, pools, solar installations, or renovations — we handle it all from quote to contract.
              </p>
              <p className="text-gray-700 leading-relaxed font-semibold">Our process is quick and transparent:</p>
              <ul className="space-y-2 text-gray-700">
                <li className="flex items-start gap-2">
                  <CheckCircle className="w-5 h-5 text-brand-green flex-shrink-0 mt-0.5" />
                  <span>Tell us what you need.</span>
                </li>
                <li className="flex items-start gap-2">
                  <CheckCircle className="w-5 h-5 text-brand-green flex-shrink-0 mt-0.5" />
                  <span>Receive a competitive quote from a vetted, insured contractor.</span>
                </li>
                <li className="flex items-start gap-2">
                  <CheckCircle className="w-5 h-5 text-brand-green flex-shrink-0 mt-0.5" />
                  <span>Approve your quote — we seal the deal with a contract.</span>
                </li>
              </ul>
              <p className="text-gray-700 leading-relaxed">
                No endless calls, no risky hires — just reliable professionals who get it done right the first time.
              </p>
              <p className="text-gray-700 leading-relaxed">
                With Quote2Contract, you&apos;re always covered, always informed, and always in control.
              </p>
              <p className="text-center text-xl font-bold text-brand-dark-blue mt-6">
                Fast. Secure. Trusted.
              </p>
              <p className="text-center text-lg text-brand-green font-semibold">
                That&apos;s the Quote2Contract promise.
              </p>
            </div>
          </div>

          <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-6">
            {features.map((feature, index) => (
              <Card key={index} className="p-6 text-center hover:shadow-brand transition-all">
                <CheckCircle className="w-12 h-12 text-brand-green mx-auto mb-4" />
                <p className="font-semibold text-brand-dark-blue">{feature}</p>
              </Card>
            ))}
          </div>
        </div>
      </section>

      {/* Process Flow Diagram */}
      <section className="py-20 bg-gradient-to-br from-gray-50 to-white relative overflow-hidden">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-16">
            <h2 className="text-3xl lg:text-4xl font-bold text-brand-dark-blue mb-4">
              How Quote2Contract Works
            </h2>
            <p className="text-xl text-gray-600 max-w-3xl mx-auto">
              From request to completion — a streamlined, transparent process designed for your peace of mind
            </p>
          </div>

          {/* Process Flow Grid */}
          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8 relative">
            {/* Card 1 - Lead Request */}
            <Card className="group relative p-8 border-2 border-brand-navy hover:border-brand-navy/80 hover:shadow-2xl transition-all duration-300 bg-gradient-to-br from-blue-50 to-white overflow-hidden animate-fade-in-up" style={{ animationDelay: '0ms' }}>
              <div className="absolute top-4 right-4 bg-brand-navy text-white text-xs font-bold px-3 py-1 rounded-full">
                STEP 1
              </div>
              <div className="text-5xl mb-4">📝</div>
              <h3 className="text-xl font-bold text-brand-dark-blue mb-3">Submit Your Project</h3>
              <p className="text-gray-600 mb-4">
                Enter your details in minutes. Our CRM captures everything instantly.
              </p>
              <div className="inline-block bg-brand-navy/10 text-brand-navy text-sm font-semibold px-4 py-2 rounded-full">
                Instant CRM Tracking
              </div>
              {/* Arrow */}
              <div className="hidden lg:block absolute -right-8 top-1/2 transform -translate-y-1/2 text-brand-green text-4xl z-10 group-hover:scale-125 transition-transform">
                →
              </div>
            </Card>

            {/* Card 2 - Quote Generation */}
            <Card className="group relative p-8 border-2 border-lime-500 hover:border-lime-400 hover:shadow-2xl transition-all duration-300 bg-gradient-to-br from-lime-50 to-white overflow-hidden animate-fade-in-up" style={{ animationDelay: '150ms' }}>
              <div className="absolute top-4 right-4 bg-lime-600 text-white text-xs font-bold px-3 py-1 rounded-full">
                STEP 2
              </div>
              <div className="text-5xl mb-4">⚙️</div>
              <h3 className="text-xl font-bold text-brand-dark-blue mb-3">Receive a Professional Quote</h3>
              <p className="text-gray-600 mb-4">
                Verified contractors submit pricing through our secure platform.
              </p>
              <div className="inline-block bg-lime-100 text-lime-700 text-sm font-semibold px-4 py-2 rounded-full">
                Transparent Pricing
              </div>
              {/* Arrow */}
              <div className="hidden lg:block absolute -right-8 top-1/2 transform -translate-y-1/2 text-brand-green text-4xl z-10 group-hover:scale-125 transition-transform">
                →
              </div>
            </Card>

            {/* Card 3 - Accept/Reject */}
            <Card className="group relative p-8 border-2 border-yellow-500 hover:border-yellow-400 hover:shadow-2xl transition-all duration-300 bg-gradient-to-br from-yellow-50 to-white overflow-hidden animate-fade-in-up" style={{ animationDelay: '300ms' }}>
              <div className="absolute top-4 right-4 bg-yellow-600 text-white text-xs font-bold px-3 py-1 rounded-full">
                STEP 3
              </div>
              <div className="text-5xl mb-4">✅</div>
              <h3 className="text-xl font-bold text-brand-dark-blue mb-3">Approve with a Click</h3>
              <p className="text-gray-600 mb-4">
                View your quote online. Accept, reject, or request clarification instantly.
              </p>
              <div className="inline-block bg-yellow-100 text-yellow-700 text-sm font-semibold px-4 py-2 rounded-full">
                Simple Decision Workflow
              </div>
            </Card>

            {/* Card 4 - Digital Contract */}
            <Card className="group relative p-8 border-2 border-green-500 hover:border-green-400 hover:shadow-2xl transition-all duration-300 bg-gradient-to-br from-green-50 to-white overflow-hidden animate-fade-in-up" style={{ animationDelay: '450ms' }}>
              <div className="absolute top-4 right-4 bg-green-600 text-white text-xs font-bold px-3 py-1 rounded-full">
                STEP 4
              </div>
              <div className="text-5xl mb-4">✍️</div>
              <h3 className="text-xl font-bold text-brand-dark-blue mb-3">E-Sign Legally Binding Contracts</h3>
              <p className="text-gray-600 mb-4">
                Terms, scope, timeline, and warranties — all secured digitally.
              </p>
              <div className="inline-block bg-green-100 text-green-700 text-sm font-semibold px-4 py-2 rounded-full">
                Legal Peace of Mind
              </div>
              {/* Arrow */}
              <div className="hidden lg:block absolute -right-8 top-1/2 transform -translate-y-1/2 text-brand-green text-4xl z-10 group-hover:scale-125 transition-transform">
                →
              </div>
            </Card>

            {/* Card 5 - Contractor Handoff */}
            <Card className="group relative p-8 border-2 border-blue-500 hover:border-blue-400 hover:shadow-2xl transition-all duration-300 bg-gradient-to-br from-blue-50 to-white overflow-hidden animate-fade-in-up" style={{ animationDelay: '600ms' }}>
              <div className="absolute top-4 right-4 bg-blue-600 text-white text-xs font-bold px-3 py-1 rounded-full">
                STEP 5
              </div>
              <div className="text-5xl mb-4">🔔</div>
              <h3 className="text-xl font-bold text-brand-dark-blue mb-3">Contractor Notified</h3>
              <p className="text-gray-600 mb-4">
                Once signed, the job transfers to the assigned contractor with full scope.
              </p>
              <div className="inline-block bg-blue-100 text-blue-700 text-sm font-semibold px-4 py-2 rounded-full">
                No Delays
              </div>
              {/* Arrow */}
              <div className="hidden lg:block absolute -right-8 top-1/2 transform -translate-y-1/2 text-brand-green text-4xl z-10 group-hover:scale-125 transition-transform">
                →
              </div>
            </Card>

            {/* Card 6 - Project Scheduling */}
            <Card className="group relative p-8 border-2 border-purple-500 hover:border-purple-400 hover:shadow-2xl transition-all duration-300 bg-gradient-to-br from-purple-50 to-white overflow-hidden animate-fade-in-up" style={{ animationDelay: '750ms' }}>
              <div className="absolute top-4 right-4 bg-purple-600 text-white text-xs font-bold px-3 py-1 rounded-full">
                STEP 6
              </div>
              <div className="text-5xl mb-4">📅</div>
              <h3 className="text-xl font-bold text-brand-dark-blue mb-3">Live Scheduling Dashboard</h3>
              <p className="text-gray-600 mb-4">
                Customer and contractor can view timelines, stages, and updates.
              </p>
              <div className="inline-block bg-purple-100 text-purple-700 text-sm font-semibold px-4 py-2 rounded-full">
                Full Transparency
              </div>
            </Card>

            {/* Card 7 - Payments */}
            <Card className="group relative p-8 border-2 border-orange-600 hover:border-orange-500 hover:shadow-2xl transition-all duration-300 bg-gradient-to-br from-orange-50 to-white overflow-hidden animate-fade-in-up" style={{ animationDelay: '900ms' }}>
              <div className="absolute top-4 right-4 bg-orange-700 text-white text-xs font-bold px-3 py-1 rounded-full">
                STEP 7
              </div>
              <div className="text-5xl mb-4">💳</div>
              <h3 className="text-xl font-bold text-brand-dark-blue mb-3">Secure, Tracked Payments</h3>
              <p className="text-gray-600 mb-4">
                Automatic reminders & full payment history.
              </p>
              <div className="inline-block bg-orange-100 text-orange-700 text-sm font-semibold px-4 py-2 rounded-full">
                Zero Lost Invoices
              </div>
              {/* Arrow */}
              <div className="hidden lg:block absolute -right-8 top-1/2 transform -translate-y-1/2 text-brand-green text-4xl z-10 group-hover:scale-125 transition-transform">
                →
              </div>
            </Card>

            {/* Card 8 - Insurance Guarantee */}
            <Card className="group relative p-8 border-2 border-slate-600 hover:border-slate-500 hover:shadow-2xl transition-all duration-300 bg-gradient-to-br from-slate-50 to-white overflow-hidden animate-fade-in-up" style={{ animationDelay: '1050ms' }}>
              <div className="absolute top-4 right-4 bg-slate-700 text-white text-xs font-bold px-3 py-1 rounded-full">
                STEP 8
              </div>
              <div className="text-5xl mb-4">🛡️</div>
              <h3 className="text-xl font-bold text-brand-dark-blue mb-3">Fully Insured Projects</h3>
              <p className="text-gray-600 mb-4">
                Every job is backed by Quote2Contract&apos;s insurance + 100% satisfaction.
              </p>
              <div className="inline-block bg-slate-200 text-slate-700 text-sm font-semibold px-4 py-2 rounded-full">
                Risk-Free
              </div>
              {/* Arrow */}
              <div className="hidden lg:block absolute -right-8 top-1/2 transform -translate-y-1/2 text-brand-green text-4xl z-10 group-hover:scale-125 transition-transform">
                →
              </div>
            </Card>

            {/* Card 9 - Completion Sign-Off */}
            <Card className="group relative p-8 border-2 border-lime-600 hover:border-lime-500 hover:shadow-2xl transition-all duration-300 bg-gradient-to-br from-lime-50 to-white overflow-hidden animate-fade-in-up" style={{ animationDelay: '1200ms' }}>
              <div className="absolute top-4 right-4 bg-lime-700 text-white text-xs font-bold px-3 py-1 rounded-full">
                STEP 9
              </div>
              <div className="text-5xl mb-4">🏁</div>
              <h3 className="text-xl font-bold text-brand-dark-blue mb-3">Digital Sign-Off</h3>
              <p className="text-gray-600 mb-4">
                Customer approves final quality, and warranty begins.
              </p>
              <div className="inline-block bg-lime-100 text-lime-700 text-sm font-semibold px-4 py-2 rounded-full">
                Certified Completion
              </div>
            </Card>
          </div>

          {/* Bottom CTA */}
          <div className="text-center mt-16">
            <p className="text-2xl font-bold text-brand-dark-blue mb-6">
              Ready to experience the difference?
            </p>
            <Button 
              size="lg"
              className="bg-brand-green hover:bg-brand-green/90 text-white px-12 py-6 text-lg rounded-full shadow-xl hover:shadow-2xl transition-all transform hover:scale-105"
              onClick={() => {
                document.getElementById('quote-form')?.scrollIntoView({ behavior: 'smooth' });
              }}
            >
              Start Your Project Now
            </Button>
          </div>
        </div>
      </section>

      {/* We Are Insured Section */}
      <section className="py-16 bg-gradient-to-br from-brand-dark-blue to-brand-navy text-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-12">
            <h2 className="text-3xl lg:text-4xl font-bold mb-3">
              We Are Insured & Certified
            </h2>
            <p className="text-xl text-white/90">
              Your peace of mind is our priority
            </p>
          </div>

          <div className="grid md:grid-cols-2 lg:grid-cols-5 gap-6">
            <Card className="p-6 text-center bg-white/10 backdrop-blur-sm border-white/20 hover:bg-white/20 transition-all">
              <Shield className="w-12 h-12 text-brand-green mx-auto mb-4" />
              <p className="font-bold text-lg text-white mb-2">✅ NHBRC Registered</p>
              <p className="text-sm text-white/80">Fully registered contractors</p>
            </Card>
            <Card className="p-6 text-center bg-white/10 backdrop-blur-sm border-white/20 hover:bg-white/20 transition-all">
              <Shield className="w-12 h-12 text-brand-green mx-auto mb-4" />
              <p className="font-bold text-lg text-white mb-2">🔒 Fully Insured</p>
              <p className="text-sm text-white/80">Contractors with comprehensive insurance</p>
            </Card>
            <Card className="p-6 text-center bg-white/10 backdrop-blur-sm border-white/20 hover:bg-white/20 transition-all">
              <Award className="w-12 h-12 text-brand-green mx-auto mb-4" />
              <p className="font-bold text-lg text-white mb-2">📜 COC Compliance</p>
              <p className="text-sm text-white/80">Guaranteed compliance certificates</p>
            </Card>
            <Card className="p-6 text-center bg-white/10 backdrop-blur-sm border-white/20 hover:bg-white/20 transition-all">
              <Building className="w-12 h-12 text-brand-green mx-auto mb-4" />
              <p className="font-bold text-lg text-white mb-2">🧱 Local Materials</p>
              <p className="text-sm text-white/80">Quality local suppliers only</p>
            </Card>
            <Card className="p-6 text-center bg-white/10 backdrop-blur-sm border-white/20 hover:bg-white/20 transition-all">
              <Award className="w-12 h-12 text-brand-green mx-auto mb-4" />
              <p className="font-bold text-lg text-white mb-2">🧰 10-Year Warranty</p>
              <p className="text-sm text-white/80">Regional warranty support</p>
            </Card>
          </div>
        </div>
      </section>

      {/* Popular Services */}
      <section className="py-20 bg-gradient-to-br from-brand-teal/10 to-brand-green/10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-16">
            <h2 className="text-4xl font-bold text-brand-dark-blue mb-4">
              Popular Services in {region}
            </h2>
            <p className="text-lg text-gray-600">Expert contractors for every project</p>
          </div>

          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
            {popularServices.map((service, index) => (
              <Card key={index} className="p-6 text-center hover:shadow-brand hover:border-brand-green hover:-translate-y-1 transition-all cursor-pointer group">
                <div className="flex flex-col items-center gap-3">
                  <div className="text-brand-green group-hover:scale-110 transition-transform">
                    {getServiceIcon(service)}
                  </div>
                  <p className="font-semibold text-sm text-brand-dark-blue">{service}</p>
                  <Link href="#quote-form">
                    <Button size="sm" variant="ghost" className="text-brand-green hover:text-brand-green/80 hover:bg-brand-green/10">
                      Get Quote →
                    </Button>
                  </Link>
                </div>
              </Card>
            ))}
          </div>
        </div>
      </section>

      {/* Detailed Services Section */}
      {detailedServices && detailedServices.length > 0 && (
        <section className="py-20 bg-white">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="text-center mb-16">
              <h2 className="text-4xl font-bold text-brand-dark-blue mb-4">
                Comprehensive Service Catalog
              </h2>
              <p className="text-lg text-gray-600">Full range of professional services we offer in {region}</p>
            </div>

            <div className="space-y-12">
              {detailedServices.map((category, catIndex) => (
                <Card key={catIndex} className="p-8 hover:shadow-brand-lg transition-all border-2">
                  {/* Category Header */}
                  <div className="mb-8">
                    <h3 className="text-3xl font-bold text-brand-dark-blue mb-2 flex items-center gap-3">
                      <span>{category.name}</span>
                    </h3>
                    <p className="text-gray-600 text-lg">{category.description}</p>
                  </div>

                  {/* Subcategories */}
                  <div className="grid md:grid-cols-2 gap-8">
                    {category.subcategories.map((subcategory, subIndex) => (
                      <div key={subIndex} className="bg-gradient-to-br from-gray-50 to-white p-6 rounded-lg border border-gray-200 hover:border-brand-green transition-all">
                        <h4 className="text-xl font-bold text-brand-dark-blue mb-4 flex items-center gap-2">
                          <CheckCircle className="w-5 h-5 text-brand-green" />
                          {subcategory.name}
                        </h4>
                        <ul className="space-y-2">
                          {subcategory.services.map((service, serviceIndex) => (
                            <li key={serviceIndex} className="text-gray-700 flex items-start gap-2 text-sm">
                              <span className="text-brand-green mt-1 flex-shrink-0">▸</span>
                              <span>{service}</span>
                            </li>
                          ))}
                        </ul>
                      </div>
                    ))}
                  </div>

                  {/* Call to Action */}
                  <div className="mt-6 pt-6 border-t border-gray-200 text-center">
                    <Link href="#quote-form">
                      <Button className="bg-brand-green hover:bg-brand-green/90">
                        Request Quote for {category.name.replace(/[🏠💧☀️🏊💦🛣️🚧🏗️]/g, '').trim()}
                        <ArrowRight className="w-4 h-4 ml-2" />
                      </Button>
                    </Link>
                  </div>
                </Card>
              ))}
            </div>

            {/* Overall CTA */}
            <div className="mt-16 text-center bg-gradient-to-r from-brand-green to-brand-teal rounded-2xl p-12 text-white">
              <h3 className="text-3xl font-bold mb-4">Can't Find What You're Looking For?</h3>
              <p className="text-xl mb-8 text-white/90">
                We also handle custom projects and specialized services. Get in touch with us!
              </p>
              <div className="flex flex-col sm:flex-row gap-4 justify-center">
                <Link href="#quote-form">
                  <Button size="lg" className="bg-white text-brand-green hover:bg-gray-100">
                    Get Free Quote
                    <ArrowRight className="w-5 h-5 ml-2" />
                  </Button>
                </Link>
                {contactPhone && (
                  <a href={`tel:${contactPhone}`}>
                    <Button size="lg" variant="outline" className="bg-transparent border-white text-white hover:bg-white/10">
                      <Phone className="w-5 h-5 mr-2" />
                      Call {contactPhone}
                    </Button>
                  </a>
                )}
              </div>
            </div>
          </div>
        </section>
      )}

      {/* Testimonials */}
      <section className="py-20 bg-gradient-to-br from-gray-50 to-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-16">
            <h2 className="text-4xl font-bold text-brand-dark-blue mb-4">
              What Our Customers Say
            </h2>
            <p className="text-lg text-gray-600">Real reviews from real homeowners</p>
          </div>

          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
            {testimonials.slice(0, 6).map((testimonial, index) => (
              <Card key={index} className="p-8 hover:shadow-brand-lg hover:-translate-y-1 transition-all">
                <div className="flex items-center gap-1 mb-4">
                  {[...Array(testimonial.rating)].map((_, i) => (
                    <Star key={i} className="w-5 h-5 fill-yellow-400 text-yellow-400" />
                  ))}
                </div>
                <p className="text-gray-700 mb-6 italic text-sm leading-relaxed">&ldquo;{testimonial.text}&rdquo;</p>
                <div className="flex items-center gap-3 pt-4 border-t">
                  <div className="w-12 h-12 rounded-full bg-gradient-to-br from-brand-green to-brand-teal flex items-center justify-center text-white font-bold text-lg">
                    {testimonial.name.charAt(0)}
                  </div>
                  <div className="flex-1">
                    <p className="font-semibold text-brand-dark-blue">{testimonial.name}</p>
                    <p className="text-xs text-gray-500 flex items-center gap-1">
                      <MapPin className="w-3 h-3" />
                      {testimonial.location}
                    </p>
                  </div>
                  <Badge variant="outline" className="bg-brand-green/10 text-brand-green border-brand-green text-xs">
                    {testimonial.project}
                  </Badge>
                </div>
              </Card>
            ))}
          </div>

          <div className="text-center mt-12">
            <p className="text-lg text-gray-700 font-semibold mb-4">
              Join 1,200+ happy South Africans who found trusted contractors through {contractor}
            </p>
            <Link href="#quote-form">
              <Button size="lg" className="bg-brand-green hover:bg-brand-green/90">
                Get Your Free Quote
              </Button>
            </Link>
          </div>
        </div>
      </section>

      {/* Service Area Map */}
      <section className="py-20 bg-brand-dark-blue text-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-12">
            <h2 className="text-4xl font-bold mb-4">
              Service Coverage Across {region}
            </h2>
            <p className="text-xl text-white/80">
              Local verified contractors available in all major cities
            </p>
          </div>

          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-8">
            {cities.map((city, index) => (
              <div key={index} className="flex items-center justify-center gap-2 p-4 bg-white/10 rounded-lg backdrop-blur-sm hover:bg-white/20 transition-all cursor-pointer">
                <MapPin className="w-4 h-4 text-brand-green flex-shrink-0" />
                <span className="font-medium text-sm">{city}</span>
              </div>
            ))}
          </div>

          <div className="text-center">
            <Link href="#quote-form">
              <Button variant="outline" className="border-white text-white hover:bg-white hover:text-brand-dark-blue">
                <MapPin className="mr-2 w-4 h-4" />
                See Contractors Near Me 🔍
              </Button>
            </Link>
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="py-20 bg-gradient-to-r from-brand-green to-brand-teal text-white relative overflow-hidden">
        <div className="absolute inset-0 opacity-10">
          <div className="w-full h-full bg-[url('https://images.unsplash.com/photo-1581094794329-c8112a89af12?w=1920')] bg-cover bg-center" />
        </div>
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 text-center relative z-10">
          <h2 className="text-4xl lg:text-5xl font-bold mb-6">
            Ready to Get Started?
          </h2>
          <p className="text-xl mb-8 opacity-90">
            Connect with verified contractors today — it&apos;s fast, free, and reliable.
          </p>
          <div className="flex flex-wrap justify-center gap-4">
            <Link href="#quote-form">
              <Button size="lg" className="bg-white text-brand-green hover:bg-gray-100 px-8 shadow-xl">
                Get Free Quote <ArrowRight className="ml-2 w-5 h-5" />
              </Button>
            </Link>
            {contactPhone && (
              <>
                <a 
                  href={`https://wa.me/${contactPhone.replace(/\+/g, '').replace(/\s/g, '')}`}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <Button size="lg" variant="outline" className="border-white text-white hover:bg-white hover:text-brand-green">
                    <MessageCircle className="mr-2 w-5 h-5" />
                    Chat on WhatsApp
                  </Button>
                </a>
                <a href={`tel:${contactPhone}`}>
                  <Button size="lg" variant="outline" className="border-white text-white hover:bg-white hover:text-brand-green">
                    <Phone className="mr-2 w-5 h-5" />
                    Call {contactPhone}
                  </Button>
                </a>
              </>
            )}
          </div>
          
          <div className="mt-12 pt-8 border-t border-white/20">
            <p className="text-lg font-semibold mb-4">📈 Trusted by 2,000+ homeowners and contractors in SA</p>
            <div className="flex flex-wrap justify-center gap-6 text-sm">
              <span>⏱ Average Contractor Match Time: 24 Hours</span>
            </div>
          </div>
        </div>
      </section>

      {/* Footer */}
      <footer className="bg-brand-navy text-white py-12">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center">
            <div className="flex items-center justify-center gap-2 mb-4">
              <div className="relative w-8 h-8">
                <Image src="/brand-logo.png" alt="Quote2Contract" fill className="object-contain" />
              </div>
              <span className="font-bold">Quote2Contract {region}</span>
            </div>
            <p className="text-sm text-gray-400 mb-4">
              Trusted partner: {contractor}
            </p>
            <div className="flex flex-wrap justify-center gap-4 text-xs text-gray-400 mb-4">
              <span>© {new Date().getFullYear()} {contractor}</span>
              <span>•</span>
              <span>NHBRC Registered</span>
              <span>•</span>
              <span>COC Certified</span>
              <span>•</span>
              <span>POPIA Compliant</span>
            </div>
            <p className="text-xs text-gray-500">
              All rights reserved. Your privacy is protected.
            </p>
          </div>
        </div>
      </footer>

      {/* WhatsApp Floating Button */}
      {contactPhone && (
        <a
          href={`https://wa.me/${contactPhone.replace(/\+/g, '').replace(/\s/g, '')}`}
          target="_blank"
          rel="noopener noreferrer"
          className="fixed bottom-6 right-6 z-50 bg-green-500 hover:bg-green-600 text-white rounded-full p-4 shadow-2xl hover:scale-110 transition-all group"
          aria-label="Chat on WhatsApp"
        >
          <MessageCircle className="w-6 h-6" />
          <span className="absolute -top-2 -left-2 bg-red-500 text-white text-xs rounded-full w-6 h-6 flex items-center justify-center animate-pulse">
            1
          </span>
          <span className="absolute right-full mr-3 top-1/2 -translate-y-1/2 bg-gray-900 text-white px-3 py-2 rounded-lg text-sm whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity">
            Chat with us now!
          </span>
        </a>
      )}

      {/* Google Maps Location Picker Dialog */}
      {showMap && (
        <div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4">
          <div className="bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-hidden">
            <div className="p-4 border-b flex justify-between items-center">
              <h3 className="text-lg font-semibold text-brand-dark-blue">Select Your Location</h3>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setShowMap(false)}
              >
                ✕
              </Button>
            </div>
            <div className="p-4">
              <LocationPicker
                onLocationSelect={handleLocationSelect}
                initialCenter={mapCenter}
              />
            </div>
          </div>
        </div>
      )}

      {/* AI Chatbot Widget */}
      <ChatbotWidget />

      {/* Success Confirmation Modal */}
      {showSuccessModal && (
        <div className="fixed inset-0 z-50 bg-black/60 flex items-center justify-center p-4 backdrop-blur-sm">
          <div className="bg-white rounded-2xl max-w-md w-full p-8 shadow-2xl animate-in fade-in zoom-in duration-300">
            {/* Success Icon */}
            <div className="flex justify-center mb-6">
              <div className="w-20 h-20 bg-gradient-to-br from-brand-green to-brand-teal rounded-full flex items-center justify-center animate-in zoom-in duration-500">
                <CheckCircle className="w-12 h-12 text-white" strokeWidth={2.5} />
              </div>
            </div>

            {/* Success Message */}
            <h3 className="text-2xl font-bold text-brand-dark-blue text-center mb-3">
              Quote Request Sent! ✓
            </h3>
            <p className="text-gray-600 text-center mb-6">
              We&apos;ve received your quote request and one of our team members will contact you within <strong className="text-brand-green">30 minutes</strong>.
            </p>

            {/* Contact Options */}
            <div className="bg-gradient-to-br from-brand-teal/10 to-brand-green/10 rounded-xl p-6 mb-6 space-y-3">
              <p className="text-sm font-semibold text-brand-dark-blue mb-3 text-center">
                Need immediate assistance? Reach us now:
              </p>
              
              {contactPhone && (
                <>
                  <a
                    href={`tel:${contactPhone}`}
                    className="flex items-center gap-3 p-3 bg-white rounded-lg hover:shadow-md transition-all group"
                  >
                    <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center group-hover:bg-blue-200 transition-colors">
                      <Phone className="w-5 h-5 text-blue-600" />
                    </div>
                    <div className="flex-1">
                      <p className="text-xs text-gray-500">Call us</p>
                      <p className="font-semibold text-brand-dark-blue">{contactPhone}</p>
                    </div>
                    <ArrowRight className="w-4 h-4 text-gray-400 group-hover:text-brand-green group-hover:translate-x-1 transition-all" />
                  </a>

                  <a
                    href={`https://wa.me/${contactPhone.replace(/\+/g, '').replace(/\s/g, '')}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-3 p-3 bg-white rounded-lg hover:shadow-md transition-all group"
                  >
                    <div className="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center group-hover:bg-green-200 transition-colors">
                      <MessageCircle className="w-5 h-5 text-green-600" />
                    </div>
                    <div className="flex-1">
                      <p className="text-xs text-gray-500">WhatsApp</p>
                      <p className="font-semibold text-brand-dark-blue">{contactPhone}</p>
                    </div>
                    <ArrowRight className="w-4 h-4 text-gray-400 group-hover:text-brand-green group-hover:translate-x-1 transition-all" />
                  </a>

                  <a
                    href={`https://t.me/${contactPhone.replace(/\+/g, '').replace(/\s/g, '')}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-3 p-3 bg-white rounded-lg hover:shadow-md transition-all group"
                  >
                    <div className="w-10 h-10 bg-sky-100 rounded-full flex items-center justify-center group-hover:bg-sky-200 transition-colors">
                      <MessageCircle className="w-5 h-5 text-sky-600" />
                    </div>
                    <div className="flex-1">
                      <p className="text-xs text-gray-500">Telegram</p>
                      <p className="font-semibold text-brand-dark-blue">{contactPhone}</p>
                    </div>
                    <ArrowRight className="w-4 h-4 text-gray-400 group-hover:text-brand-green group-hover:translate-x-1 transition-all" />
                  </a>
                </>
              )}

              <div className="flex items-center gap-3 p-3 bg-white rounded-lg">
                <div className="w-10 h-10 bg-purple-100 rounded-full flex items-center justify-center">
                  <Mail className="w-5 h-5 text-purple-600" />
                </div>
                <div className="flex-1">
                  <p className="text-xs text-gray-500">Email confirmation sent to</p>
                  <p className="font-semibold text-brand-dark-blue text-sm">{submittedEmail || 'your email'}</p>
                </div>
              </div>
            </div>

            {/* Close Button */}
            <Button
              onClick={() => setShowSuccessModal(false)}
              className="w-full bg-gradient-to-r from-brand-green to-brand-teal text-white hover:opacity-90 transition-opacity py-6 text-lg font-semibold"
            >
              Got it, thanks!
            </Button>

            {/* Additional Info */}
            <p className="text-xs text-center text-gray-500 mt-4">
              ✓ Your information is secure and will never be shared
            </p>
          </div>
        </div>
      )}
    </div>
  );
}
