import { Head, usePage } from '@inertiajs/react';
import { useEffect, useMemo, useState } from 'react';
import Layout from '@/Components/Layout';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
    ShoppingCart,
    Utensils,
    Factory,
    Truck,
    Briefcase,
    HeartPulse,
    GraduationCap,
    Building2,
    Users,
    Globe,
    Smartphone,
    Code2,
    Palette,
    Layers,
    PenTool,
    Server,
    Database,
    BarChart3,
    Package,
    UserCheck,
    DollarSign,
    Tag,
    Award,
    Receipt,
    Network,
    Sparkles,
    ArrowRight,
    ArrowLeft,
    Check,
    CheckCircle2,
    CircleDot,
    Clock,
    Wallet,
    Mail,
    Phone,
    Building,
    User,
    MessageSquare,
    Rocket,
    Calendar,
    Zap,
    Target,
    Headphones,
    FileText,
    Camera,
    ShieldCheck,
    Search,
    Bot,
    type LucideIcon
} from 'lucide-react';

type QuestionType = 'single' | 'multi' | 'text' | 'textarea' | 'contact';

interface Option {
    id: string;
    label: string;
    description?: string;
    icon?: LucideIcon;
    price?: number;
    color?: string;
}

interface Question {
    id: string;
    type: QuestionType;
    title: string;
    subtitle?: string;
    options?: Option[];
    placeholder?: string;
    minSelected?: number;
    optional?: boolean;
    columns?: 2 | 3 | 4;
}

interface Flow {
    key: string;
    name: string;
    tagline: string;
    accent: string;
    basePriceMin: number;
    basePriceMax: number;
    currency: string;
    steps: Question[];
}

const erpFlow: Flow = {
    key: 'erp',
    name: 'POS & ERP Solution',
    tagline: 'Configure your retail and enterprise platform',
    accent: 'from-blue-500 via-primary to-purple-500',
    basePriceMin: 3000,
    basePriceMax: 5000,
    currency: 'QAR',
    steps: [
        {
            id: 'business_type',
            type: 'single',
            title: 'What type of business are you running?',
            subtitle: "We'll tailor the ERP modules to your industry.",
            columns: 3,
            options: [
                { id: 'retail', label: 'Retail Store', description: 'Single or multi-store retail', icon: ShoppingCart, color: 'from-blue-500 to-cyan-500', price: 0 },
                { id: 'restaurant', label: 'Restaurant / Café', description: 'F&B and hospitality', icon: Utensils, color: 'from-orange-500 to-red-500', price: 500 },
                { id: 'manufacturing', label: 'Manufacturing', description: 'Production & assembly', icon: Factory, color: 'from-slate-500 to-gray-600', price: 1500 },
                { id: 'wholesale', label: 'Wholesale / Distribution', description: 'B2B distribution', icon: Truck, color: 'from-emerald-500 to-teal-500', price: 1000 },
                { id: 'service', label: 'Service Business', description: 'Consulting & services', icon: Briefcase, color: 'from-purple-500 to-pink-500', price: 0 },
                { id: 'healthcare', label: 'Healthcare / Clinic', description: 'Medical & pharma', icon: HeartPulse, color: 'from-rose-500 to-red-500', price: 1500 },
            ],
        },
        {
            id: 'company_size',
            type: 'single',
            title: 'How big is your team?',
            subtitle: 'Helps us scale licensing and infrastructure.',
            columns: 4,
            options: [
                { id: '1-10', label: '1 – 10 employees', icon: User, color: 'from-blue-500 to-cyan-500', price: 0 },
                { id: '11-50', label: '11 – 50 employees', icon: Users, color: 'from-purple-500 to-pink-500', price: 800 },
                { id: '51-200', label: '51 – 200 employees', icon: Building2, color: 'from-emerald-500 to-teal-500', price: 2000 },
                { id: '200+', label: '200+ employees', icon: Building, color: 'from-amber-500 to-orange-500', price: 4000 },
            ],
        },
        {
            id: 'modules',
            type: 'multi',
            title: 'Which modules do you need?',
            subtitle: 'Pick everything that applies — you can add or remove later.',
            minSelected: 1,
            columns: 3,
            options: [
                { id: 'pos', label: 'Point of Sale', description: 'Counter checkout', icon: Receipt, color: 'from-blue-500 to-cyan-500', price: 600 },
                { id: 'inventory', label: 'Inventory', description: 'Stock & warehouses', icon: Package, color: 'from-emerald-500 to-green-500', price: 700 },
                { id: 'crm', label: 'CRM', description: 'Customer 360°', icon: Users, color: 'from-purple-500 to-pink-500', price: 700 },
                { id: 'finance', label: 'Finance & Accounting', description: 'Books & invoicing', icon: DollarSign, color: 'from-amber-500 to-orange-500', price: 900 },
                { id: 'hr', label: 'HR & Payroll', description: 'Employees & salaries', icon: UserCheck, color: 'from-blue-600 to-indigo-600', price: 800 },
                { id: 'pricing', label: 'Pricing & Discounts', description: 'Promo engine', icon: Tag, color: 'from-indigo-500 to-purple-500', price: 400 },
                { id: 'loyalty', label: 'Loyalty & Rewards', description: 'Member programs', icon: Award, color: 'from-amber-500 to-yellow-500', price: 500 },
                { id: 'reports', label: 'Reports & Analytics', description: 'Live dashboards', icon: BarChart3, color: 'from-cyan-500 to-blue-500', price: 600 },
                { id: 'supply', label: 'Supply Chain', description: 'Vendors & logistics', icon: Network, color: 'from-slate-500 to-gray-600', price: 1000 },
            ],
        },
        {
            id: 'locations',
            type: 'single',
            title: 'How many stores or locations?',
            subtitle: 'Each additional location includes sync and reporting.',
            columns: 4,
            options: [
                { id: '1', label: '1 location', icon: Building, color: 'from-blue-500 to-cyan-500', price: 0 },
                { id: '2-5', label: '2 – 5 locations', icon: Building2, color: 'from-purple-500 to-pink-500', price: 1000 },
                { id: '6-15', label: '6 – 15 locations', icon: Layers, color: 'from-emerald-500 to-teal-500', price: 2500 },
                { id: '15+', label: '15+ locations', icon: Globe, color: 'from-amber-500 to-orange-500', price: 5000 },
            ],
        },
        {
            id: 'integrations',
            type: 'multi',
            title: 'Any integrations or special needs?',
            subtitle: 'Optional — pick anything that applies.',
            optional: true,
            columns: 3,
            options: [
                { id: 'data_migration', label: 'Migrate existing data', description: 'Import legacy records', icon: Database, color: 'from-blue-500 to-cyan-500', price: 800 },
                { id: 'ecommerce', label: 'E-commerce sync', description: 'Connect web store', icon: ShoppingCart, color: 'from-purple-500 to-pink-500', price: 700 },
                { id: 'whmcs', label: 'WHMCS integration', description: 'Billing automation', icon: Server, color: 'from-emerald-500 to-teal-500', price: 600 },
                { id: 'mobile', label: 'Mobile app', description: 'Field ops on iOS/Android', icon: Smartphone, color: 'from-violet-500 to-purple-600', price: 2500 },
                { id: 'ai_automation', label: 'AI automation', description: 'Smart alerts & forecasting', icon: Bot, color: 'from-cyan-500 to-blue-500', price: 1500 },
                { id: 'custom_api', label: 'Custom API integrations', description: 'External systems', icon: Code2, color: 'from-amber-500 to-orange-500', price: 1200 },
            ],
        },
        {
            id: 'timeline',
            type: 'single',
            title: 'When do you need this live?',
            subtitle: 'Faster timelines may include rush fees.',
            columns: 4,
            options: [
                { id: 'asap', label: 'ASAP (within 4 weeks)', icon: Zap, color: 'from-red-500 to-orange-500', price: 1500 },
                { id: '1-3m', label: '1 – 3 months', icon: Clock, color: 'from-amber-500 to-orange-500', price: 0 },
                { id: '3-6m', label: '3 – 6 months', icon: Calendar, color: 'from-blue-500 to-cyan-500', price: 0 },
                { id: 'flexible', label: 'Flexible / Planning', icon: Target, color: 'from-emerald-500 to-teal-500', price: 0 },
            ],
        },
        {
            id: 'notes',
            type: 'textarea',
            title: 'Anything specific we should know?',
            subtitle: 'Optional — share goals, pain points, or must-have features.',
            optional: true,
            placeholder: 'e.g. We need barcode-driven stocktaking, multi-warehouse transfers, and Arabic invoice templates.',
        },
        {
            id: 'contact',
            type: 'contact',
            title: 'Where should we send your proposal?',
            subtitle: "We'll review your config and respond within 24 hours.",
        },
    ],
};

