import React, { useState, useMemo } from 'react';
import { Head, usePage } from '@inertiajs/react';
import { PublicHeader } from '@/Components/PublicHeader';
import { PublicFooter } from '@/Components/PublicFooter';
import { SEOHead } from '@/Components/SEOHead';
import {
    Calculator,
    Check,
    ArrowRight,
    ArrowLeft,
    Sparkles,
    ShieldCheck,
    Smartphone,
    Globe,
    Server,
    Layers,
    Lock,
    CreditCard,
    MessageSquare,
    Bot,
    BarChart3,
    Building2,
    Languages,
    Cpu,
    Calendar,
    Send,
    CheckCircle2,
    Clock,
    DollarSign,
    Zap,
} from 'lucide-react';

interface EstimatorProps {
    settings?: Record<string, string>;
    defaultCurrency?: string;
}

interface ProjectTypeOption {
    id: string;
    title: string;
    description: string;
    icon: any;
    basePriceMin: number;
    basePriceMax: number;
    baseWeeksMin: number;
    baseWeeksMax: number;
}

interface FeatureOption {
    id: string;
    name: string;
    desc: string;
    icon: any;
    priceMin: number;
    priceMax: number;
    weeks: number;
    category: 'core' | 'advanced' | 'enterprise';
}

const PROJECT_TYPES: ProjectTypeOption[] = [
    {
        id: 'web_app',
        title: 'Custom Web Application',
        description: 'High-performance web apps built with Laravel, React, Next.js, and Inertia.js.',
        icon: Globe,
        basePriceMin: 1800,
        basePriceMax: 3200,
        baseWeeksMin: 3,
        baseWeeksMax: 5,
    },
    {
        id: 'mobile_app',
        title: 'Mobile App (iOS & Android)',
        description: 'Cross-platform native mobile apps using Flutter or React Native with fluid animations.',
        icon: Smartphone,
        basePriceMin: 2400,
        basePriceMax: 4500,
        baseWeeksMin: 4,
        baseWeeksMax: 7,
    },
    {
        id: 'saas',
        title: 'Full SaaS Platform',
        description: 'Multi-tenant software with subscription billing, team management, and API access.',
        icon: Layers,
        basePriceMin: 3800,
        basePriceMax: 7500,
        baseWeeksMin: 6,
        baseWeeksMax: 10,
    },
    {
        id: 'cloud_devops',
        title: 'DevOps & Cloud Infrastructure',
        description: 'AWS / Docker / Kubernetes architectures, CI/CD automated pipelines, and Redis clusters.',
        icon: Server,
        basePriceMin: 1400,
        basePriceMax: 2800,
        baseWeeksMin: 2,
        baseWeeksMax: 4,
    },
    {
        id: 'security_recovery',
        title: 'Cybersecurity & Incident Triage',
        description: 'Rapid malware removal, vulnerability audits, server hardening, and clean data recovery.',
        icon: ShieldCheck,
        basePriceMin: 1200,
        basePriceMax: 2500,
        baseWeeksMin: 1,
        baseWeeksMax: 3,
    },
];

const SCALES = [
    { id: 'mvp', title: 'MVP / Startup', desc: 'Fast turnaround, core features, launch ready', multiplier: 1.0 },
    { id: 'growth', title: 'Growth / Scaleup', desc: 'Advanced performance, modular architecture, moderate scale', multiplier: 1.35 },
    { id: 'enterprise', title: 'Enterprise Platform', desc: 'High concurrency, 99.99% uptime SLA, security compliance', multiplier: 1.75 },
];

