
"use client";

import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Briefcase, Target, LineChart, BookOpen, ArrowRight, ShieldCheck, Zap, Coins, Link2, Rocket, LayoutTemplate, Box, Hash, Combine, Cog, TrendingUp, CheckCircle, Headset, Users, GraduationCap, Plus, Twitter, Instagram, Facebook, Loader2, Phone, MessageSquare } from 'lucide-react';
import React, { useEffect, useState, useRef } from 'react';
import { db } from '@/lib/firebase';
import { doc, getDoc, collection, query, where, getDocs, orderBy, limit } from 'firebase/firestore';
import Image from 'next/image';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Header } from '@/components/layout/header';
import { Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious } from '@/components/ui/carousel';
import Autoplay from "embla-carousel-autoplay";
import ReactMarkdown from 'react-markdown';
import TradingViewWidget from '@/components/ui/trading-view-widget';
import { useAuth } from '@/hooks/use-auth';
import { useRouter } from 'next/navigation';
import { usePreloader } from '@/components/providers/preloader-provider';
import { Skeleton } from '@/components/ui/skeleton';

interface InvestmentPlan {
  id: string;
  planName: string;
  minAmount: number;
  maxAmount: number;
  investmentType: 'fixed' | 'range';
  interestRate: number;
  returnPeriod: 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' | 'lifetime';
  termDuration: number;
  capitalBack: boolean;
  featured: boolean;
  returnPayout: boolean;
  createdAt: any;
  blockedDays: string[];
  imageUrl?: string;
}

interface PlanFeature {
    id: string;
    label: string;
    key: 'interest' | 'capitalBack' | 'payout' | 'recurrence' | 'blockedDays' | 'claimNeeded' | 'minAmount' | 'maxAmount' | 'totalReturn';
}

interface InvestmentTemplate {
    id: string;
    name: string;
    active: boolean;
    cardBackgroundColor: string;
    cardBackgroundColor2?: string;
    cardBackgroundOverlayColor?: string;
    planNameColor: string;
    amountColor: string;
    featureTextColor: string;
    featureValueColor: string;
    separatorColor: string;
    buttonBackgroundColor: string;
    buttonTextColor: string;
    buttonText: string;
    featureBackgroundColor?: string;
    features: PlanFeature[];
}

interface FeatureListData {
    title: string;
}
interface StatData {
    value: string;
    label: string;
}
interface PortfolioFeatureData {
    title: string;
}
interface BenefitData {
    title: string;
    description: string;
}
interface UpgradeFeatureData {
    title: string;
}
interface FaqData {
    question: string;
    answer: string;
}
interface ThemeColors {
    primary: string;
    background: string;
    accent: string;
}
interface BlogPost {
  id: string;
  title: string;
  content: string[];
  imageUrl: string;
  status: 'draft' | 'published';
  buttonText?: string;
  buttonLink?: string;
}
interface CryptoCoin {
    name: string;
    price: string;
    category: string;
    icon: string;
}
interface SupportPageData {
    whatsappUrl?: string;
    phone?: string;
    telegramUrl?: string;
}
interface CustomHtmlSection {
    id: string;
    name: string;
    html: string;
}
interface TemplateData {
  sectionOrder: string[];
  showHero: boolean;
  showPartners: boolean;
  showFeaturedPlans: boolean;
  showFeatures: boolean;
  showStats: boolean;
  showMultiOption: boolean;
  showPortfolio: boolean;
  showUpgrade: boolean;
  showBenefits: boolean;
  showFaqs: boolean;
  showCta: boolean;
  showBlog: boolean;
  showCryptoCoins: boolean;
  headerLogoText: string;
  showLogoTextWithImage: boolean;
  logoWidth?: number;
  logoHeight?: number;
  headerNavFeature: string;
  headerNavBenefits: string;
  headerNavServices: string;
  headerNavUpgrade: string;
  headerNavFAQs: string;
  heroTitle: string;
  heroSubtitle: string;
  heroImageUrls: string[];
  heroBackgroundImageUrl: string;
  heroOverlayColor: string;
  heroShowCarouselArrows: boolean;
  heroCarouselSpeed: number;
  heroSliderWidth?: number;
  heroSliderHeight?: number;
  partnersTitle: string;
  partnersLogoUrls: string[];
  featuredPlansSubtitle: string;
  featuredPlansTitle: string;
  featuresSectionSubtitle: string;
  featuresSectionTitle: string;
  featuresList: FeatureListData[];
  featuresImageUrl: string;
  stats: StatData[];
  multiOptionSubtitle: string;
  multiOptionTitle: string;
  multiOptionImageUrl: string;
  planningTitle: string;
  planningDescription: string;
  refinementTitle: string;
  refinementDescription: string;
  prototypeTitle: string;
  prototypeDescription: string;
  scaleTitle: string;
  scaleDescription: string;
  benefitsSubtitle: string;
  benefitsTitle: string;
  benefitsDescription: string;
  benefits: BenefitData[];
  upgradeSubtitle: string;
  upgradeTitle: string;
  upgradeDescription: string;
  upgradeFeatures: UpgradeFeatureData[];
  upgradeImageUrl: string;
  portfolioSectionSubtitle: string;
  portfolioSectionTitle: string;
  portfolioSectionDescription: string;
  portfolioImageUrl: string;
  portfolioFeatures: PortfolioFeatureData[];
  faqSubtitle: string;
  faqTitle: string;
  faqDescription: string;
  faqs: FaqData[];
  ctaTitle: string;
  ctaSubtitle: string;
  themeColors: ThemeColors;
  loginTitle: string;
  loginSubtitle: string;
  signupTitle: string;
  signupSubtitle: string;
  logoUrl: string;
  blogTitle: string;
  blogSubtitle: string;
  cryptoSectionSubtitle: string;
  cryptoSectionTitle: string;
  cryptoCoins: CryptoCoin[];
  supportPage: SupportPageData;
  tawkToScript: string;
  customHtmlSections?: CustomHtmlSection[];
}