const serviceFlow: Flow = {
    key: 'service',
    name: 'Custom Project',
    tagline: 'Configure your website, app, or software project',
    accent: 'from-purple-500 via-pink-500 to-orange-500',
    basePriceMin: 1500,
    basePriceMax: 3500,
    currency: 'QAR',
    steps: [
        {
            id: 'project_type',
            type: 'single',
            title: 'What are you building?',
            subtitle: "We'll customize the questions based on your project type.",
            columns: 3,
            options: [
                { id: 'website', label: 'Website', description: 'Marketing or business site', icon: Globe, color: 'from-blue-500 to-cyan-500', price: 0 },
                { id: 'webapp', label: 'Web Application', description: 'SaaS, dashboards, tools', icon: Code2, color: 'from-purple-500 to-pink-500', price: 2500 },
                { id: 'mobile', label: 'Mobile App', description: 'iOS / Android / Both', icon: Smartphone, color: 'from-emerald-500 to-teal-500', price: 4000 },
                { id: 'ecommerce', label: 'E-commerce', description: 'Online store with payments', icon: ShoppingCart, color: 'from-amber-500 to-orange-500', price: 2000 },
                { id: 'custom', label: 'Custom Software', description: 'Bespoke business platform', icon: Server, color: 'from-slate-500 to-gray-600', price: 5000 },
                { id: 'design', label: 'UI / UX Design Only', description: 'Figma + style system', icon: Palette, color: 'from-rose-500 to-red-500', price: 0 },
            ],
        },
        {
            id: 'category',
            type: 'single',
            title: 'What industry or category?',
            subtitle: 'Helps us match the right design language and tone.',
            columns: 3,
            options: [
                { id: 'business', label: 'Business / Corporate', icon: Building2, color: 'from-blue-500 to-cyan-500', price: 0 },
                { id: 'portfolio', label: 'Portfolio / Personal', icon: Camera, color: 'from-purple-500 to-pink-500', price: 0 },
                { id: 'ecommerce', label: 'E-commerce / Retail', icon: ShoppingCart, color: 'from-amber-500 to-orange-500', price: 500 },
                { id: 'education', label: 'Education / LMS', icon: GraduationCap, color: 'from-emerald-500 to-teal-500', price: 800 },
                { id: 'healthcare', label: 'Healthcare', icon: HeartPulse, color: 'from-rose-500 to-red-500', price: 1000 },
                { id: 'saas', label: 'SaaS / Software', icon: Code2, color: 'from-violet-500 to-purple-600', price: 1500 },
                { id: 'realestate', label: 'Real Estate', icon: Building, color: 'from-indigo-500 to-purple-500', price: 600 },
                { id: 'nonprofit', label: 'Nonprofit / NGO', icon: Award, color: 'from-amber-500 to-yellow-500', price: 0 },
                { id: 'other', label: 'Other / Tell us', icon: PenTool, color: 'from-slate-500 to-gray-600', price: 0 },
            ],
        },
        {
            id: 'pages',
            type: 'single',
            title: 'How many pages or screens?',
            subtitle: 'Approximate is fine — we can adjust later.',
            columns: 4,
            options: [
                { id: '1-5', label: '1 – 5 pages', description: 'Landing / brochure', icon: FileText, color: 'from-blue-500 to-cyan-500', price: 0 },
                { id: '6-15', label: '6 – 15 pages', description: 'Standard business site', icon: Layers, color: 'from-purple-500 to-pink-500', price: 600 },
                { id: '16-30', label: '16 – 30 pages', description: 'Content-heavy', icon: FileText, color: 'from-emerald-500 to-teal-500', price: 1500 },
                { id: '30+', label: '30+ pages', description: 'Large platform', icon: Database, color: 'from-amber-500 to-orange-500', price: 3000 },
            ],
        },
        {
            id: 'features',
            type: 'multi',
            title: 'Which features do you need?',
            subtitle: 'Pick everything you can think of — we will refine together.',
            minSelected: 1,
            columns: 3,
            options: [
                { id: 'auth', label: 'User Login / Auth', description: 'Sign-up, profiles', icon: ShieldCheck, color: 'from-blue-500 to-cyan-500', price: 400 },
                { id: 'payment', label: 'Payment Gateway', description: 'Stripe, PayPal, etc.', icon: Wallet, color: 'from-emerald-500 to-teal-500', price: 600 },
                { id: 'cms', label: 'Content Management', description: 'Edit pages yourself', icon: PenTool, color: 'from-purple-500 to-pink-500', price: 800 },
                { id: 'search', label: 'Search & Filtering', description: 'Smart search', icon: Search, color: 'from-amber-500 to-orange-500', price: 400 },
                { id: 'multi_lang', label: 'Multi-language', description: 'EN / BN / AR / etc.', icon: Globe, color: 'from-cyan-500 to-blue-500', price: 600 },
                { id: 'blog', label: 'Blog / News', description: 'Articles & categories', icon: FileText, color: 'from-rose-500 to-red-500', price: 300 },
                { id: 'chat', label: 'Live Chat / Support', description: 'Real-time messaging', icon: MessageSquare, color: 'from-indigo-500 to-purple-500', price: 500 },
                { id: 'admin', label: 'Admin Panel', description: 'Custom backend', icon: Server, color: 'from-slate-500 to-gray-600', price: 900 },
                { id: 'ai', label: 'AI Features', description: 'Smart automation', icon: Bot, color: 'from-violet-500 to-purple-600', price: 1500 },
            ],
        },
        {
            id: 'mobile_addon',
            type: 'single',
            title: 'Do you also need a mobile app?',
            subtitle: 'We can build native apps alongside the web product.',
            columns: 4,
            options: [
                { id: 'none', label: 'No mobile app', icon: Globe, color: 'from-slate-500 to-gray-600', price: 0 },
                { id: 'ios', label: 'iOS only', icon: Smartphone, color: 'from-blue-500 to-cyan-500', price: 3000 },
                { id: 'android', label: 'Android only', icon: Smartphone, color: 'from-emerald-500 to-teal-500', price: 3000 },
                { id: 'both', label: 'iOS + Android', icon: Smartphone, color: 'from-purple-500 to-pink-500', price: 5000 },
            ],
        },
        {
            id: 'design',
            type: 'single',
            title: 'How should we approach design?',
            subtitle: 'Custom design takes longer but produces a unique brand.',
            columns: 3,
            options: [
                { id: 'custom', label: 'Custom Design', description: 'Built for your brand', icon: Palette, color: 'from-purple-500 to-pink-500', price: 1500 },
                { id: 'template', label: 'Template-Based', description: 'Faster, more affordable', icon: Layers, color: 'from-blue-500 to-cyan-500', price: 0 },
                { id: 'existing', label: 'Use My Existing Design', description: 'You provide Figma/PSD', icon: PenTool, color: 'from-emerald-500 to-teal-500', price: 0 },
            ],
        },
        {
            id: 'timeline',
            type: 'single',
            title: 'When do you need this delivered?',
            subtitle: 'Tighter timelines may carry a rush fee.',
            columns: 4,
            options: [
                { id: 'asap', label: 'ASAP (4 – 6 weeks)', icon: Zap, color: 'from-red-500 to-orange-500', price: 1000 },
                { id: '2-3m', label: '2 – 3 months', icon: Clock, color: 'from-amber-500 to-orange-500', price: 0 },
                { id: '3-6m', label: '3 – 6 months', icon: Calendar, color: 'from-blue-500 to-cyan-500', price: 0 },
                { id: 'flexible', label: 'Flexible', icon: Target, color: 'from-emerald-500 to-teal-500', price: 0 },
            ],
        },
        {
            id: 'notes',
            type: 'textarea',
            title: 'Any references or special notes?',
            subtitle: 'Share inspiration links, must-have features, or anything else.',
            optional: true,
            placeholder: 'e.g. We love the design of stripe.com and need similar onboarding flow + integration with Mailchimp.',
        },
        {
            id: 'contact',
            type: 'contact',
            title: 'Where should we send your quote?',
            subtitle: "We'll review your config and respond within 24 hours.",
        },
    ],
};