const FEATURES: FeatureOption[] = [
    { id: 'auth_security', name: 'Role-Based RBAC & 2FA Auth', desc: 'Permissions, social login, passkeys, and session security', icon: Lock, priceMin: 300, priceMax: 500, weeks: 1, category: 'core' },
    { id: 'payments', name: 'Payment Gateways & Subscriptions', desc: 'Stripe, PayPal, BKash, SSLCommerz, and automated invoicing', icon: CreditCard, priceMin: 400, priceMax: 700, weeks: 1, category: 'core' },
    { id: 'realtime_chat', name: 'Real-Time Chat & WebSockets', desc: 'Live messaging, instant notifications, presence indicators', icon: MessageSquare, priceMin: 450, priceMax: 800, weeks: 1, category: 'advanced' },
    { id: 'ai_integration', name: 'AI & Custom RAG LLM Agents', desc: 'Autonomous AI assistant, semantic embeddings, smart workflows', icon: Bot, priceMin: 600, priceMax: 1200, weeks: 1.5, category: 'advanced' },
    { id: 'analytics_reporting', name: 'Analytics Dashboard & Charts', desc: 'Real-time revenue metrics, user cohort graphs, CSV/PDF exports', icon: BarChart3, priceMin: 350, priceMax: 650, weeks: 1, category: 'core' },
    { id: 'multi_tenancy', name: 'Multi-Tenant Workspace Engine', desc: 'Isolated customer subdomains, team seats, and white-labeling', icon: Building2, priceMin: 700, priceMax: 1400, weeks: 2, category: 'enterprise' },
    { id: 'localization', name: 'Multilingual i18n & Multi-Currency', desc: 'Dynamic translations and geo-localized pricing engines', icon: Languages, priceMin: 300, priceMax: 500, weeks: 0.5, category: 'advanced' },
    { id: 'hardware_offline', name: 'Device Hardware & Offline Sync', desc: 'Biometrics, GPS tracking, camera scanner, offline local storage', icon: Cpu, priceMin: 500, priceMax: 900, weeks: 1.5, category: 'enterprise' },
];

const DESIGN_TIERS = [
    { id: 'custom_system', title: 'Tech in Soul Custom Design System', desc: 'Tailored dark/light mode, sleek glassmorphism, responsive micro-animations', extraMin: 0, extraMax: 0 },
    { id: 'figma_prototype', title: 'Bespoke Figma UI/UX & Interactive Prototypes', desc: 'Complete Figma wireframes, design token kit, user journey mappings', extraMin: 600, extraMax: 1200 },
    { id: 'client_figma', title: 'Client-Provided Figma Design', desc: 'We directly translate your existing Figma / Adobe XD files to pixel-perfect code', extraMin: -200, extraMax: -100 },
];