const initialData: TemplateData = {
  sectionOrder: ['hero', 'partners', 'cryptoCoins', 'featuredPlans', 'blog', 'features', 'stats', 'multiOption', 'portfolio', 'upgrade', 'benefits', 'faqs', 'cta'],
  showHero: true,
  showPartners: true,
  showFeaturedPlans: true,
  showFeatures: true,
  showStats: true,
  showMultiOption: true,
  showPortfolio: true,
  showUpgrade: true,
  showBenefits: true,
  showFaqs: true,
  showCta: true,
  showBlog: true,
  showCryptoCoins: true,
  cryptoSectionSubtitle: "Featured crypto coins",
  cryptoSectionTitle: "Top crypto coins updates",
  cryptoCoins: [
    { name: 'BitCoin', price: '$111321', category: 'Highest volume', icon: 'https://i.postimg.cc/4x0jST83/Bitcoin.png' },
    { name: 'Ethereum', price: '$4660.11', category: 'Top gainer', icon: 'https://i.postimg.cc/VvV9b4q2/Ethereum.png' },
    { name: 'Litecoin', price: '$112.33', category: 'New listing', icon: 'https://i.postimg.cc/9QJgvgJ3/Litecoin.png' },
    { name: 'Polkadot', price: '$3.92', category: 'Most traded', icon: 'https://i.postimg.cc/G3x7B4zM/Polkadot.png' },
    { name: 'Solana', price: '$198.73', category: 'Biggest gainers', icon: 'https://i.postimg.cc/PrN4k6S7/Solana.png' },
    { name: 'Chainlink', price: '$24.59', category: 'Trending', icon: 'https://i.postimg.cc/L82v4XvJ/Chainlink.png' },
  ],
  blogTitle: 'From Our Blog',
  blogSubtitle: 'Latest news and insights from our team.',
  headerLogoText: 'WealthWise',
  showLogoTextWithImage: true,
  headerNavFeature: 'Features',
  headerNavBenefits: 'Benefits',
  headerNavServices: 'Our Process',
  headerNavUpgrade: 'Security',
  headerNavFAQs: 'FAQs',
  heroTitle: 'Build Your Future with Smart Investments',
  heroSubtitle: 'A modern platform to grow your wealth with tailored investment plans and expert guidance.',
  heroImageUrls: ['https://i.postimg.cc/T3N0F23G/hero-image.png'],
  heroBackgroundImageUrl: '',
  heroOverlayColor: 'rgba(0, 0, 0, 0.5)',
  heroShowCarouselArrows: true,
  heroCarouselSpeed: 5000,
  partnersTitle: 'Trusted by top financial platforms',
  partnersLogoUrls: [
    'https://i.postimg.cc/PqYpW1s1/logoipsum-221.png',
    'https://i.postimg.cc/W3hB1gV1/logoipsum-222.png',
    'https://i.postimg.cc/L8WkPPC3/logoipsum-223.png',
    'https://i.postimg.cc/jST3m9g3/logoipsum-224.png',
    'https://i.postimg.cc/6pW6dJ0G/logoipsum-225.png',
    'https://i.postimg.cc/WbSjG4M3/logoipsum-226.png',
  ],
  featuredPlansSubtitle: 'Our Top Plans',
  featuredPlansTitle: 'Explore Our Featured Investment Plans',
  featuresSectionSubtitle: 'Why Choose Us',
  featuresSectionTitle: 'Unlock Your Financial Potential with Our Tools',
  featuresList: [
    { title: 'Personalized Investment Strategies' },
    { title: 'Track Your Portfolio in Real-Time' },
    { title: 'Secure and Transparent Platform' },
    { title: 'Expert Support and Guidance' },
  ],
  featuresImageUrl: 'https://i.postimg.cc/d1Qz8s2H/features-image.png',
  stats: [
      { value: '10K+', label: 'Active Investors' },
      { value: '24/7', label: 'Support' },
      { value: '$50M+', label: 'Assets Managed' },
      { value: '99.9%', label: 'Uptime' },
  ],
  multiOptionSubtitle: 'Our Process',
  multiOptionTitle: 'A Streamlined Journey to Your Financial Goals',
  multiOptionImageUrl: 'https://i.postimg.cc/8z7tQ3bY/process-image.png',
  planningTitle: 'Discovery',
  planningDescription: 'Understand your financial goals and risk tolerance.',
  refinementTitle: 'Strategy',
  refinementDescription: 'Develop a personalized investment strategy for you.',
  prototypeTitle: 'Execution',
  prototypeDescription: 'Implement your strategy with our powerful tools.',
  scaleTitle: 'Monitoring',
  scaleDescription: 'Continuously monitor and adjust your portfolio for success.',
  benefitsSubtitle: 'Always by your side',
  benefitsTitle: 'The Benefits of Investing With Us',
  benefitsDescription: 'Get expert guidance and powerful tools to achieve your financial dreams.',
  benefits: [
      { title: '24/7 Support', description: 'Our expert team is always here to help you navigate your investment journey.' },
      { title: 'Community', description: 'Join a community of like-minded investors and share insights.' },
      { title: 'Education', description: 'Access our free resources to learn more about smart investing.' },
  ],
  upgradeSubtitle: 'Our Commitment',
  upgradeTitle: 'A Secure & Reliable Investment Platform',
  upgradeDescription: 'We are committed to providing a secure, reliable, and user-friendly platform for all your investment needs.',
  upgradeFeatures: [
      { title: 'User friendly interface' },
      { title: 'Secure and reliable' },
      { title: 'Fast and efficient' },
      { title: '24/7 support' },
      { title: 'Advanced trading tools' },
      { title: 'Mobile app' },
      { title: 'API access' },
      { title: 'Low fees' },
  ],
  upgradeImageUrl: 'https://i.postimg.cc/J0P7dFwN/security-image.png',
  portfolioSectionSubtitle: 'Your Portfolio',
  portfolioSectionTitle: 'Take Control of Your Financial Future',
  portfolioSectionDescription: 'Our platform gives you the tools to manage your portfolio effectively.',
  portfolioImageUrl: 'https://i.postimg.cc/NfK6B0V9/portfolio-image.png',
  portfolioFeatures: [
    { title: 'Manage your portfolio' },
    { title: 'Vault protection' },
    { title: 'Mobile apps' },
  ],
  faqSubtitle: 'Popular questions',
  faqTitle: 'Frequently Asked Questions',
  faqDescription: 'Find answers to common questions about our platform and services.',
  faqs: [
    { question: 'What is this platform?', answer: 'We are a modern investment platform that helps you grow your wealth with personalized plans and expert guidance.' },
    { question: 'Is my investment secure?', answer: 'Yes, security is our top priority. We use industry-standard security measures to protect your assets and personal information.' },
    { question: 'What are the fees?', answer: 'We believe in transparent pricing. Our fee structure is simple and competitive. Please visit our pricing page for more details.' },
    { question: 'How do I get started?', answer: 'Getting started is easy! Simply sign up for an account, complete our short questionnaire, and you can start investing in minutes.' },
    { question: 'Can I withdraw my money?', answer: 'Yes, you can withdraw your funds at any time, subject to the terms of your chosen investment plan.' },
    { question: 'Do you offer support?', answer: 'Absolutely. Our dedicated support team is available 24/7 to assist you with any questions or issues you may have.' },
  ],
  ctaTitle: 'Ready to Start Your Investment Journey?',
  ctaSubtitle: 'Create an account today and take the first step towards a brighter financial future.',
  themeColors: {
    primary: '142 76% 56%',
    background: '222 47% 11%',
    accent: '142 76% 56%'
  },
  loginTitle: 'Welcome Back',
  loginSubtitle: 'Enter your credentials to access your account.',
  signupTitle: 'Create an Account',
  signupSubtitle: 'Start your journey to financial wisdom today.',
  logoUrl: '',
  logoWidth: 32,
  logoHeight: 32,
  supportPage: {
    whatsappUrl: '+94773543361',
    phone: '',
    telegramUrl: ''
  },
  tawkToScript: '<!--Start of Tawk.to Script-->\n<script type="text/javascript">\nvar Tawk_API=Tawk_API||{};\nTawk_API.visitor = {\nname: \'Vistor\',\nemail: \'vistor@example.com\'\n};\nTawk_API.onLoad = function(){\nTawk_API.maximize();\n};\nvar Tawk_LoadStart=new Date();\n(function(){\nvar s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];\ns1.async=true;\ns1.src=\'https://embed.tawk.to/6695333beaf35fe675ee8f9b/1i2s835do\';\ns1.charset=\'UTF-8\';\ns1.setAttribute(\'crossorigin\',\'*\');\ns0.parentNode.insertBefore(s1,s0);\n})();\n</script>\n<!--End of Tawk.to Script-->',
  customHtmlSections: [],
};