const generalFlow: Flow = {
    key: 'general',
    name: 'New Project',
    tagline: "Let's scope your project",
    accent: 'from-primary via-blue-500 to-purple-500',
    basePriceMin: 1000,
    basePriceMax: 3000,
    currency: 'QAR',
    steps: [
        {
            id: 'project_type',
            type: 'single',
            title: 'What can we help you build?',
            subtitle: "Pick the closest match — we'll tailor follow-up questions.",
            columns: 3,
            options: [
                { id: 'website', label: 'Website', icon: Globe, color: 'from-blue-500 to-cyan-500', price: 0 },
                { id: 'webapp', label: 'Web Application', icon: Code2, color: 'from-purple-500 to-pink-500', price: 2000 },
                { id: 'mobile', label: 'Mobile App', icon: Smartphone, color: 'from-emerald-500 to-teal-500', price: 3500 },
                { id: 'ecommerce', label: 'E-commerce', icon: ShoppingCart, color: 'from-amber-500 to-orange-500', price: 1800 },
                { id: 'erp', label: 'POS / ERP', icon: Server, color: 'from-slate-500 to-gray-600', price: 4000 },
                { id: 'design', label: 'Design Only', icon: Palette, color: 'from-rose-500 to-red-500', price: 0 },
            ],
        },
        ...serviceFlow.steps.slice(1),
    ],
};