export default function Index({ settings = {}, defaultCurrency = 'USD' }: EstimatorProps) {
    const [step, setStep] = useState(1);
    const [selectedType, setSelectedType] = useState<string>('web_app');
    const [selectedScale, setSelectedScale] = useState<string>('growth');
    const [selectedFeatures, setSelectedFeatures] = useState<string[]>(['auth_security', 'analytics_reporting']);
    const [selectedDesign, setSelectedDesign] = useState<string>('custom_system');

    // Lead Form State
    const [clientName, setClientName] = useState('');
    const [clientEmail, setClientEmail] = useState('');
    const [clientPhone, setClientPhone] = useState('');
    const [companyName, setCompanyName] = useState('');
    const [clientNotes, setClientNotes] = useState('');
    const [submitting, setSubmitting] = useState(false);
    const [submittedData, setSubmittedData] = useState<any | null>(null);
    const [submitError, setSubmitError] = useState<string | null>(null);

    const toggleFeature = (id: string) => {
        setSelectedFeatures((prev) =>
            prev.includes(id) ? prev.filter((f) => f !== id) : [...prev, id]
        );
    };

    // Calculate dynamic cost and timeline
    const calculation = useMemo(() => {
        const typeObj = PROJECT_TYPES.find((t) => t.id === selectedType) || PROJECT_TYPES[0];
        const scaleObj = SCALES.find((s) => s.id === selectedScale) || SCALES[1];
        const designObj = DESIGN_TIERS.find((d) => d.id === selectedDesign) || DESIGN_TIERS[0];

        let featurePriceMin = 0;
        let featurePriceMax = 0;
        let featureWeeks = 0;

        selectedFeatures.forEach((fId) => {
            const f = FEATURES.find((item) => item.id === fId);
            if (f) {
                featurePriceMin += f.priceMin;
                featurePriceMax += f.priceMax;
                featureWeeks += f.weeks;
            }
        });

        const rawMin = (typeObj.basePriceMin + featurePriceMin + designObj.extraMin) * scaleObj.multiplier;
        const rawMax = (typeObj.basePriceMax + featurePriceMax + designObj.extraMax) * scaleObj.multiplier;

        const totalWeeksMin = Math.max(1, Math.round(typeObj.baseWeeksMin + (featureWeeks * 0.7)));
        const totalWeeksMax = Math.max(totalWeeksMin + 1, Math.round(typeObj.baseWeeksMax + featureWeeks));

        // Round to nearest 50
        const minBudget = Math.round(rawMin / 50) * 50;
        const maxBudget = Math.round(rawMax / 50) * 50;

        return {
            typeTitle: typeObj.title,
            scaleTitle: scaleObj.title,
            designTitle: designObj.title,
            minBudget,
            maxBudget,
            weeksMin: totalWeeksMin,
            weeksMax: totalWeeksMax,
            featureCount: selectedFeatures.length,
        };
    }, [selectedType, selectedScale, selectedFeatures, selectedDesign]);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!clientName.trim() || !clientEmail.trim()) return;

        setSubmitting(true);
        setSubmitError(null);

        try {
            const csrfToken = (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement)?.content;
            const res = await fetch('/estimate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': csrfToken || '',
                },
                body: JSON.stringify({
                    client_name: clientName,
                    client_email: clientEmail,
                    client_phone: clientPhone,
                    company_name: companyName,
                    project_type: calculation.typeTitle,
                    project_scale: calculation.scaleTitle,
                    features: selectedFeatures.map((fId) => FEATURES.find((f) => f.id === fId)?.name || fId),
                    design_tier: calculation.designTitle,
                    estimated_min_budget: calculation.minBudget,
                    estimated_max_budget: calculation.maxBudget,
                    currency: defaultCurrency,
                    estimated_weeks_min: calculation.weeksMin,
                    estimated_weeks_max: calculation.weeksMax,
                    notes: clientNotes,
                }),
            });

            const result = await res.json();
            if (result.success) {
                setSubmittedData(result.estimate || { client_name: clientName });
            } else {
                setSubmitError(result.message || 'Submission failed. Please try again.');
            }
        } catch (err: any) {
            setSubmitError(err.message || 'Network error occurred. Please contact us directly.');
        } finally {
            setSubmitting(false);
        }
    };

    return (
        <div className="min-h-screen bg-[#060B18] text-white flex flex-col selection:bg-[#00F2FE]/20 selection:text-[#00F2FE]">
            <SEOHead
                title="Interactive Project Cost & Scope Estimator | Tech in Soul"
                description="Calculate instant ballpark budgets, architectural roadmaps, and delivery timelines for custom web apps, mobile apps, and SaaS platforms."
            />
            <PublicHeader />

            <main className="flex-1 pt-32 pb-24 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto w-full">
                {/* Hero Header */}
                <div className="text-center max-w-3xl mx-auto mb-12 space-y-4">
                    <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-[#00F2FE]/10 border border-[#00F2FE]/30 text-[#00F2FE] text-xs font-bold uppercase tracking-wider">
                        <Sparkles className="w-3.5 h-3.5" /> Instant Scoping & Budget Calculator
                    </div>
                    <h1 className="text-3xl sm:text-5xl font-extrabold tracking-tight text-white">
                        Estimate Your Project <span className="bg-gradient-to-r from-[#00F2FE] via-[#4FACFE] to-[#00F2FE] bg-clip-text text-transparent">Scope & Timeline</span>
                    </h1>
                    <p className="text-sm sm:text-base text-slate-300">
                        Configure your target platform, engineering scale, and feature set to calculate ballpark budgets and sprint timelines in real time.
                    </p>
                </div>

                {submittedData ? (
                    /* Submission Success Screen */
                    <div className="max-w-2xl mx-auto p-8 sm:p-12 rounded-3xl bg-[#0B132B] border border-cyan-500/40 shadow-2xl text-center space-y-6 animate-in fade-in zoom-in-95">
                        <div className="w-16 h-16 rounded-2xl bg-gradient-to-tr from-[#00F2FE] to-[#4FACFE] flex items-center justify-center mx-auto text-[#060B18] shadow-lg shadow-cyan-500/20">
                            <CheckCircle2 className="w-10 h-10" />
                        </div>

                        <div className="space-y-2">
                            <h2 className="text-2xl font-bold text-white">Project Scope Recorded!</h2>
                            <p className="text-sm text-slate-300">
                                Thank you, <span className="text-[#00F2FE] font-bold">{clientName}</span>. An engineering director has received your architectural specification.
                            </p>
                        </div>

                        {/* Summary Box */}
                        <div className="p-5 rounded-2xl bg-[#060B18] border border-slate-800 text-left space-y-3 font-mono text-xs">
                            <div className="flex justify-between border-b border-slate-800/80 pb-2">
                                <span className="text-slate-400">Project Type:</span>
                                <span className="text-white font-bold">{calculation.typeTitle}</span>
                            </div>
                            <div className="flex justify-between border-b border-slate-800/80 pb-2">
                                <span className="text-slate-400">Estimated Budget Range:</span>
                                <span className="text-cyan-300 font-bold">${calculation.minBudget.toLocaleString()} – ${calculation.maxBudget.toLocaleString()} {defaultCurrency}</span>
                            </div>
                            <div className="flex justify-between border-b border-slate-800/80 pb-2">
                                <span className="text-slate-400">Estimated Delivery Time:</span>
                                <span className="text-white font-bold">{calculation.weeksMin} – {calculation.weeksMax} Weeks</span>
                            </div>
                            <div className="flex justify-between">
                                <span className="text-slate-400">Selected Features:</span>
                                <span className="text-slate-300">{calculation.featureCount} modules selected</span>
                            </div>
                        </div>

                        <div className="flex flex-col sm:flex-row gap-3 justify-center pt-2">
                            <a
                                href="/contact"
                                className="px-6 py-3 rounded-xl text-xs font-bold bg-gradient-to-r from-[#00F2FE] to-[#4FACFE] text-[#060B18] hover:opacity-95 shadow-lg shadow-cyan-500/20 flex items-center justify-center gap-2"
                            >
                                <Calendar className="w-4 h-4" /> Book Free Strategy Call
                            </a>
                            <button
                                type="button"
                                onClick={() => {
                                    setSubmittedData(null);
                                    setStep(1);
                                }}
                                className="px-6 py-3 rounded-xl text-xs font-bold bg-[#060B18] text-slate-300 hover:text-white border border-slate-800"
                            >
                                Calculate Another Project
                            </button>
                        </div>
                    </div>
                ) : (
                    /* Main Estimator Workflow */
                    <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
                        {/* Left: Step Form Container */}
                        <div className="lg:col-span-8 space-y-6">
                            {/* Step Indicator */}
                            <div className="p-4 rounded-2xl bg-[#0B132B] border border-slate-800 flex items-center justify-between">
                                {[
                                    { num: 1, label: 'Platform' },
                                    { num: 2, label: 'Scale' },
                                    { num: 3, label: 'Features' },
                                    { num: 4, label: 'Design' },
                                    { num: 5, label: 'Get Proposal' },
                                ].map((s) => (
                                    <button
                                        key={s.num}
                                        type="button"
                                        onClick={() => setStep(s.num)}
                                        className={`flex items-center gap-2 text-xs font-bold transition-all ${
                                            step === s.num
                                                ? 'text-[#00F2FE]'
                                                : step > s.num
                                                ? 'text-slate-300'
                                                : 'text-slate-600'
                                        }`}
                                    >
                                        <div
                                            className={`w-7 h-7 rounded-lg flex items-center justify-center text-xs font-bold border ${
                                                step === s.num
                                                    ? 'bg-[#00F2FE] text-[#060B18] border-[#00F2FE]'
                                                    : step > s.num
                                                    ? 'bg-cyan-950/40 text-cyan-400 border-cyan-700/50'
                                                    : 'bg-[#060B18] text-slate-500 border-slate-800'
                                            }`}
                                        >
                                            {step > s.num ? <Check className="w-3.5 h-3.5" /> : s.num}
                                        </div>
                                        <span className="hidden sm:inline">{s.label}</span>
                                    </button>
                                ))}
                            </div>

                            {/* Step 1: Project Type */}
                            {step === 1 && (
                                <div className="p-6 sm:p-8 rounded-3xl bg-[#0B132B] border border-slate-800 space-y-6 animate-in fade-in">
                                    <div className="space-y-1">
                                        <h3 className="text-lg font-bold text-white">Step 1: Select Platform / Solution Type</h3>
                                        <p className="text-xs text-slate-400">Choose the primary technology solution you need built.</p>
                                    </div>

                                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                        {PROJECT_TYPES.map((type) => {
                                            const Icon = type.icon;
                                            const isSelected = selectedType === type.id;
                                            return (
                                                <button
                                                    key={type.id}
                                                    type="button"
                                                    onClick={() => setSelectedType(type.id)}
                                                    className={`p-5 rounded-2xl text-left border transition-all relative ${
                                                        isSelected
                                                            ? 'bg-gradient-to-b from-[#00F2FE]/10 to-transparent border-[#00F2FE] shadow-lg shadow-cyan-500/10'
                                                            : 'bg-[#060B18] border-slate-800 hover:border-slate-700 text-slate-300'
                                                    }`}
                                                >
                                                    {isSelected && (
                                                        <div className="absolute top-4 right-4 w-6 h-6 rounded-full bg-[#00F2FE] text-[#060B18] flex items-center justify-center">
                                                            <Check className="w-3.5 h-3.5" />
                                                        </div>
                                                    )}
                                                    <div className={`w-10 h-10 rounded-xl flex items-center justify-center mb-3 ${isSelected ? 'bg-[#00F2FE] text-[#060B18]' : 'bg-[#1C2541] text-slate-300'}`}>
                                                        <Icon className="w-5 h-5" />
                                                    </div>
                                                    <h4 className="text-sm font-bold text-white mb-1">{type.title}</h4>
                                                    <p className="text-xs text-slate-400 leading-relaxed">{type.description}</p>
                                                </button>
                                            );
                                        })}
                                    </div>

                                    <div className="flex justify-end pt-4">
                                        <button
                                            type="button"
                                            onClick={() => setStep(2)}
                                            className="px-6 py-3 rounded-xl text-xs font-bold bg-gradient-to-r from-[#00F2FE] to-[#4FACFE] text-[#060B18] hover:opacity-95 flex items-center gap-2 shadow-md shadow-cyan-500/10"
                                        >
                                            Next: Project Scale <ArrowRight className="w-4 h-4" />
                                        </button>
                                    </div>
                                </div>
                            )}

                            {/* Step 2: Scale */}
                            {step === 2 && (
                                <div className="p-6 sm:p-8 rounded-3xl bg-[#0B132B] border border-slate-800 space-y-6 animate-in fade-in">
                                    <div className="space-y-1">
                                        <h3 className="text-lg font-bold text-white">Step 2: Architecture Scale & Target Traffic</h3>
                                        <p className="text-xs text-slate-400">Choose the architectural maturity and user volume requirements.</p>
                                    </div>

                                    <div className="space-y-3">
                                        {SCALES.map((scale) => {
                                            const isSelected = selectedScale === scale.id;
                                            return (
                                                <button
                                                    key={scale.id}
                                                    type="button"
                                                    onClick={() => setSelectedScale(scale.id)}
                                                    className={`w-full p-5 rounded-2xl text-left border flex items-center justify-between transition-all ${
                                                        isSelected
                                                            ? 'bg-[#00F2FE]/10 border-[#00F2FE] text-white shadow-lg shadow-cyan-500/10'
                                                            : 'bg-[#060B18] border-slate-800 hover:border-slate-700 text-slate-300'
                                                    }`}
                                                >
                                                    <div className="space-y-1">
                                                        <h4 className="text-sm font-bold text-white">{scale.title}</h4>
                                                        <p className="text-xs text-slate-400">{scale.desc}</p>
                                                    </div>
                                                    <div className={`w-6 h-6 rounded-full border flex items-center justify-center ${isSelected ? 'bg-[#00F2FE] border-[#00F2FE] text-[#060B18]' : 'border-slate-700'}`}>
                                                        {isSelected && <Check className="w-3.5 h-3.5" />}
                                                    </div>
                                                </button>
                                            );
                                        })}
                                    </div>

                                    <div className="flex justify-between pt-4">
                                        <button
                                            type="button"
                                            onClick={() => setStep(1)}
                                            className="px-5 py-2.5 rounded-xl text-xs font-semibold bg-[#060B18] text-slate-400 hover:text-white border border-slate-800 flex items-center gap-1.5"
                                        >
                                            <ArrowLeft className="w-4 h-4" /> Back
                                        </button>
                                        <button
                                            type="button"
                                            onClick={() => setStep(3)}
                                            className="px-6 py-3 rounded-xl text-xs font-bold bg-gradient-to-r from-[#00F2FE] to-[#4FACFE] text-[#060B18] hover:opacity-95 flex items-center gap-2 shadow-md"
                                        >
                                            Next: Select Features <ArrowRight className="w-4 h-4" />
                                        </button>
                                    </div>
                                </div>
                            )}

                            {/* Step 3: Features */}
                            {step === 3 && (
                                <div className="p-6 sm:p-8 rounded-3xl bg-[#0B132B] border border-slate-800 space-y-6 animate-in fade-in">
                                    <div className="space-y-1">
                                        <h3 className="text-lg font-bold text-white">Step 3: Select Required Functional Modules</h3>
                                        <p className="text-xs text-slate-400">Click to select the core integrations, APIs, and functional components.</p>
                                    </div>

                                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3.5">
                                        {FEATURES.map((feature) => {
                                            const Icon = feature.icon;
                                            const isSelected = selectedFeatures.includes(feature.id);
                                            return (
                                                <button
                                                    key={feature.id}
                                                    type="button"
                                                    onClick={() => toggleFeature(feature.id)}
                                                    className={`p-4 rounded-2xl text-left border transition-all flex items-start gap-3.5 ${
                                                        isSelected
                                                            ? 'bg-[#00F2FE]/10 border-[#00F2FE] text-white shadow-sm'
                                                            : 'bg-[#060B18] border-slate-800/80 hover:border-slate-700 text-slate-400'
                                                    }`}
                                                >
                                                    <div className={`p-2.5 rounded-xl shrink-0 ${isSelected ? 'bg-[#00F2FE] text-[#060B18]' : 'bg-[#1C2541] text-slate-400'}`}>
                                                        <Icon className="w-4 h-4" />
                                                    </div>
                                                    <div className="flex-1 min-w-0">
                                                        <div className="flex items-center justify-between">
                                                            <h4 className="text-xs font-bold text-white">{feature.name}</h4>
                                                            <div className={`w-4 h-4 rounded-md border flex items-center justify-center ${isSelected ? 'bg-[#00F2FE] border-[#00F2FE] text-[#060B18]' : 'border-slate-700'}`}>
                                                                {isSelected && <Check className="w-3 h-3" />}
                                                            </div>
                                                        </div>
                                                        <p className="text-[11px] text-slate-400 mt-1 leading-snug">{feature.desc}</p>
                                                    </div>
                                                </button>
                                            );
                                        })}
                                    </div>

                                    <div className="flex justify-between pt-4">
                                        <button
                                            type="button"
                                            onClick={() => setStep(2)}
                                            className="px-5 py-2.5 rounded-xl text-xs font-semibold bg-[#060B18] text-slate-400 hover:text-white border border-slate-800 flex items-center gap-1.5"
                                        >
                                            <ArrowLeft className="w-4 h-4" /> Back
                                        </button>
                                        <button
                                            type="button"
                                            onClick={() => setStep(4)}
                                            className="px-6 py-3 rounded-xl text-xs font-bold bg-gradient-to-r from-[#00F2FE] to-[#4FACFE] text-[#060B18] hover:opacity-95 flex items-center gap-2 shadow-md"
                                        >
                                            Next: Design Tier <ArrowRight className="w-4 h-4" />
                                        </button>
                                    </div>
                                </div>
                            )}

                            {/* Step 4: Design Tier */}
                            {step === 4 && (
                                <div className="p-6 sm:p-8 rounded-3xl bg-[#0B132B] border border-slate-800 space-y-6 animate-in fade-in">
                                    <div className="space-y-1">
                                        <h3 className="text-lg font-bold text-white">Step 4: UI/UX & Design Tier</h3>
                                        <p className="text-xs text-slate-400">Choose how UI/UX design and wireframing will be handled.</p>
                                    </div>

                                    <div className="space-y-3">
                                        {DESIGN_TIERS.map((tier) => {
                                            const isSelected = selectedDesign === tier.id;
                                            return (
                                                <button
                                                    key={tier.id}
                                                    type="button"
                                                    onClick={() => setSelectedDesign(tier.id)}
                                                    className={`w-full p-5 rounded-2xl text-left border flex items-center justify-between transition-all ${
                                                        isSelected
                                                            ? 'bg-[#00F2FE]/10 border-[#00F2FE] text-white shadow-lg shadow-cyan-500/10'
                                                            : 'bg-[#060B18] border-slate-800 hover:border-slate-700 text-slate-300'
                                                    }`}
                                                >
                                                    <div className="space-y-1">
                                                        <h4 className="text-sm font-bold text-white">{tier.title}</h4>
                                                        <p className="text-xs text-slate-400">{tier.desc}</p>
                                                    </div>
                                                    <div className={`w-6 h-6 rounded-full border flex items-center justify-center ${isSelected ? 'bg-[#00F2FE] border-[#00F2FE] text-[#060B18]' : 'border-slate-700'}`}>
                                                        {isSelected && <Check className="w-3.5 h-3.5" />}
                                                    </div>
                                                </button>
                                            );
                                        })}
                                    </div>

                                    <div className="flex justify-between pt-4">
                                        <button
                                            type="button"
                                            onClick={() => setStep(3)}
                                            className="px-5 py-2.5 rounded-xl text-xs font-semibold bg-[#060B18] text-slate-400 hover:text-white border border-slate-800 flex items-center gap-1.5"
                                        >
                                            <ArrowLeft className="w-4 h-4" /> Back
                                        </button>
                                        <button
                                            type="button"
                                            onClick={() => setStep(5)}
                                            className="px-6 py-3 rounded-xl text-xs font-bold bg-gradient-to-r from-[#00F2FE] to-[#4FACFE] text-[#060B18] hover:opacity-95 flex items-center gap-2 shadow-md"
                                        >
                                            Review & Get Detailed Proposal <ArrowRight className="w-4 h-4" />
                                        </button>
                                    </div>
                                </div>
                            )}

                            {/* Step 5: Submit Proposal & Lead Form */}
                            {step === 5 && (
                                <div className="p-6 sm:p-8 rounded-3xl bg-[#0B132B] border border-slate-800 space-y-6 animate-in fade-in">
                                    <div className="space-y-1">
                                        <h3 className="text-lg font-bold text-white">Step 5: Receive Your Full Architectural Proposal</h3>
                                        <p className="text-xs text-slate-400">
                                            Enter your contact details to lock in this estimate and receive our formal technical specification and milestone breakdown.
                                        </p>
                                    </div>

                                    {submitError && (
                                        <div className="p-4 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-400 text-xs">
                                            {submitError}
                                        </div>
                                    )}

                                    <form onSubmit={handleSubmit} className="space-y-4">
                                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                            <div>
                                                <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Your Full Name *</label>
                                                <input
                                                    type="text"
                                                    required
                                                    value={clientName}
                                                    onChange={(e) => setClientName(e.target.value)}
                                                    placeholder="Alex Johnson"
                                                    className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                                />
                                            </div>

                                            <div>
                                                <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Work Email Address *</label>
                                                <input
                                                    type="email"
                                                    required
                                                    value={clientEmail}
                                                    onChange={(e) => setClientEmail(e.target.value)}
                                                    placeholder="alex@company.com"
                                                    className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                                />
                                            </div>
                                        </div>

                                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                            <div>
                                                <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Phone / WhatsApp (Optional)</label>
                                                <input
                                                    type="text"
                                                    value={clientPhone}
                                                    onChange={(e) => setClientPhone(e.target.value)}
                                                    placeholder="+1 (555) 000-0000"
                                                    className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                                />
                                            </div>

                                            <div>
                                                <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Company / Organization (Optional)</label>
                                                <input
                                                    type="text"
                                                    value={companyName}
                                                    onChange={(e) => setCompanyName(e.target.value)}
                                                    placeholder="Apex Labs Inc"
                                                    className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                                />
                                            </div>
                                        </div>

                                        <div>
                                            <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Project Notes or Specific Needs (Optional)</label>
                                            <textarea
                                                rows={3}
                                                value={clientNotes}
                                                onChange={(e) => setClientNotes(e.target.value)}
                                                placeholder="Tell us any specific APIs, deadline targets, or existing systems to integrate..."
                                                className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                            />
                                        </div>

                                        <div className="flex justify-between pt-4 border-t border-slate-800">
                                            <button
                                                type="button"
                                                onClick={() => setStep(4)}
                                                className="px-5 py-2.5 rounded-xl text-xs font-semibold bg-[#060B18] text-slate-400 hover:text-white border border-slate-800 flex items-center gap-1.5"
                                            >
                                                <ArrowLeft className="w-4 h-4" /> Back
                                            </button>

                                            <button
                                                type="submit"
                                                disabled={submitting}
                                                className="px-8 py-3 rounded-xl text-xs font-bold bg-gradient-to-r from-[#00F2FE] to-[#4FACFE] text-[#060B18] hover:opacity-95 shadow-lg shadow-cyan-500/20 flex items-center gap-2"
                                            >
                                                <Send className="w-4 h-4" />
                                                {submitting ? 'Submitting Scope...' : 'Submit & Receive Technical Proposal'}
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            )}
                        </div>

                        {/* Right: Live Dynamic Summary Card */}
                        <div className="lg:col-span-4 sticky top-28 space-y-4">
                            <div className="p-6 rounded-3xl bg-[#0B132B] border border-cyan-500/30 shadow-xl space-y-6">
                                <div className="flex items-center justify-between pb-4 border-b border-slate-800">
                                    <div className="flex items-center gap-2">
                                        <Calculator className="w-4 h-4 text-[#00F2FE]" />
                                        <h3 className="text-xs font-bold text-white uppercase tracking-wider">Live Scope Estimate</h3>
                                    </div>
                                    <span className="text-[10px] text-cyan-400 font-mono font-bold bg-cyan-950/60 px-2 py-0.5 rounded-full border border-cyan-500/30">
                                        Step {step} of 5
                                    </span>
                                </div>

                                {/* Budget Display */}
                                <div className="p-5 rounded-2xl bg-[#060B18] border border-slate-800/80 space-y-1">
                                    <span className="text-[11px] font-bold text-slate-400 uppercase tracking-wider flex items-center gap-1">
                                        <DollarSign className="w-3 h-3 text-[#00F2FE]" /> Estimated Budget Range
                                    </span>
                                    <div className="text-2xl sm:text-3xl font-extrabold bg-gradient-to-r from-[#00F2FE] to-[#4FACFE] bg-clip-text text-transparent">
                                        ${calculation.minBudget.toLocaleString()} – ${calculation.maxBudget.toLocaleString()}
                                    </div>
                                    <p className="text-[10px] text-slate-500 font-mono">
                                        Estimated based on current sprint velocities & scope.
                                    </p>
                                </div>

                                {/* Timeline Display */}
                                <div className="p-4 rounded-2xl bg-[#060B18] border border-slate-800/80 flex items-center gap-3">
                                    <div className="w-9 h-9 rounded-xl bg-[#1C2541] text-[#00F2FE] flex items-center justify-center shrink-0">
                                        <Clock className="w-4 h-4" />
                                    </div>
                                    <div>
                                        <span className="text-[10px] font-bold text-slate-400 uppercase">Estimated Sprint Timeline</span>
                                        <p className="text-sm font-bold text-white">{calculation.weeksMin} – {calculation.weeksMax} Weeks</p>
                                    </div>
                                </div>

                                {/* Specification Breakdown */}
                                <div className="space-y-2 pt-2 border-t border-slate-800 text-xs">
                                    <div className="flex justify-between py-1 border-b border-slate-800/40">
                                        <span className="text-slate-400">Solution:</span>
                                        <span className="text-slate-200 font-medium">{calculation.typeTitle}</span>
                                    </div>
                                    <div className="flex justify-between py-1 border-b border-slate-800/40">
                                        <span className="text-slate-400">Scale Tier:</span>
                                        <span className="text-slate-200 font-medium">{calculation.scaleTitle}</span>
                                    </div>
                                    <div className="flex justify-between py-1 border-b border-slate-800/40">
                                        <span className="text-slate-400">Active Features:</span>
                                        <span className="text-cyan-300 font-mono font-bold">{calculation.featureCount} modules</span>
                                    </div>
                                </div>

                                <div className="pt-2">
                                    <p className="text-[11px] text-slate-400 leading-relaxed text-center">
                                        All estimations include dedicated QA testing, automated CI/CD deployment pipelines, and 30-day post-launch warranty.
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                )}
            </main>

            <PublicFooter />
        </div>
    );
}