interface CurrencySettings {
  symbol: string;
  position: 'left' | 'right';
}

const benefitIcons = [
    <Headset key="support" className="h-8 w-8 text-primary" />,
    <Users key="community" className="h-8 w-8 text-primary" />,
    <GraduationCap key="academy" className="h-8 w-8 text-primary" />,
];


export default function Home() {
  const { user, loading: authLoading } = useAuth();
  const { appLoading } = usePreloader();
  const router = useRouter();
  const [data, setData] = useState<TemplateData>(initialData);
  const [loading, setLoading] = useState(true);
  const [featuredPlans, setFeaturedPlans] = useState<InvestmentPlan[]>([]);
  const [blogPosts, setBlogPosts] = useState<BlogPost[]>([]);
  const [investmentTemplate, setInvestmentTemplate] = useState<InvestmentTemplate | null>(null);
  const [currency, setCurrency] = useState<CurrencySettings>({ symbol: '$', position: 'left' });
  const autoplayPlugin = React.useRef(Autoplay({ delay: data.heroCarouselSpeed || 5000, stopOnInteraction: false }));

  useEffect(() => {
    autoplayPlugin.current.options.delay = data.heroCarouselSpeed || 5000;
  }, [data.heroCarouselSpeed]);
  
  useEffect(() => {
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animate-fade-in');
            }
        });
    }, { threshold: 0.1 });

    const targets = document.querySelectorAll('.scroll-animate');
    targets.forEach(target => observer.observe(target));

    return () => targets.forEach(target => observer.unobserve(target));
  }, [loading]);

  useEffect(() => {
    const fetchData = async () => {
      if (!db) {
        setLoading(false);
        return;
      }
      try {
        const docRef = doc(db, 'template', 'landingPage');
        const docSnap = await getDoc(docRef);
        if (docSnap.exists()) {
          const fetchedData = docSnap.data() as TemplateData;
           setData({ ...initialData, ...fetchedData });
           if(fetchedData.themeColors) {
             document.documentElement.style.setProperty('--primary', fetchedData.themeColors.primary);
             document.documentElement.style.setProperty('--background', fetchedData.themeColors.background);
             document.documentElement.style.setProperty('--accent', fetchedData.themeColors.accent);
           }
        }

        const currencyDoc = await getDoc(doc(db, "settings", "currency"));
        if (currencyDoc.exists()) {
          setCurrency(currencyDoc.data() as CurrencySettings);
        }
        
        const investmentTemplateDoc = doc(db, "settings", "investmentTemplates");
        const investmentTemplateSnap = await getDoc(investmentTemplateDoc);
        if (investmentTemplateSnap.exists()) {
          const templates = investmentTemplateSnap.data().templates as InvestmentTemplate[];
          setInvestmentTemplate(templates.find(t => t.active) || templates[0] || null);
        }
        
        const plansQuery = query(collection(db, "investmentPlans"), where("featured", "==", true), where("status", "==", "active"));
        const plansSnapshot = await getDocs(plansQuery);
        const plansData = plansSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })) as InvestmentPlan[];
        setFeaturedPlans(plansData);

        // Fetch all blog posts and filter/sort on the client
        const postsQuery = query(collection(db, "blogPosts"), where("status", "==", "published"), orderBy("publishedAt", "desc"));
        const postsSnapshot = await getDocs(postsQuery);
        const postsData = postsSnapshot.docs
            .map(doc => {
                const postData = doc.data();
                return { id: doc.id, ...postData, content: Array.isArray(postData.content) ? postData.content : [postData.content] } as BlogPost
            })
            .slice(0, 3); // Take the latest 3 published posts
        setBlogPosts(postsData);

      } catch (error) {
        console.error("Error fetching landing page data:", error);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  const pageFeatures = [
    { icon: <Target className="h-6 w-6 text-primary"/>, title: data.featuresList?.[0]?.title},
    { icon: <LineChart className="h-6 w-6 text-primary"/>, title: data.featuresList?.[1]?.title},
    { icon: <ShieldCheck className="h-6 w-6 text-primary"/>, title: data.featuresList?.[2]?.title},
    { icon: <BookOpen className="h-6 w-6 text-primary"/>, title: data.featuresList?.[3]?.title},
  ];

  const multiOptionFeatures = [
    { icon: <Hash className="h-6 w-6 text-primary"/>, title: data.planningTitle, description: data.planningDescription },
    { icon: <Combine className="h-6 w-6 text-primary"/>, title: data.refinementTitle, description: data.refinementDescription },
    { icon: <Cog className="h-6 w-6 text-primary"/>, title: data.prototypeTitle, description: data.prototypeDescription },
    { icon: <TrendingUp className="h-6 w-6 text-primary"/>, title: data.scaleTitle, description: data.scaleDescription },
  ];
  
  const upgradePageFeatures = data.upgradeFeatures.map(feature => ({
      icon: <CheckCircle className="h-6 w-6 text-primary" />,
      title: feature.title,
  }));
  
  const portfolioPageFeatures = [
      { icon: <CheckCircle className="h-6 w-6 text-primary"/>, title: data.portfolioFeatures?.[0]?.title},
      { icon: <ShieldCheck className="h-6 w-6 text-primary"/>, title: data.portfolioFeatures?.[1]?.title},
      { icon: <Zap className="h-6 w-6 text-primary"/>, title: data.portfolioFeatures?.[2]?.title},
  ];

  const formatCurrency = (amount: number) => {
    const value = amount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2});
    return currency.position === 'left' ? `${currency.symbol}${value}` : `${value}${currency.symbol}`;
  };
  
  const getFeatureValue = (plan: InvestmentPlan, key: PlanFeature['key'], templateId: string = 'default') => {
      const isGreenPluss = templateId === 'green_pluss';

      switch(key) {
          case 'interest':
              return <span className="font-medium">{plan.interestRate}% {plan.returnPeriod.charAt(0).toUpperCase() + plan.returnPeriod.slice(1)}</span>
          case 'capitalBack':
             return plan.capitalBack ? (
                <Badge variant="outline" className={isGreenPluss ? "bg-green-500/10 text-green-400 border-none" : "text-green-500 border-green-500/50 bg-green-500/10"}>YES</Badge>
            ) : (
                 <Badge variant="outline" className={isGreenPluss ? "bg-red-500/10 text-red-400 border-none" : "text-red-500 border-red-500/50 bg-red-500/10"}>NO</Badge>
            )
          case 'payout':
          case 'claimNeeded':
            return <Badge variant="outline" className={isGreenPluss ? "bg-blue-500/10 text-blue-400 border-none" : "text-blue-500 border-blue-500/50 bg-blue-500/10"}>{plan.returnPayout ? 'Automatic' : 'Manual'}</Badge>
          case 'recurrence':
            return <Badge variant="outline" className={isGreenPluss ? "bg-yellow-500/10 text-yellow-400 border-none" : "text-yellow-500 border-yellow-500/50 bg-yellow-500/10"}>
                        {plan.returnPeriod === 'lifetime' ? 'Lifetime' : `${plan.termDuration} Times`}
                   </Badge>
          case 'blockedDays':
              if (plan.blockedDays && plan.blockedDays.length > 0) {
                  return <Badge variant="outline" className={isGreenPluss ? "bg-red-500/10 text-red-400 border-none" : "text-red-500 border-red-500/50 bg-red-500/10"}>{plan.blockedDays.join(', ')}</Badge>
              }
              return <Badge variant="outline" className={isGreenPluss ? "bg-green-500/10 text-green-400 border-none" : "text-green-500 border-green-500/50 bg-green-500/10"}>None</Badge>
          case 'minAmount':
              return <span>{formatCurrency(plan.minAmount)}</span>
          case 'maxAmount':
              return <span>{formatCurrency(plan.maxAmount)}</span>
          case 'totalReturn':
              const profitPerReturn = (plan.minAmount * plan.interestRate) / 100;
              const totalProfit = profitPerReturn * plan.termDuration;
              return <span>{formatCurrency(totalProfit)} + <Badge variant="default">Capital</Badge></span>
          default:
            return null;
      }
  }
  
  const renderDefaultTemplate = (plan: InvestmentPlan, tpl: InvestmentTemplate) => (
     <div 
        key={plan.id} 
        style={{ backgroundColor: tpl.cardBackgroundColor }}
        className={`p-6 rounded-2xl border ${plan.featured ? 'border-primary shadow-lg shadow-primary/20' : 'border-border/50'} flex flex-col`}
    >
        {plan.imageUrl && plan.imageUrl.trim() !== '' && (
            <div className="relative h-40 w-full mb-4 rounded-lg overflow-hidden">
                <Image src={plan.imageUrl} alt={plan.planName} layout="fill" objectFit="cover" />
            </div>
        )}
        <div className="text-center mb-6">
            <h3 className="text-xl font-bold font-headline mb-2" style={{color: tpl.planNameColor}}>{plan.planName}</h3>
            <p className="text-2xl font-bold" style={{color: tpl.amountColor}}>
                {plan.investmentType === 'range' ? `${formatCurrency(plan.minAmount)} - ${formatCurrency(plan.maxAmount)}` : formatCurrency(plan.minAmount)}
            </p>
        </div>
        
        <div className="space-y-4 flex-grow">
             {tpl.features.map((feature, index) => (
                 <React.Fragment key={index}>
                    <div className="flex justify-between items-center text-sm">
                        <span style={{ color: tpl.featureTextColor }}>{feature.label}</span>
                        <div style={{ color: tpl.featureValueColor }}>{getFeatureValue(plan, feature.key)}</div>
                    </div>
                    {index < tpl.features.length - 1 && <div style={{height: '1px', backgroundColor: tpl.separatorColor}}></div>}
                 </React.Fragment>
             ))}
        </div>

        <Button 
            className="w-full mt-6" 
            asChild
            style={{ backgroundColor: tpl.buttonBackgroundColor, color: tpl.buttonTextColor }}
        >
           <Link href="/signup">{tpl.buttonText}</Link>
        </Button>
    </div>
  );

  const renderGreenPlussTemplate = (plan: InvestmentPlan, tpl: InvestmentTemplate) => {
    const interestText = `${plan.interestRate}%`;
    const backgroundStyle = tpl.cardBackgroundColor2 
        ? { background: `linear-gradient(to bottom right, ${tpl.cardBackgroundColor}, ${tpl.cardBackgroundColor2})`, color: tpl.featureTextColor }
        : { backgroundColor: tpl.cardBackgroundColor, color: tpl.featureTextColor };

    return (
        <div 
            key={plan.id} 
            style={{...backgroundStyle, position: 'relative'}}
            className={`p-4 rounded-2xl border-2 ${plan.featured ? 'border-primary' : 'border-gray-800'} flex flex-col w-full max-w-sm mx-auto`}
        >
             <div style={{ position: 'absolute', inset: 0, backgroundColor: tpl.cardBackgroundOverlayColor || 'transparent', borderRadius: 'inherit' }}></div>
             <div className="relative z-10 flex flex-col h-full">
                <div className="text-center font-bold py-2 rounded-t-lg -mx-4 -mt-4 mb-4" style={{ backgroundColor: tpl.buttonBackgroundColor, color: tpl.buttonTextColor }}>
                    {plan.planName}
                </div>
                
                {plan.imageUrl && plan.imageUrl.trim() !== '' && (
                    <div className="relative h-40 w-full mb-4 rounded-lg overflow-hidden">
                        <Image src={plan.imageUrl} alt={plan.planName} layout="fill" objectFit="cover" />
                    </div>
                )}
                
                <div className="text-center my-4">
                    <div className="inline-block font-bold text-4xl px-4 py-2 rounded-lg" style={{ backgroundColor: tpl.buttonBackgroundColor, color: tpl.buttonTextColor }}>
                       {interestText}
                    </div>
                    <p className="text-lg mt-2 capitalize">{plan.returnPeriod}</p>
                </div>
                
                <div className="space-y-3 flex-grow mb-6">
                    {tpl.features.map((feature, index) => (
                        <div key={index} className="flex items-center gap-3 bg-gray-900/50 p-3 rounded-lg text-sm">
                            <CheckCircle className="h-5 w-5" style={{ color: tpl.buttonBackgroundColor }}/>
                            <span>{feature.label}</span>
                            <div className="font-bold ml-auto">{getFeatureValue(plan, feature.key, tpl.id)}</div>
                        </div>
                    ))}
                </div>

                <Button 
                    className="w-full mt-auto font-bold" 
                    asChild
                    style={{ backgroundColor: tpl.buttonBackgroundColor, color: tpl.buttonTextColor }}
                >
                   <Link href="/signup">{tpl.buttonText}</Link>
                </Button>
            </div>
        </div>
    );
  }
  
  const sections: Record<string, React.ReactNode> = {
    hero: data.showHero && (
        <section id="hero" className="relative scroll-animate">
          {data.heroBackgroundImageUrl && data.heroBackgroundImageUrl.trim() !== '' ? (
            <>
              <Image 
                src={data.heroBackgroundImageUrl} 
                alt="Background" 
                layout="fill" 
                objectFit="cover" 
                className="absolute inset-0 z-0"
                data-ai-hint="sky night"
                priority
              />
              <div 
                className="absolute inset-0 z-10" 
                style={{ backgroundColor: data.heroOverlayColor }}
              ></div>
            </>
          ) : null}
          <div className="relative z-20 container mx-auto px-4 sm:px-6 lg:px-8 py-20 md:py-32">
            <div className="grid md:grid-cols-2 gap-12 items-center">
              <div className="text-center md:text-left">
                <h1 className="text-4xl md:text-6xl font-headline font-bold mb-4 leading-tight">
                  {data.heroTitle}
                </h1>
                <p className="text-lg md:text-xl text-muted-foreground max-w-xl mx-auto md:mx-0 mb-8">
                  {data.heroSubtitle}
                </p>
                <div className="space-x-4">
                  <Button size="lg" asChild>
                    <Link href="/signup">
                      Get Started <ArrowRight className="ml-2 h-5 w-5" />
                    </Link>
                  </Button>
                </div>
              </div>
              <div className="relative" style={{ height: data.heroSliderHeight || 'auto' }}>
                  {data.heroImageUrls && data.heroImageUrls.length > 0 && (
                    <Carousel 
                        opts={{ loop: true }}
                        plugins={[autoplayPlugin.current]}
                        className="w-full mx-auto"
                        style={{ maxWidth: data.heroSliderWidth ? `${data.heroSliderWidth}px` : '100%'}}
                    >
                      <CarouselContent>
                        {data.heroImageUrls.filter(url => url && url.trim() !== '').map((url, index) => (
                          <CarouselItem key={index}>
                            <div className="relative aspect-square">
                                <Image 
                                    src={url} 
                                    alt={`Hero Image ${index + 1}`} 
                                    layout="fill" 
                                    objectFit="contain" 
                                    data-ai-hint="investment mobile app"
                                />
                            </div>
                          </CarouselItem>
                        ))}
                      </CarouselContent>
                      {data.heroShowCarouselArrows && (
                        <>
                          <CarouselPrevious className="left-4" />
                          <CarouselNext className="right-4" />
                        </>
                      )}
                    </Carousel>
                  )}
              </div>
            </div>
          </div>
        </section>
        ),
    partners: data.showPartners && (
      <section id="partners" className="py-12 bg-background scroll-animate">
        <div className="container mx-auto px-4 sm:px-6 lg:px-8">
          <h3 className="text-center text-muted-foreground mb-8">{data.partnersTitle}</h3>
          <div
            className="relative w-full overflow-hidden"
            style={{ maskImage: 'linear-gradient(to right, transparent, black 10%, black 90%, transparent)'}}
          >
            <div className="flex animate-scroll group-hover:pause">
              {[...data.partnersLogoUrls, ...data.partnersLogoUrls].map((logoUrl, index) => (
                <div key={index} className="flex-shrink-0 mx-8" style={{ width: '150px' }}>
                  {logoUrl && logoUrl.trim() !== '' && <Image src={logoUrl} alt={`Partner logo ${index + 1}`} width={150} height={50} objectFit="contain" />}
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>
    ),
    cryptoCoins: data.showCryptoCoins && (
          <section id="crypto-coins" className="py-20 scroll-animate">
            <div className="container mx-auto px-4 sm:px-6 lg:px-8">
              <div className="text-center mb-12">
                <p className="text-primary font-medium">{data.cryptoSectionSubtitle}</p>
                <h2 className="text-3xl md:text-4xl font-headline font-bold mt-2">{data.cryptoSectionTitle}</h2>
              </div>
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
                {data.cryptoCoins.map((coin, index) => (
                  <Card key={index} className="p-4">
                    <CardContent className="p-0">
                      <p className="text-sm text-muted-foreground mb-2">{coin.category}</p>
                      <div className="flex items-center gap-2">
                        {coin.icon && coin.icon.trim() !== '' && <Image src={coin.icon} alt={coin.name} width={24} height={24} />}
                        <div>
                          <p className="font-semibold">{coin.name}</p>
                          <p className="text-sm font-bold">{coin.price}</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </div>
          </section>
        ),
    featuredPlans: data.showFeaturedPlans && investmentTemplate && featuredPlans.length > 0 && (
        <section id="featured-plans" className="py-20 scroll-animate">
           <div className="container mx-auto px-4 sm:px-6 lg:px-8">
                <div className="text-center mb-12">
                    <p className="text-primary font-medium">{data.featuredPlansSubtitle}</p>
                    <h2 className="text-3xl md:text-4xl font-headline font-bold mt-2">{data.featuredPlansTitle}</h2>
                </div>
                <div className="flex justify-center">
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                        {featuredPlans.map((plan) => {
                           if (investmentTemplate.id === 'green_pluss') {
                               return renderGreenPlussTemplate(plan, investmentTemplate);
                           }
                           return renderDefaultTemplate(plan, investmentTemplate);
                        })}
                    </div>
                </div>
           </div>
        </section>
        ),
    blog: data.showBlog && blogPosts.length > 0 && (
            <section id="blog" className="py-20 scroll-animate">
                <div className="container mx-auto px-4 sm:px-6 lg:px-8">
                    <div className="text-center mb-12">
                        <p className="text-primary font-medium">{data.blogSubtitle}</p>
                        <h2 className="text-3xl md:text-4xl font-headline font-bold mt-2">{data.blogTitle}</h2>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
                        {blogPosts.map((post) => (
                            <Card key={post.id}>
                                <CardContent className="p-6">
                                    {post.imageUrl && post.imageUrl.trim() !== '' && (
                                    <div className="relative aspect-video mb-4">
                                        <Image src={post.imageUrl} alt={post.title} layout="fill" objectFit="cover" className="rounded-lg" />
                                    </div>
                                    )}
                                    <h3 className="text-xl font-bold font-headline mb-2">{post.title}</h3>
                                    <div className="text-muted-foreground line-clamp-3 prose prose-sm prose-invert">
                                        <ReactMarkdown>{(post.content || []).join(' ')}</ReactMarkdown>
                                    </div>
                                    <div className="mt-4">
                                        <Button variant="link" asChild className="p-0">
                                            <Link href={`/blog/${post.id}`}>Read More <ArrowRight className="ml-2 h-4 w-4" /></Link>
                                        </Button>
                                    </div>
                                </CardContent>
                            </Card>
                        ))}
                    </div>
                </div>
            </section>
        ),
    features: data.showFeatures && (
        <section id="features" className="py-20 scroll-animate">
            <div className="container mx-auto px-4 sm:px-6 lg:px-8">
                <div className="grid md:grid-cols-2 gap-12 items-center">
                    <div className="md:order-1">
                        <p className="text-primary font-semibold">{data.featuresSectionSubtitle}</p>
                        <h2 className="text-3xl md:text-4xl font-headline font-bold mt-2 mb-8">{data.featuresSectionTitle}</h2>
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                            {pageFeatures.map((feature, index) => (
                                <div key={index} className="flex items-start gap-4">
                                    <div className="bg-primary/10 p-3 rounded-full">
                                        {feature.icon}
                                    </div>
                                    <p className="font-medium">{feature.title}</p>
                                </div>
                            ))}
                        </div>
                    </div>
                    <div className="relative h-64 md:h-auto md:aspect-square md:order-2">
                        {data.featuresImageUrl && data.featuresImageUrl.trim() !== '' && <Image src={data.featuresImageUrl} alt="Investment App Features" layout="fill" objectFit="contain" data-ai-hint="investment portfolio" />}
                    </div>
                </div>
            </div>
        </section>
        ),
    stats: data.showStats && (
        <section id="stats" className="py-20 bg-card/50 scroll-animate">
            <div className="container mx-auto px-4 sm:px-6 lg:px-8">
                <div className="grid grid-cols-2 md:grid-cols-4 gap-8 text-center">
                    {data.stats.map((stat, index) => (
                        <div key={index}>
                            <h3 className="text-4xl font-bold text-primary">{stat.value}</h3>
                            <p className="text-muted-foreground mt-2">{stat.label}</p>
                        </div>
                    ))}
                </div>
            </div>
        </section>
        ),
    multiOption: data.showMultiOption && (
        <section id="services" className="py-20 scroll-animate">
          <div className="container mx-auto px-4 sm:px-6 lg:px-8">
            <div className="text-center mb-12">
                <p className="text-primary font-semibold">{data.multiOptionSubtitle}</p>
                <h2 className="text-3xl md:text-4xl font-headline font-bold mt-2 max-w-2xl mx-auto">{data.multiOptionTitle}</h2>
            </div>
            <div className="grid lg:grid-cols-3 gap-8 items-center">
              <div className="space-y-8 text-center lg:text-right">
                  {multiOptionFeatures.slice(0,2).map((feature, index) => (
                      <div key={index}>
                          <div className="flex flex-col md:flex-row items-center justify-center lg:justify-end gap-4 mb-2">
                             <h3 className="text-xl font-headline font-bold order-2 md:order-1">{feature.title}</h3>
                             <div className="bg-card/50 p-3 rounded-full order-1 md:order-2">
                                 {feature.icon}
                             </div>
                          </div>
                          <p className="text-muted-foreground">{feature.description}</p>
                      </div>
                  ))}
              </div>
              <div className="relative h-96 lg:h-[32rem] w-full hidden lg:block">
                 {data.multiOptionImageUrl && data.multiOptionImageUrl.trim() !== '' && <Image src={data.multiOptionImageUrl} alt="Investment app on phone" layout="fill" objectFit="contain" data-ai-hint="mobile app investment" />}
              </div>
               <div className="space-y-8 text-center lg:text-left">
                  {multiOptionFeatures.slice(2,4).map((feature, index) => (
                      <div key={index}>
                          <div className="flex flex-col md:flex-row items-center justify-center lg:justify-start gap-4 mb-2">
                             <div className="bg-card/50 p-3 rounded-full">
                                 {feature.icon}
                             </div>
                             <h3 className="text-xl font-headline font-bold">{feature.title}</h3>
                          </div>
                          <p className="text-muted-foreground">{feature.description}</p>
                      </div>
                  ))}
              </div>
            </div>
          </div>
        </section>
        ),
    portfolio: data.showPortfolio && (
        <section id="portfolio" className="py-20 scroll-animate">
            <div className="container mx-auto px-4 sm:px-6 lg:px-8">
                <div className="grid md:grid-cols-2 gap-12 items-center">
                    <div className="relative h-64 md:h-auto md:aspect-square md:order-1">
                         {data.portfolioImageUrl && data.portfolioImageUrl.trim() !== '' && <Image src={data.portfolioImageUrl} alt="Investment Portfolio" layout="fill" objectFit="contain" data-ai-hint="investment portfolio cards" />}
                    </div>
                    <div className="md:order-2">
                        <p className="text-primary font-semibold">{data.portfolioSectionSubtitle}</p>
                        <h2 className="text-3xl md:text-4xl font-headline font-bold mt-2 mb-4">{data.portfolioSectionTitle}</h2>
                        <p className="text-muted-foreground mb-8">{data.portfolioSectionDescription}</p>
                        <div className="space-y-6">
                            {portfolioPageFeatures.map((feature, index) => (
                                <div key={index} className="flex items-center gap-4">
                                    <div className="bg-primary/10 p-3 rounded-full">
                                        {feature.icon}
                                    </div>
                                    <p className="font-medium text-lg">{feature.title}</p>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            </div>
        </section>
        ),
    upgrade: data.showUpgrade && (
        <section id="upgrade" className="py-20 scroll-animate">
            <div className="container mx-auto px-4 sm:px-6 lg:px-8">
                <div className="grid md:grid-cols-2 gap-12 items-center">
                    <div className="md:order-1">
                        <p className="text-primary font-semibold">{data.upgradeSubtitle}</p>
                        <h2 className="text-3xl md:text-4xl font-headline font-bold mt-2 mb-4">{data.upgradeTitle}</h2>
                        <p className="text-muted-foreground mb-8">{data.upgradeDescription}</p>
                        <div className="grid grid-cols-2 gap-6">
                            {upgradePageFeatures.map((feature, index) => (
                                <div key={index} className="flex items-center gap-4">
                                    <div className="bg-primary/10 p-2 rounded-full">
                                        {feature.icon}
                                    </div>
                                    <p className="font-medium">{feature.title}</p>
                                </div>
                            ))}
                        </div>
                    </div>
                     <div className="relative h-64 md:h-auto md:aspect-video rounded-lg overflow-hidden md:order-2">
                         {data.upgradeImageUrl && data.upgradeImageUrl.trim() !== '' && <Image src={data.upgradeImageUrl} alt="Secure Investment Platform" layout="fill" objectFit="cover" data-ai-hint="financial charts" />}
                    </div>
                </div>
            </div>
        </section>
        ),
    benefits: data.showBenefits && (
        <section id="benefits" className="py-20 scroll-animate">
            <div className="container mx-auto px-4 sm:px-6 lg:px-8">
                <div className="text-center mb-12">
                    <p className="text-primary font-semibold">{data.benefitsSubtitle}</p>
                    <h2 className="text-3xl md:text-4xl font-headline font-bold mt-2">{data.benefitsTitle}</h2>
                    <p className="text-muted-foreground mt-4 max-w-2xl mx-auto">{data.benefitsDescription}</p>
                </div>
                <div className="relative bg-card/50 rounded-2xl p-8 md:p-12 overflow-hidden">
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-8 relative z-10">
                        {data.benefits.map((benefit, index) => (
                            <div key={index} className="text-center flex flex-col items-center">
                                <div className="bg-background/50 p-4 rounded-full mb-4">
                                    {benefitIcons[index]}
                                </div>
                                <h3 className="text-xl font-bold font-headline mb-2">{benefit.title}</h3>
                                <p className="text-muted-foreground">{benefit.description}</p>
                            </div>
                        ))}
                    </div>
                    <div className="absolute bottom-0 left-0 w-full h-32" style={{
                         background: 'linear-gradient(to top, hsl(var(--primary)) 0%, transparent 100%)',
                         opacity: 0.1,
                         maskImage: 'url("data:image/svg+xml,%3csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 1440 320\'%3e%3cpath fill=\'%23000000\' fill-opacity=\'1\' d=\'M0,160L48,170.7C96,181,192,203,288,218.7C384,235,480,245,576,224C672,203,768,149,864,138.7C960,128,1056,160,1152,160C1248,160,1344,128,1392,112L1440,96L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z\'%3e%3c/path%3e%3c/svg%3e")',
                         maskSize: 'cover',
                         maskRepeat: 'no-repeat',
                         maskPosition: 'bottom',
                    }}></div>
                </div>
            </div>
        </section>
        ),
    faqs: data.showFaqs && (
        <section id="faqs" className="py-20 bg-background scroll-animate">
            <div className="container mx-auto px-4 sm:px-6 lg:px-8">
                <div className="text-center mb-12">
                    <p className="text-primary font-semibold">{data.faqSubtitle}</p>
                    <h2 className="text-3xl md:text-4xl font-headline font-bold mt-2">{data.faqTitle}</h2>
                    <p className="text-muted-foreground mt-4 max-w-2xl mx-auto">{data.faqDescription}</p>
                </div>
                <div className="max-w-3xl mx-auto">
                    <Accordion type="single" collapsible className="w-full space-y-4">
                        {data.faqs.map((faq, index) => (
                            <AccordionItem value={`item-${index}`} key={index} className="bg-card/50 rounded-lg px-6 border-none">
                                <AccordionTrigger className="font-semibold text-lg text-left hover:no-underline">
                                    {faq.question}
                                </AccordionTrigger>
                                <AccordionContent className="text-base text-muted-foreground pb-6">
                                    {faq.answer}
                                </AccordionContent>
                            </AccordionItem>
                        ))}
                    </Accordion>
                </div>
            </div>
        </section>
        ),
    cta: data.showCta && (
        <section id="cta" className="container mx-auto px-4 sm:px-6 lg:px-8 py-20 text-center scroll-animate">
             <h2 className="text-3xl md:text-4xl font-headline font-bold">
                {data.ctaTitle}
              </h2>
              <p className="text-lg text-muted-foreground mt-2 mb-8 max-w-xl mx-auto">
                {data.ctaSubtitle}
              </p>
               <Button size="lg" asChild>
                <Link href="/signup">
                    Create Your Free Account <ArrowRight className="ml-2 h-5 w-5" />
                </Link>
                </Button>
        </section>
        ),
  };
  
  const orderedSections = data.sectionOrder?.map(key => {
      if (key.startsWith('html_')) {
          const customSection = data.customHtmlSections?.find(s => s.id === key);
          return customSection ? <section key={key} className="scroll-animate"><TradingViewWidget htmlContent={customSection.html} /></section> : null;
      }
      return sections[key] ? React.cloneElement(sections[key] as React.ReactElement, { key }) : null;
  }).filter(Boolean) || Object.values(sections);


  if (loading || authLoading || appLoading) {
    return (
      <div className="flex flex-col min-h-screen">
        <Header />
        <main className="flex-grow flex items-center justify-center">
            {/* The preloader is now global, so we don't need a specific loader here,
                but we can keep a simple one as a fallback. */}
        </main>
      </div>
    );
  }

  return (
    <div className="flex flex-col min-h-screen bg-background text-foreground">
      <Header />

      <main className="flex-grow">
        {orderedSections}
      </main>

       <style jsx>{`
        @keyframes scroll {
          from {
            transform: translateX(0);
          }
          to {
            transform: translateX(-50%);
          }
        }
        .animate-scroll {
          display: flex;
          animation: scroll 40s linear infinite;
        }
        .group-hover\\:pause:hover .animate-scroll {
            animation-play-state: paused;
        }
        @keyframes fade-in {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .scroll-animate {
            opacity: 0;
            transition: opacity 0.6s ease-out, transform 0.6s ease-out;
        }
        .animate-fade-in {
            animation: fade-in 0.6s ease-out forwards;
        }
      `}</style>
    </div>
  );
}