function getFlow(context: string | null): Flow {
    if (context === 'erp') return erpFlow;
    if (context === 'service') return serviceFlow;
    return generalFlow;
}

interface AnswerState {
    [questionId: string]: string | string[];
}

interface ContactState {
    name: string;
    email: string;
    phone: string;
    company: string;
}

export default function Order() {
    const { url } = usePage();
    const params = new URLSearchParams(url.includes('?') ? url.split('?')[1] : '');
    const context = params.get('context');
    const sourceService = params.get('service');

    const flow = useMemo(() => getFlow(context), [context]);
    const totalSteps = flow.steps.length;

    const [stepIndex, setStepIndex] = useState(0);
    const [answers, setAnswers] = useState<AnswerState>({});
    const [contact, setContact] = useState<ContactState>({
        name: '',
        email: '',
        phone: '',
        company: '',
    });
    const [submitted, setSubmitted] = useState(false);

    useEffect(() => {
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }, [stepIndex]);

    const currentStep = flow.steps[stepIndex];
    const progress = ((stepIndex + 1) / totalSteps) * 100;

    const priceTotal = useMemo(() => {
        let extra = 0;
        flow.steps.forEach((q) => {
            if (q.type === 'single' && q.options) {
                const id = answers[q.id] as string | undefined;
                if (id) {
                    const opt = q.options.find((o) => o.id === id);
                    if (opt?.price) extra += opt.price;
                }
            }
            if (q.type === 'multi' && q.options) {
                const ids = (answers[q.id] as string[] | undefined) ?? [];
                ids.forEach((id) => {
                    const opt = q.options!.find((o) => o.id === id);
                    if (opt?.price) extra += opt.price;
                });
            }
        });
        return {
            min: flow.basePriceMin + extra,
            max: flow.basePriceMax + Math.round(extra * 1.4),
        };
    }, [answers, flow]);

    const isStepValid = useMemo(() => {
        if (!currentStep) return false;
        if (currentStep.optional) return true;
        if (currentStep.type === 'single') return Boolean(answers[currentStep.id]);
        if (currentStep.type === 'multi') {
            const arr = (answers[currentStep.id] as string[] | undefined) ?? [];
            return arr.length >= (currentStep.minSelected ?? 1);
        }
        if (currentStep.type === 'text' || currentStep.type === 'textarea') {
            const v = answers[currentStep.id] as string | undefined;
            return Boolean(v && v.trim().length > 0);
        }
        if (currentStep.type === 'contact') {
            return Boolean(contact.name.trim() && contact.email.trim());
        }
        return true;
    }, [currentStep, answers, contact]);

    const handleSingle = (qid: string, oid: string) => {
        setAnswers((s) => ({ ...s, [qid]: oid }));
    };

    const handleMulti = (qid: string, oid: string) => {
        setAnswers((s) => {
            const cur = (s[qid] as string[] | undefined) ?? [];
            const next = cur.includes(oid) ? cur.filter((x) => x !== oid) : [...cur, oid];
            return { ...s, [qid]: next };
        });
    };

    const handleText = (qid: string, value: string) => {
        setAnswers((s) => ({ ...s, [qid]: value }));
    };

    const next = () => {
        if (stepIndex < totalSteps - 1) setStepIndex(stepIndex + 1);
        else handleSubmit();
    };
    const back = () => {
        if (stepIndex > 0) setStepIndex(stepIndex - 1);
    };

    const handleSubmit = () => {
        setSubmitted(true);
    };

    if (submitted) {
        return (
            <Layout>
                <Head title="Order Received | HomeTech" />
                <section className="min-h-[80vh] bg-slate-950 flex items-center justify-center py-20 relative overflow-hidden">
                    <div className="absolute inset-0 overflow-hidden">
                        <div className="absolute -top-40 -left-40 w-[600px] h-[600px] bg-primary/40 rounded-full mix-blend-screen filter blur-3xl animate-pulse" />
                        <div className="absolute -bottom-40 -right-40 w-[600px] h-[600px] bg-emerald-500/30 rounded-full mix-blend-screen filter blur-3xl animate-pulse" style={{ animationDelay: '2s' }} />
                    </div>
                    <div className="absolute inset-0 bg-[linear-gradient(to_right,#80808012_1px,transparent_1px),linear-gradient(to_bottom,#80808012_1px,transparent_1px)] bg-[size:48px_48px]" />

                    <div className="container mx-auto px-4 relative z-10 text-center max-w-2xl">
                        <div className="inline-flex items-center justify-center w-24 h-24 rounded-full bg-gradient-to-br from-emerald-400 to-green-600 mb-8 shadow-2xl shadow-emerald-500/50">
                            <CheckCircle2 className="w-14 h-14 text-white" />
                        </div>
                        <h1 className="text-4xl md:text-5xl lg:text-6xl font-bold text-white mb-6 leading-tight">
                            Order received,{' '}
                            <span className="bg-gradient-to-r from-emerald-400 to-cyan-400 bg-clip-text text-transparent">
                                {contact.name.split(' ')[0] || 'partner'}!
                            </span>
                        </h1>
                        <p className="text-xl text-white/70 mb-8 leading-relaxed">
                            Your {flow.name.toLowerCase()} configuration has been logged. Our team will reach out at <span className="text-cyan-300 font-semibold">{contact.email}</span> within 24 hours with a detailed proposal.
                        </p>

                        <div className="bg-white/5 backdrop-blur-sm border border-white/10 rounded-2xl p-6 mb-8">
                            <div className="flex items-center justify-between mb-3">
                                <span className="text-white/60 text-sm">Estimated investment</span>
                                <Badge className="bg-emerald-500/20 text-emerald-300 border-emerald-500/30">
                                    <Sparkles className="w-3 h-3 mr-1" />
                                    Auto-calculated
                                </Badge>
                            </div>
                            <div className="text-3xl md:text-4xl font-bold text-white">
                                {flow.currency} {priceTotal.min.toLocaleString()} – {priceTotal.max.toLocaleString()}
                            </div>
                            <div className="text-white/50 text-sm mt-2">
                                Final pricing finalized after our discovery call.
                            </div>
                        </div>

                        <div className="flex flex-wrap gap-4 justify-center">
                            <Button size="lg" className="bg-gradient-to-r from-primary to-blue-600 text-white shadow-lg shadow-primary/50">
                                <a href="/" className="flex items-center gap-2 text-white">
                                    Back to Home
                                    <ArrowRight className="w-4 h-4" />
                                </a>
                            </Button>
                            <Button size="lg" variant="outline" className="border-white/20 bg-white/5 text-white hover:bg-white/10 hover:text-white">
                                <a href="/portfolio" className="text-white">See Our Work</a>
                            </Button>
                        </div>
                    </div>
                </section>
            </Layout>
        );
    }

    const sourceLabel = sourceService
        ? `from ${sourceService.replace(/-/g, ' ')}`
        : context === 'erp'
        ? 'from POS & ERP'
        : context === 'service'
        ? 'from Services'
        : '';

    return (
        <Layout>
            <Head title={`${flow.name} | Configure your project`} />

            {/* Compact Light Header with Progress */}
            <section className="relative overflow-hidden bg-gradient-to-br from-slate-50 via-white to-blue-50/40 pt-20 pb-12 border-b border-slate-100">
                <div className="absolute inset-0 overflow-hidden">
                    <div className="absolute -top-40 -left-40 w-[500px] h-[500px] bg-primary/15 rounded-full filter blur-3xl animate-pulse" />
                    <div className="absolute -bottom-40 -right-40 w-[500px] h-[500px] bg-purple-500/15 rounded-full filter blur-3xl animate-pulse" style={{ animationDelay: '2s' }} />
                </div>
                <div className="absolute inset-0 bg-[linear-gradient(to_right,#cbd5e10a_1px,transparent_1px),linear-gradient(to_bottom,#cbd5e10a_1px,transparent_1px)] bg-[size:48px_48px]" />

                <div className="container mx-auto px-4 relative z-10">
                    <div className="max-w-5xl mx-auto">
                        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-8">
                            <div>
                                <div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white border border-slate-200 shadow-sm text-slate-700 text-xs mb-3">
                                    <span className="relative flex h-2 w-2">
                                        <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                                        <span className="relative inline-flex rounded-full h-2 w-2 bg-emerald-500"></span>
                                    </span>
                                    <span>Configuring {flow.name} {sourceLabel}</span>
                                </div>
                                <h1 className="text-3xl md:text-4xl lg:text-5xl font-bold text-slate-900 leading-tight">
                                    {flow.tagline}{' '}
                                    <span className={`bg-gradient-to-r ${flow.accent} bg-clip-text text-transparent`}>
                                        in {totalSteps} steps
                                    </span>
                                </h1>
                            </div>
                            <div className="flex items-center gap-3 text-slate-500 text-sm">
                                <CircleDot className="w-4 h-4 text-emerald-500 animate-pulse" />
                                <span>Step <span className="text-slate-900 font-bold">{stepIndex + 1}</span> of {totalSteps}</span>
                            </div>
                        </div>

                        {/* Progress Bar */}
                        <div className="relative h-2 bg-slate-200 rounded-full overflow-hidden mb-4">
                            <div
                                className={`absolute inset-y-0 left-0 bg-gradient-to-r ${flow.accent} rounded-full transition-all duration-500 shadow-lg shadow-primary/30`}
                                style={{ width: `${progress}%` }}
                            />
                        </div>

                        {/* Step Pips */}
                        <div className="flex items-center justify-between gap-1">
                            {flow.steps.map((s, idx) => (
                                <button
                                    key={s.id}
                                    onClick={() => idx < stepIndex && setStepIndex(idx)}
                                    disabled={idx > stepIndex}
                                    className={`flex-1 h-1 rounded-full transition-all ${
                                        idx <= stepIndex ? 'bg-slate-400 cursor-pointer hover:bg-slate-500' : 'bg-slate-200 cursor-not-allowed'
                                    }`}
                                    aria-label={`Go to step ${idx + 1}`}
                                />
                            ))}
                        </div>
                    </div>
                </div>
            </section>

            {/* Wizard + Summary */}
            <section className="bg-slate-50 py-12 md:py-16">
                <div className="container mx-auto px-4">
                    <div className="max-w-6xl mx-auto grid lg:grid-cols-3 gap-8">
                        {/* Left: Question Body */}
                        <div className="lg:col-span-2">
                            <div className="bg-white rounded-3xl shadow-xl border border-slate-100 p-6 md:p-10 min-h-[500px] flex flex-col">
                                <div key={currentStep.id} className="animate-in fade-in slide-in-from-right-4 duration-300 flex-1">
                                    <div className="mb-8">
                                        <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-primary/10 text-primary text-xs font-semibold mb-4">
                                            <Sparkles className="w-3 h-3" />
                                            Step {stepIndex + 1} / {totalSteps}
                                        </div>
                                        <h2 className="text-2xl md:text-3xl lg:text-4xl font-bold mb-3 text-slate-900">
                                            {currentStep.title}
                                        </h2>
                                        {currentStep.subtitle && (
                                            <p className="text-slate-600 text-base md:text-lg leading-relaxed">
                                                {currentStep.subtitle}
                                            </p>
                                        )}
                                    </div>

                                    <QuestionRenderer
                                        question={currentStep}
                                        answers={answers}
                                        contact={contact}
                                        onSingle={handleSingle}
                                        onMulti={handleMulti}
                                        onText={handleText}
                                        onContact={(field, value) => setContact((c) => ({ ...c, [field]: value }))}
                                    />
                                </div>

                                {/* Nav */}
                                <div className="flex items-center justify-between gap-4 mt-10 pt-6 border-t border-slate-100">
                                    <Button
                                        variant="ghost"
                                        onClick={back}
                                        disabled={stepIndex === 0}
                                        className="gap-2 text-slate-600 disabled:opacity-30"
                                    >
                                        <ArrowLeft className="w-4 h-4" />
                                        Back
                                    </Button>

                                    <Button
                                        size="lg"
                                        onClick={next}
                                        disabled={!isStepValid}
                                        className={`gap-2 px-8 h-12 text-base bg-gradient-to-r ${flow.accent} text-white shadow-lg shadow-primary/30 disabled:opacity-40 disabled:cursor-not-allowed group`}
                                    >
                                        {stepIndex === totalSteps - 1 ? (
                                            <>
                                                Submit Order
                                                <Rocket className="w-5 h-5 group-hover:translate-x-1 group-hover:-translate-y-0.5 transition-transform" />
                                            </>
                                        ) : (
                                            <>
                                                Continue
                                                <ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" />
                                            </>
                                        )}
                                    </Button>
                                </div>
                            </div>
                        </div>

                        {/* Right: Live Summary */}
                        <div className="lg:col-span-1">
                            <div className="lg:sticky lg:top-24 space-y-4">
                                {/* Price Card */}
                                <div className="bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 rounded-3xl p-6 text-white shadow-2xl border border-white/10 relative overflow-hidden">
                                    <div className="absolute inset-0 opacity-10">
                                        <div className="absolute top-0 right-0 w-48 h-48 bg-primary rounded-full filter blur-3xl" />
                                        <div className="absolute bottom-0 left-0 w-48 h-48 bg-purple-500 rounded-full filter blur-3xl" />
                                    </div>

                                    <div className="relative z-10">
                                        <div className="flex items-center justify-between mb-4">
                                            <span className="text-white/60 text-xs uppercase tracking-wider font-semibold">Live Estimate</span>
                                            <Badge className="bg-emerald-500/20 text-emerald-300 border-emerald-500/30 text-[10px]">
                                                <span className="relative flex h-1.5 w-1.5 mr-1.5">
                                                    <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75" />
                                                    <span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-emerald-400" />
                                                </span>
                                                Live
                                            </Badge>
                                        </div>
                                        <div className="text-3xl md:text-4xl font-bold mb-1 bg-gradient-to-r from-white to-cyan-300 bg-clip-text text-transparent">
                                            {flow.currency} {priceTotal.min.toLocaleString()}
                                        </div>
                                        <div className="text-white/60 text-sm mb-4">
                                            – {priceTotal.max.toLocaleString()} {flow.currency}
                                        </div>
                                        <div className="text-xs text-white/50 leading-relaxed">
                                            Estimate updates as you make selections. Final pricing confirmed after a 30-min discovery call.
                                        </div>
                                    </div>
                                </div>

                                {/* Selections Summary */}
                                <div className="bg-white rounded-3xl p-6 shadow-lg border border-slate-100">
                                    <h3 className="font-bold text-slate-900 mb-4 flex items-center gap-2">
                                        <CheckCircle2 className="w-5 h-5 text-emerald-500" />
                                        Your selections
                                    </h3>
                                    <div className="space-y-3 max-h-80 overflow-y-auto pr-1">
                                        {flow.steps.slice(0, stepIndex + 1).map((q) => {
                                            const renderValue = () => {
                                                if (q.type === 'single' && q.options) {
                                                    const id = answers[q.id] as string | undefined;
                                                    const opt = id ? q.options.find((o) => o.id === id) : null;
                                                    return opt?.label;
                                                }
                                                if (q.type === 'multi' && q.options) {
                                                    const ids = (answers[q.id] as string[] | undefined) ?? [];
                                                    return ids.length > 0
                                                        ? ids.map((id) => q.options!.find((o) => o.id === id)?.label).filter(Boolean).join(', ')
                                                        : null;
                                                }
                                                if (q.type === 'textarea' || q.type === 'text') {
                                                    const v = answers[q.id] as string | undefined;
                                                    return v && v.length > 60 ? v.slice(0, 60) + '…' : v;
                                                }
                                                if (q.type === 'contact') {
                                                    return contact.name ? `${contact.name} · ${contact.email}` : null;
                                                }
                                                return null;
                                            };
                                            const value = renderValue();
                                            if (!value) return null;
                                            return (
                                                <div key={q.id} className="text-sm">
                                                    <div className="text-slate-500 text-xs mb-0.5 line-clamp-1">{q.title.replace(/\?$/, '')}</div>
                                                    <div className="text-slate-900 font-semibold line-clamp-2">{value}</div>
                                                </div>
                                            );
                                        })}
                                        {Object.keys(answers).length === 0 && !contact.name && (
                                            <div className="text-sm text-slate-400 italic text-center py-6">
                                                Your selections will appear here as you build your project.
                                            </div>
                                        )}
                                    </div>
                                </div>

                                {/* Trust */}
                                <div className="bg-white rounded-3xl p-6 shadow-lg border border-slate-100">
                                    <div className="flex items-start gap-3">
                                        <div className="w-10 h-10 rounded-full bg-gradient-to-br from-emerald-400 to-teal-500 flex items-center justify-center flex-shrink-0">
                                            <Headphones className="w-5 h-5 text-white" />
                                        </div>
                                        <div>
                                            <div className="font-bold text-sm text-slate-900 mb-1">No commitment</div>
                                            <div className="text-xs text-slate-600 leading-relaxed">
                                                Submitting this form is just a request for a proposal. We'll reach out within 24 hours.
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </Layout>
    );
}

interface RendererProps {
    question: Question;
    answers: AnswerState;
    contact: ContactState;
    onSingle: (qid: string, oid: string) => void;
    onMulti: (qid: string, oid: string) => void;
    onText: (qid: string, value: string) => void;
    onContact: (field: keyof ContactState, value: string) => void;
}

function QuestionRenderer({ question, answers, contact, onSingle, onMulti, onText, onContact }: RendererProps) {
    if (question.type === 'single' && question.options) {
        const selected = answers[question.id] as string | undefined;
        const cols = question.columns ?? 3;
        const gridClass =
            cols === 4
                ? 'sm:grid-cols-2 lg:grid-cols-4'
                : cols === 2
                ? 'sm:grid-cols-2'
                : 'sm:grid-cols-2 lg:grid-cols-3';
        return (
            <div className={`grid grid-cols-1 ${gridClass} gap-3 md:gap-4`}>
                {question.options.map((opt) => {
                    const Icon = opt.icon;
                    const isSelected = selected === opt.id;
                    return (
                        <button
                            key={opt.id}
                            type="button"
                            onClick={() => onSingle(question.id, opt.id)}
                            className={`relative group text-left p-5 rounded-2xl border-2 transition-all duration-200 ${
                                isSelected
                                    ? 'border-primary bg-primary/5 shadow-lg shadow-primary/20 scale-[1.02]'
                                    : 'border-slate-200 hover:border-primary/40 hover:shadow-md bg-white'
                            }`}
                        >
                            {Icon && (
                                <div className={`w-12 h-12 mb-3 rounded-xl flex items-center justify-center bg-gradient-to-br ${opt.color ?? 'from-slate-500 to-slate-600'} shadow-md group-hover:scale-110 transition-transform`}>
                                    <Icon className="w-6 h-6 text-white" />
                                </div>
                            )}
                            <div className="font-bold text-slate-900 mb-1">{opt.label}</div>
                            {opt.description && (
                                <div className="text-xs text-slate-500 leading-relaxed">{opt.description}</div>
                            )}
                            {isSelected && (
                                <div className="absolute top-3 right-3 w-6 h-6 rounded-full bg-primary flex items-center justify-center shadow-lg">
                                    <Check className="w-4 h-4 text-white" />
                                </div>
                            )}
                        </button>
                    );
                })}
            </div>
        );
    }

    if (question.type === 'multi' && question.options) {
        const selected = (answers[question.id] as string[] | undefined) ?? [];
        const cols = question.columns ?? 3;
        const gridClass =
            cols === 4
                ? 'sm:grid-cols-2 lg:grid-cols-4'
                : cols === 2
                ? 'sm:grid-cols-2'
                : 'sm:grid-cols-2 lg:grid-cols-3';
        return (
            <>
                <div className={`grid grid-cols-1 ${gridClass} gap-3 md:gap-4`}>
                    {question.options.map((opt) => {
                        const Icon = opt.icon;
                        const isSelected = selected.includes(opt.id);
                        return (
                            <button
                                key={opt.id}
                                type="button"
                                onClick={() => onMulti(question.id, opt.id)}
                                className={`relative group text-left p-5 rounded-2xl border-2 transition-all duration-200 ${
                                    isSelected
                                        ? 'border-primary bg-primary/5 shadow-lg shadow-primary/20 scale-[1.02]'
                                        : 'border-slate-200 hover:border-primary/40 hover:shadow-md bg-white'
                                }`}
                            >
                                {Icon && (
                                    <div className={`w-12 h-12 mb-3 rounded-xl flex items-center justify-center bg-gradient-to-br ${opt.color ?? 'from-slate-500 to-slate-600'} shadow-md group-hover:scale-110 transition-transform`}>
                                        <Icon className="w-6 h-6 text-white" />
                                    </div>
                                )}
                                <div className="font-bold text-slate-900 mb-1">{opt.label}</div>
                                {opt.description && (
                                    <div className="text-xs text-slate-500 leading-relaxed">{opt.description}</div>
                                )}
                                {isSelected && (
                                    <div className="absolute top-3 right-3 w-6 h-6 rounded-full bg-primary flex items-center justify-center shadow-lg">
                                        <Check className="w-4 h-4 text-white" />
                                    </div>
                                )}
                            </button>
                        );
                    })}
                </div>
                {selected.length > 0 && (
                    <div className="mt-4 text-sm text-slate-500 flex items-center gap-2">
                        <CheckCircle2 className="w-4 h-4 text-emerald-500" />
                        {selected.length} selected
                    </div>
                )}
            </>
        );
    }

    if (question.type === 'textarea') {
        const value = (answers[question.id] as string | undefined) ?? '';
        return (
            <div>
                <textarea
                    value={value}
                    onChange={(e) => onText(question.id, e.target.value)}
                    placeholder={question.placeholder}
                    rows={6}
                    className="w-full p-4 rounded-2xl border-2 border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all resize-none text-slate-900 placeholder:text-slate-400"
                />
                <div className="text-xs text-slate-400 mt-2">{value.length} characters</div>
            </div>
        );
    }

    if (question.type === 'text') {
        const value = (answers[question.id] as string | undefined) ?? '';
        return (
            <input
                type="text"
                value={value}
                onChange={(e) => onText(question.id, e.target.value)}
                placeholder={question.placeholder}
                className="w-full p-4 rounded-2xl border-2 border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all text-slate-900 placeholder:text-slate-400"
            />
        );
    }

    if (question.type === 'contact') {
        return (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <ContactField
                    icon={User}
                    label="Full name"
                    placeholder="Your name"
                    value={contact.name}
                    onChange={(v) => onContact('name', v)}
                    required
                />
                <ContactField
                    icon={Mail}
                    label="Email address"
                    placeholder="you@example.com"
                    type="email"
                    value={contact.email}
                    onChange={(v) => onContact('email', v)}
                    required
                />
                <ContactField
                    icon={Phone}
                    label="Phone (optional)"
                    placeholder="+880 ..."
                    type="tel"
                    value={contact.phone}
                    onChange={(v) => onContact('phone', v)}
                />
                <ContactField
                    icon={Building}
                    label="Company (optional)"
                    placeholder="Company name"
                    value={contact.company}
                    onChange={(v) => onContact('company', v)}
                />
            </div>
        );
    }

    return null;
}

interface ContactFieldProps {
    icon: LucideIcon;
    label: string;
    placeholder: string;
    type?: string;
    value: string;
    onChange: (v: string) => void;
    required?: boolean;
}

function ContactField({ icon: Icon, label, placeholder, type = 'text', value, onChange, required }: ContactFieldProps) {
    return (
        <label className="block">
            <span className="text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2">
                <Icon className="w-4 h-4 text-primary" />
                {label}
                {required && <span className="text-red-500">*</span>}
            </span>
            <input
                type={type}
                value={value}
                onChange={(e) => onChange(e.target.value)}
                placeholder={placeholder}
                required={required}
                className="w-full p-4 rounded-2xl border-2 border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all text-slate-900 placeholder:text-slate-400"
            />
        </label>
    );
}
