

"use client";

import { DashboardLayout } from "@/components/layout/dashboard-layout";
import { useAuth } from "@/hooks/use-auth";
import React, { useEffect, useState, useMemo } from "react";
import { db } from "@/lib/firebase";
import { collection, doc, getDoc, onSnapshot, query, where, getDocs, orderBy, limit } from "firebase/firestore";
import { addDays, format, startOfDay } from 'date-fns';
import { ResponsiveContainer, BarChart, Bar, LineChart, Line, XAxis, YAxis, Tooltip, Legend, CartesianGrid, Cell } from 'recharts';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { ChartConfig, ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart";
import { Loader2, Star, TrendingUp as InvestmentIcon, CheckCircle, Headset, Users, GraduationCap, Plus, Twitter, Instagram, Facebook, Phone, MessageSquare, ArrowRight, LayoutDashboard, Box, Hash, Combine, Cog, TrendingUp, Zap, Coins, Link2, Rocket, Palette, FileText, BookOpen, Info, Award, CircleDollarSign, Bell, HelpCircle, Languages, Settings, Share2, Gift, Package, CreditCard, ShieldCheck, Mail, Settings2, HandCoins, Banknote, ArrowDown, ArrowUp } from "lucide-react";
import * as LucideIcons from "lucide-react";
import Link from 'next/link';
import Image from "next/image";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Progress } from "@/components/ui/progress";
import ReactMarkdown from 'react-markdown';


interface UserData {
    username?: string;
    firstName?: string;
    lastName?: string;
    balance?: number;
}

// Staking Interfaces
interface StakingPlan {
  id: string;
  planName: string;
  imageUrl?: string;
  minAmount: number;
  maxAmount: number;
  returnPercentage: number;
  durationDays: number;
  capitalBack: boolean;
  createdAt: any;
}
interface UserStake {
    id: string;
    planName: string;
    amount: number;
    status: 'active' | 'completed' | 'cancelled';
    startDate: any;
    endDate: any;
}

// Investment Interfaces
interface InvestmentPlan {
  id: string;
  planName: string;
  imageUrl?: string;
  interestRate: number;
  returnPeriod: string;
  minAmount: number;
  maxAmount: number;
  investmentType: 'fixed' | 'range';
  termDuration: number;
  capitalBack: boolean;
  featured: boolean;
  returnPayout: boolean;
  createdAt: any;
  blockedDays: string[];
}
interface UserInvestment {
    id: string;
    planName: string;
    amount: number;
    status: 'active' | 'completed';
    startDate: any;
    returnsCalculated: number;
    termDuration: number;
}

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 StakingTemplate {
    id: string;
    cardBackgroundColor: string;
    cardBackgroundColor2?: string;
    cardTextColor: string;
    planNameColor: string;
    returnPercentageColor: string;
    durationColor: string;
    detailsLabelColor: string;
    detailsValueColor: string;
    buttonBackgroundColor: string;
    buttonTextColor: string;
    badgeBackgroundColor: string;
    badgeTextColor: string;
    returnPercentageBackgroundColor?: string; // New
    durationBackgroundColor?: string; // New
}


interface IconBoxSetting {
    id: string;
    iconUrl: string;
    iconWidth: number;
    iconHeight: number;
    title: string;
    subtitle?: string;
    link: string;
    overlayColor: string; // Kept for legacy, but we'll use new fields
    boxMinWidth?: number;
    boxBackgroundColor?: string;
    iconBackgroundColor?: string;
    iconColor?: string;
}

interface IconBoxSection {
    id: string;
    title: string;
    subtitle?: string;
    boxes: IconBoxSetting[];
}

interface StatCardSetting {
    id: string;
    key: 'totalDeposits' | 'totalWithdrawals' | 'pendingDeposits' | 'pendingWithdrawals' | 'totalInvestments' | 'activeInvestments' | 'totalReturnsFromInvests' | 'totalStakes' | 'totalReturnFromStakes' | 'totalActiveStakes' | 'totalPoolInvestments' | 'totalActivePool' | 'totalReturnFromPool' | 'totalReferrals' | 'totalRefCommissions';
    title: string;
    subtitle?: string;
    icon?: string;
    imageUrl?: string;
    bgColor?: string;
    bgUrl?: string;
}

interface StatCardSection {
    id: string;
    title: string;
    subtitle?: string;
    cards: StatCardSetting[];
}

interface DashboardSectionSetting {
    key: 'welcome' | 'chart' | `stats_${string}` | `icon_boxes_${string}` | 'recentTransactions' | 'announcement' | 'staking' | 'investment';
    visible: boolean;
}

interface DashboardSettings {
    welcomeMessage?: string;
    welcomeBgUrl?: string;
    welcomeOverlayColor?: string;
    chartType: 'bar' | 'line';
    barChartColors: {
        investment: string;
        staking: string;
        pool: string;
        deposit: string;
        referral: string;
    };
    lineChartColors: {
        investment: string;
        staking: string;
        pool: string;
        deposit: string;
        referral: string;
    };
    chartSeriesVisibility: {
        investment: boolean;
        staking: boolean;
        pool: boolean;
        deposit: boolean;
        referral: boolean;
    };
    balanceBarBackgroundUrl: string;
    balanceBarOverlayColor: string;
    chartBackgroundUrl: string;
    chartOverlayColor: string;
    sections: DashboardSectionSetting[];
    statCardSections: StatCardSection[];
    iconBoxSections: IconBoxSection[];
    recentTransactionsBgUrl?: string;
    recentTransactionsOverlayColor?: string;
    announcementText?: string;
    announcementIconUrl?: string;
    announcementBgUrl?: string;
    announcementOverlayColor?: string;
    announcementSpeed?: number;
    announcementAnimationEnabled?: boolean;
    // New Staking Section fields
    stakingSectionTitle?: string;
    stakingSectionSubtitle?: string;
    stakingSectionBgUrl?: string;
    stakingSectionOverlayColor?: string;
    stakingSectionAvailableTabText?: string;
    stakingSectionMyStakesTabText?: string;
    stakingSectionCardWidth?: number;
    // New Investment Section fields
    investmentSectionTitle?: string;
    investmentSectionSubtitle?: string;
    investmentSectionBgUrl?: string;
    investmentSectionOverlayColor?: string;
    investmentSectionAvailableTabText?: string;
    investmentSectionMyInvestmentsTabText?: string;
}

interface DailyData {
    name: string;
    Investment: number;
    Staking: number;
    Pool: number;
    Deposit: number;
    Referral: number;
}

interface Transaction {
    id: string;
    amount: number;
    title: string;
    type: 'deposit' | 'withdraw' | 'bonus' | 'investment';
    status: 'pending' | 'completed' | 'rejected' | 'other';
    date: any;
}

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

export default function DashboardPage() {
  const { user } = useAuth();
  const [userData, setUserData] = useState<UserData | null>(null);
  const [settings, setSettings] = useState<DashboardSettings | null>(null);
  const [loading, setLoading] = useState(true);
  const [dailyData, setDailyData] = useState<DailyData[]>([]);
  const [currency, setCurrency] = useState<CurrencySettings>({ symbol: '$', position: 'left' });
  const [userStats, setUserStats] = useState<any>({});
  const [recentTransactions, setRecentTransactions] = useState<Transaction[]>([]);
  const [stakingTemplate, setStakingTemplate] = useState<StakingTemplate | null>(null);
  
  const [availableStakes, setAvailableStakes] = useState<StakingPlan[]>([]);
  const [myStakes, setMyStakes] = useState<UserStake[]>([]);
  
  const [availableInvestments, setAvailableInvestments] = useState<InvestmentPlan[]>([]);
  const [myInvestments, setMyInvestments] = useState<UserInvestment[]>([]);
  const [investmentTemplate, setInvestmentTemplate] = useState<InvestmentTemplate | null>(null);


  useEffect(() => {
    if (!db || !user) {
        setLoading(false);
        return;
    }

    const fetchDashboardData = async () => {
        try {
            // Fetch settings
            const settingsDocRef = doc(db, 'settings', 'dashboard');
            const settingsDoc = await getDoc(settingsDocRef);
            if (settingsDoc.exists()) {
                const data = settingsDoc.data();
                const sections = data.sections || [
                    { key: 'announcement', visible: true },
                    { key: 'welcome', visible: true },
                    { key: 'investment', visible: true },
                    { key: 'staking', visible: true },
                    { key: 'chart', visible: true },
                    { key: 'recentTransactions', visible: true },
                    ...(data.statCardSections || []).map((s: StatCardSection) => ({ key: s.id, visible: true })),
                    ...(data.iconBoxSections || []).map((s: IconBoxSection) => ({ key: s.id, visible: true })),
                ];
                setSettings({ ...data, sections } as DashboardSettings);
            }

            const stakingTemplateDoc = await getDoc(doc(db, "settings", "stakingTemplate"));
            if (stakingTemplateDoc.exists()) {
                setStakingTemplate(stakingTemplateDoc.data() as StakingTemplate);
            }

            const investmentTemplateDoc = await getDoc(doc(db, "settings", "investmentTemplates"));
            if (investmentTemplateDoc.exists()) {
                const templates = investmentTemplateDoc.data().templates as InvestmentTemplate[];
                setInvestmentTemplate(templates.find(t => t.active) || templates[0] || null);
            }
            
            const currencyDoc = await getDoc(doc(db, "settings", "currency"));
            if (currencyDoc.exists()) {
              setCurrency(currencyDoc.data() as CurrencySettings);
            }

            // Fetch user data
            const userDocRef = doc(db, "users", user.uid);
            const unsubscribeUser = onSnapshot(userDocRef, (doc) => {
                if (doc.exists()) {
                    const data = doc.data() as UserData | undefined;
                    setUserData({
                        username: data?.username || user.uid.slice(0, 8).toUpperCase(),
                        firstName: data?.firstName || '',
                        lastName: data?.lastName || '',
                        balance: data?.balance || 0
                    });
                }
            });
            
            // Staking Data
            const availableStakesQuery = query(collection(db, "stakingPlans"), where("status", "==", "active"), orderBy("createdAt", "desc"), limit(3));
            const myStakesQuery = query(collection(db, "userStakes"), where("userId", "==", user.uid), where("status", "==", "active"), orderBy("startDate", "desc"), limit(3));
            const [availableStakesSnap, myStakesSnap] = await Promise.all([getDocs(availableStakesQuery), getDocs(myStakesQuery)]);
            setAvailableStakes(availableStakesSnap.docs.map(d => ({id: d.id, ...d.data()} as StakingPlan)));
            setMyStakes(myStakesSnap.docs.map(d => ({id: d.id, ...d.data()} as UserStake)));
            
            // Investment Data
            const availableInvestmentsQuery = query(collection(db, "investmentPlans"), where("status", "==", "active"), orderBy("createdAt", "desc"));
            const myInvestmentsQuery = query(collection(db, "userInvestments"), where("userId", "==", user.uid), where("status", "==", "active"), orderBy("startDate", "desc"), limit(3));
            const [availableInvestmentsSnap, myInvestmentsSnap] = await Promise.all([getDocs(availableInvestmentsQuery), getDocs(myInvestmentsQuery)]);
            setAvailableInvestments(availableInvestmentsSnap.docs.map(d => ({id: d.id, ...d.data()} as InvestmentPlan)));
            setMyInvestments(myInvestmentsSnap.docs.map(d => ({id: d.id, ...d.data()} as UserInvestment)));


            // Fetch transactional data for stats
            const depositsQuery = query(collection(db, "deposits"), where("userId", "==", user.uid));
            const withdrawalsQuery = query(collection(db, "withdrawals"), where("userId", "==", user.uid));
            const investmentsQuery = query(collection(db, "userInvestments"), where("userId", "==", user.uid));
            const stakesQuery = query(collection(db, "userStakes"), where("userId", "==", user.uid));
            const poolsQuery = query(collection(db, "userPoolInvestments"), where("userId", "==", user.uid));
            const investmentTxQuery = query(collection(db, "investmentTransactions"), where("userId", "==", user.uid), where("type", "in", ["Profit Return (Auto)", "Profit Return (Manual)"]));
            const refQuery = query(collection(db, "users"), where("referredBy", "==", user.uid));
            const refCommissionsQuery = query(collection(db, "referralCommissions"), where("referrerId", "==", user.uid));
            
            const [
              depositsSnap, withdrawalsSnap, investmentsSnap, stakesSnap, poolsSnap,
              investmentTxSnap, refSnap, refCommissionsSnap
            ] = await Promise.all([
                getDocs(depositsQuery), getDocs(withdrawalsQuery), getDocs(investmentsQuery),
                getDocs(stakesQuery), getDocs(poolsQuery), getDocs(investmentTxQuery),
                getDocs(refQuery), getDocs(refCommissionsQuery)
            ]);

            const allUserInvestments = investmentsSnap.docs.map(d => d.data());
            const allUserStakes = stakesSnap.docs.map(d => d.data());
            const allUserPools = poolsSnap.docs.map(d => d.data());

            const statsData = {
                totalDeposits: depositsSnap.docs.filter(d => d.data().status === 'completed').reduce((sum, doc) => sum + doc.data().amount, 0),
                totalWithdrawals: withdrawalsSnap.docs.filter(d => d.data().status === 'completed').reduce((sum, doc) => sum + doc.data().amount, 0),
                pendingDeposits: depositsSnap.docs.filter(d => d.data().status === 'pending').reduce((sum, doc) => sum + doc.data().amount, 0),
                pendingWithdrawals: withdrawalsSnap.docs.filter(d => d.data().status === 'pending').reduce((sum, doc) => sum + doc.data().amount, 0),
                totalInvestments: allUserInvestments.reduce((sum, doc) => sum + doc.amount, 0) + allUserStakes.reduce((sum, doc) => sum + doc.amount, 0) + allUserPools.reduce((sum, doc) => sum + doc.amount, 0),
                activeInvestments: allUserInvestments.filter(d => d.status === 'active').reduce((sum, doc) => sum + doc.amount, 0),
                totalReturnsFromInvests: investmentTxSnap.docs.reduce((sum, doc) => sum + doc.data().amount, 0),
                totalStakes: allUserStakes.reduce((sum, doc) => sum + doc.amount, 0),
                totalActiveStakes: allUserStakes.filter(d => d.status === 'active').reduce((sum, doc) => sum + doc.amount, 0),
                totalReturnFromStakes: allUserStakes.filter(d => d.status === 'completed').reduce((sum, doc) => sum + (doc.amount * doc.returnPercentage / 100), 0),
                totalPoolInvestments: allUserPools.reduce((sum, doc) => sum + doc.amount, 0),
                totalActivePool: allUserPools.filter(d => d.status === 'active').reduce((sum, doc) => sum + doc.amount, 0),
                totalReturnFromPool: allUserPools.filter(d => d.status === 'completed').reduce((sum, doc) => sum + (doc.returnAmount || 0), 0),
                totalReferrals: refSnap.size,
                totalRefCommissions: refCommissionsSnap.docs.reduce((sum, doc) => sum + doc.data().amount, 0),
            };
            setUserStats(statsData);

            // Fetch Recent Transactions for the new section
            const allTransactions: Transaction[] = [];
            depositsSnap.docs.forEach(d => allTransactions.push({ id: d.id, ...d.data(), title: `Deposit via ${d.data().method}`, type: 'deposit', date: d.data().createdAt } as Transaction));
            withdrawalsSnap.docs.forEach(d => allTransactions.push({ id: d.id, ...d.data(), title: `Withdrawal via ${d.data().method}`, type: 'withdraw', date: d.data().createdAt } as Transaction));
            investmentTxSnap.docs.forEach(d => allTransactions.push({ id: d.id, ...d.data(), title: `${d.data().type} from ${d.data().planName}`, type: 'investment', status: 'completed', date: d.data().date } as Transaction));
            setRecentTransactions(allTransactions.sort((a,b) => b.date.seconds - a.date.seconds).slice(0, 5));


            // Fetch chart data
            const fifteenDaysAgo = startOfDay(addDays(new Date(), -14));
            const dataMap = new Map<string, DailyData>();
            for (let i = 0; i < 15; i++) {
                const date = format(addDays(fifteenDaysAgo, i), 'MMM d');
                dataMap.set(date, { name: date, Investment: 0, Staking: 0, Pool: 0, Deposit: 0, Referral: 0 });
            }

             const chartQueries = {
                Investment: query(collection(db, "investmentTransactions"), where("userId", "==", user.uid), where("date", ">=", fifteenDaysAgo), where("type", "in", ["Profit Return (Auto)", "Profit Return (Manual)"])),
                Staking: query(collection(db, "investmentTransactions"), where("userId", "==", user.uid), where("date", ">=", fifteenDaysAgo), where("type", "==", "Staking Return")),
                Pool: query(collection(db, "investmentTransactions"), where("userId", "==", user.uid), where("date", ">=", fifteenDaysAgo), where("type", "==", "Pool Return")),
                Deposit: query(collection(db, "deposits"), where("userId", "==", user.uid), where("createdAt", ">=", fifteenDaysAgo), where("status", "==", "completed")),
                Referral: query(collection(db, "referralCommissions"), where("referrerId", "==", user.uid), where("date", ">=", fifteenDaysAgo)),
            };

            const results = await Promise.all(Object.entries(chartQueries).map(([key, q]) => getDocs(q)));
            
            results.forEach((snapshot, index) => {
                const key = Object.keys(chartQueries)[index] as keyof DailyData;
                snapshot.forEach(doc => {
                    const data = doc.data();
                    const dateField = data.createdAt || data.date;
                    if(dateField) {
                        const day = format(dateField.toDate(), 'MMM d');
                        if (dataMap.has(day)) {
                            dataMap.get(day)![key] = (dataMap.get(day)![key] || 0) + data.amount;
                        }
                    }
                });
            });

            setDailyData(Array.from(dataMap.values()));

            return () => unsubscribeUser();

        } catch (error) {
            console.error("Error fetching dashboard data:", error);
        } finally {
            setLoading(false);
        }
    };

    fetchDashboardData();

  }, [user]);

  const chartConfig: ChartConfig = useMemo(() => {
    if (!settings) return {};
    return {
        Investment: { label: 'Investment', color: settings.lineChartColors.investment },
        Staking: { label: 'Staking', color: settings.lineChartColors.staking },
        Pool: { label: 'Pool', color: settings.lineChartColors.pool },
        Deposit: { label: 'Deposit', color: settings.lineChartColors.deposit },
        Referral: { label: 'Referral', color: settings.lineChartColors.referral },
    }
  }, [settings]);

   const formatCurrency = (amount: number) => {
        const value = (amount || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        return currency.position === 'left' ? `${currency.symbol}${value}` : `${value}${currency.symbol}`;
    };

    const welcomeMessage = useMemo(() => {
        if (!settings?.welcomeMessage || !userData) return `Welcome back!`;
        return settings.welcomeMessage
            .replace('{firstName}', userData.firstName || '')
            .replace('{lastName}', userData.lastName || '');
    }, [settings, userData]);
    
    const welcomeStyle: React.CSSProperties = {
        backgroundImage: settings?.welcomeBgUrl ? `url(${settings.welcomeBgUrl})` : 'none',
        backgroundColor: settings?.welcomeBgUrl ? 'transparent' : 'hsl(var(--card))',
        position: 'relative',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
    };
    
    const welcomeOverlayStyle: React.CSSProperties = {
        position: 'absolute',
        inset: 0,
        backgroundColor: settings?.welcomeOverlayColor || 'transparent',
        zIndex: 0,
        borderRadius: 'inherit'
    };

    const balanceBarStyle: React.CSSProperties = {
        backgroundImage: settings?.balanceBarBackgroundUrl ? `url(${settings.balanceBarBackgroundUrl})` : 'none',
        backgroundColor: settings?.balanceBarBackgroundUrl ? 'transparent' : 'hsl(var(--card))',
        position: 'relative',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
    };
    
    const balanceBarOverlayStyle: React.CSSProperties = {
        position: 'absolute',
        inset: 0,
        backgroundColor: settings?.balanceBarOverlayColor || 'transparent',
        zIndex: 0,
        borderRadius: 'inherit',
    };

    const chartCardStyle: React.CSSProperties = {
        backgroundImage: settings?.chartBackgroundUrl ? `url(${settings.chartBackgroundUrl})` : 'none',
        backgroundColor: settings?.chartBackgroundUrl ? 'transparent' : 'hsl(var(--card))',
        position: 'relative',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
    };
    
     const chartOverlayStyle: React.CSSProperties = {
        position: 'absolute',
        inset: 0,
        backgroundColor: settings?.chartOverlayColor || 'transparent',
        zIndex: 0,
        borderRadius: 'inherit',
    };
    
    const transactionsCardStyle: React.CSSProperties = {
        backgroundImage: settings?.recentTransactionsBgUrl ? `url(${settings.recentTransactionsBgUrl})` : 'none',
        backgroundColor: settings?.recentTransactionsBgUrl ? 'transparent' : 'hsl(var(--card))',
        position: 'relative',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
    };
    
     const transactionsOverlayStyle: React.CSSProperties = {
        position: 'absolute',
        inset: 0,
        backgroundColor: settings?.recentTransactionsOverlayColor || 'transparent',
        zIndex: 0,
        borderRadius: 'inherit',
    };
    
    const announcementStyle: React.CSSProperties = {
        backgroundImage: settings?.announcementBgUrl ? `url(${settings.announcementBgUrl})` : 'none',
        backgroundColor: settings?.announcementBgUrl ? 'transparent' : 'hsl(var(--card)/0.5)',
        position: 'relative',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
    };
    
    const announcementOverlayStyle: React.CSSProperties = {
        position: 'absolute',
        inset: 0,
        backgroundColor: settings?.announcementOverlayColor || 'transparent',
        zIndex: 0,
        borderRadius: 'inherit',
    };
    
    const stakingSectionStyle: React.CSSProperties = {
        backgroundImage: settings?.stakingSectionBgUrl ? `url(${settings.stakingSectionBgUrl})` : 'none',
        backgroundColor: settings?.stakingSectionBgUrl ? 'transparent' : 'hsl(var(--card))',
        position: 'relative',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
    };
    const stakingSectionOverlayStyle: React.CSSProperties = {
        position: 'absolute', inset: 0, zIndex: 0, borderRadius: 'inherit',
        backgroundColor: settings?.stakingSectionOverlayColor || 'transparent',
    };
    
    const investmentSectionStyle: React.CSSProperties = {
        backgroundImage: settings?.investmentSectionBgUrl ? `url(${settings.investmentSectionBgUrl})` : 'none',
        backgroundColor: settings?.investmentSectionBgUrl ? 'transparent' : 'hsl(var(--card))',
        position: 'relative',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
    };
    const investmentSectionOverlayStyle: React.CSSProperties = {
        position: 'absolute', inset: 0, zIndex: 0, borderRadius: 'inherit',
        backgroundColor: settings?.investmentSectionOverlayColor || 'transparent',
    };

    const StatCard = ({ card }: { card: StatCardSetting }) => {
        const Icon = (LucideIcons as any)[card.icon || 'Wallet'];
        const cardStyle: React.CSSProperties = {
            backgroundImage: card.bgUrl ? `url(${card.bgUrl})` : 'none',
            backgroundColor: card.bgUrl ? 'transparent' : 'hsl(var(--card))',
            position: 'relative',
            backgroundSize: 'cover',
            backgroundPosition: 'center',
        };
        const overlayStyle: React.CSSProperties = {
            position: 'absolute',
            inset: 0,
            backgroundColor: card.bgColor || 'rgba(0,0,0,0.3)',
            zIndex: 0,
            borderRadius: 'inherit',
        };
        const statValue = userStats[card.key] || 0;

        return (
            <Card style={cardStyle} className="text-white overflow-hidden">
                <div style={overlayStyle}></div>
                <div className="relative z-10">
                    <CardHeader className="flex flex-row items-center justify-between pb-2">
                        <CardTitle className="text-sm font-medium">{card.title}</CardTitle>
                        {card.imageUrl ? <Image src={card.imageUrl} alt={card.title} width={20} height={20} /> : Icon && <Icon className="h-5 w-5 text-white/80" />}
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{formatCurrency(statValue)}</div>
                        {card.subtitle && <p className="text-xs text-white/80">{card.subtitle}</p>}
                    </CardContent>
                </div>
            </Card>
        )
    };

    const IconBox = ({ box }: { box: IconBoxSetting }) => {
        return (
            <Link href={box.link || '#'} className="block rounded-lg shadow-sm hover:shadow-primary/20 transition-shadow" style={{ minWidth: box.boxMinWidth || 180, backgroundColor: box.boxBackgroundColor || 'hsl(var(--card))' }}>
                <div className="flex flex-col items-center justify-center p-6 text-center aspect-square">
                    <div className="flex items-center justify-center rounded-full mb-4" style={{ 
                        width: (box.iconWidth || 40) + 20, 
                        height: (box.iconHeight || 40) + 20, 
                        backgroundColor: box.iconBackgroundColor || 'hsla(var(--primary), 0.1)',
                    }}>
                        <Image src={box.iconUrl} alt={box.title} width={box.iconWidth || 40} height={box.iconHeight || 40} />
                    </div>
                    <h4 className="font-semibold text-sm">{box.title}</h4>
                    {box.subtitle && <p className="text-xs text-muted-foreground">{box.subtitle}</p>}
                </div>
            </Link>
        )
    }

    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, position: 'relative' }}
        className={`p-6 rounded-2xl border ${plan.featured ? 'border-primary shadow-lg shadow-primary/20' : 'border-border/50'} flex flex-col`}
    >
        <div style={{ position: 'absolute', inset: 0, backgroundColor: tpl.cardBackgroundOverlayColor || 'transparent', borderRadius: 'inherit' }}></div>
        <div className="relative z-10 flex flex-col h-full">
            {plan.imageUrl && (
                <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={`/dashboard/investment/invest/${plan.id}`}>{tpl.buttonText}</Link>
            </Button>
        </div>
    </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 && (
                    <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={`/dashboard/investment/invest/${plan.id}`}>{tpl.buttonText}</Link>
                </Button>
            </div>
        </div>
    );
  }
    
  const dashboardSections: { [key: string]: React.ReactNode } = {
      announcement: (
        <div style={announcementStyle} className="rounded-lg py-2 flex items-center gap-4 overflow-hidden text-white relative">
            <div style={announcementOverlayStyle}></div>
            <div className="relative z-10 flex items-center flex-nowrap w-full">
                {settings?.announcementIconUrl && (
                    <Image src={settings.announcementIconUrl} alt="Announcement" width={32} height={32} className="rounded-full flex-shrink-0 ml-4" />
                )}
                <div className="animate-marquee-wrapper flex-shrink-0">
                    <div className={settings?.announcementAnimationEnabled ? 'animate-marquee' : ''}>
                        <span className="text-md font-semibold mx-8">{settings?.announcementText}</span>
                        {settings?.announcementAnimationEnabled && <span className="text-md font-semibold mx-8" aria-hidden="true">{settings?.announcementText}</span>}
                    </div>
                </div>
            </div>
        </div>
      ),
      welcome: (
        <div style={welcomeStyle} className="p-8 rounded-lg text-white relative overflow-hidden text-center">
            <div style={welcomeOverlayStyle}></div>
            <div className="relative z-10">
                <h1 className="text-3xl font-bold font-headline">{welcomeMessage}</h1>
            </div>
        </div>
      ),
      investment: (
        <Card style={investmentSectionStyle}>
            <div style={investmentSectionOverlayStyle}></div>
            <div className="relative z-10">
                <CardHeader>
                    <CardTitle>{settings?.investmentSectionTitle}</CardTitle>
                    <CardDescription>{settings?.investmentSectionSubtitle}</CardDescription>
                </CardHeader>
                <CardContent>
                    <Tabs defaultValue="available">
                        <TabsList className="grid w-full grid-cols-2">
                            <TabsTrigger value="available">{settings?.investmentSectionAvailableTabText}</TabsTrigger>
                            <TabsTrigger value="my-investments">{settings?.investmentSectionMyInvestmentsTabText}</TabsTrigger>
                        </TabsList>
                        <TabsContent value="available" className="pt-4">
                           {availableInvestments.length > 0 ? (
                                <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
                                {availableInvestments.map(plan => {
                                    if (investmentTemplate) {
                                         if (investmentTemplate.id === 'green_pluss') {
                                            return renderGreenPlussTemplate(plan, investmentTemplate);
                                        }
                                        return renderDefaultTemplate(plan, investmentTemplate);
                                    }
                                    return (
                                        <Link key={plan.id} href={`/dashboard/investment/invest/${plan.id}`} className="block p-3 rounded-md hover:bg-muted/50 transition-colors">
                                            <div className="flex justify-between items-center">
                                                <div className='flex items-center gap-2'>
                                                    <InvestmentIcon className="h-5 w-5 text-primary" />
                                                    <p className="font-semibold">{plan.planName}</p>
                                                </div>
                                                <Badge>{plan.interestRate}% / {plan.returnPeriod}</Badge>
                                            </div>
                                        </Link>
                                    )
                                })}
                                </div>
                            ) : <p className="text-center text-muted-foreground py-4">No new investment plans available.</p>}
                        </TabsContent>
                        <TabsContent value="my-investments" className="pt-4">
                              {myInvestments.length > 0 ? (
                                <div className="space-y-2">
                                {myInvestments.map(investment => (
                                    <Link key={investment.id} href="/dashboard/investment/my-investment" className="block p-3 rounded-md hover:bg-muted/50 transition-colors">
                                        <div className="flex justify-between items-center">
                                            <p className="font-semibold">{investment.planName}</p>
                                            <p className="text-sm text-muted-foreground">{formatCurrency(investment.amount)}</p>
                                        </div>
                                        <Progress value={(investment.returnsCalculated/investment.termDuration)*100} className="h-2 mt-1" />
                                    </Link>
                                ))}
                                </div>
                            ) : <p className="text-center text-muted-foreground py-4">You have no active investments.</p>}
                        </TabsContent>
                    </Tabs>
                </CardContent>
            </div>
        </Card>
      ),
      staking: (
        <Card style={stakingSectionStyle}>
            <div style={stakingSectionOverlayStyle}></div>
            <div className="relative z-10">
                <CardHeader>
                    <CardTitle>{settings?.stakingSectionTitle}</CardTitle>
                    <CardDescription>{settings?.stakingSectionSubtitle}</CardDescription>
                </CardHeader>
                <CardContent>
                    <Tabs defaultValue="available">
                        <TabsList className="grid w-full grid-cols-2">
                            <TabsTrigger value="available">{settings?.stakingSectionAvailableTabText}</TabsTrigger>
                            <TabsTrigger value="my-stakes">{settings?.stakingSectionMyStakesTabText}</TabsTrigger>
                        </TabsList>
                        <TabsContent value="available" className="pt-4">
                            {availableStakes.length > 0 ? (
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                {availableStakes.map(plan => {
                                    if (!stakingTemplate) return null;
                                    const backgroundStyle = stakingTemplate.cardBackgroundColor2 
                                        ? { background: `linear-gradient(to bottom right, ${stakingTemplate.cardBackgroundColor}, ${stakingTemplate.cardBackgroundColor2})` }
                                        : { backgroundColor: stakingTemplate.cardBackgroundColor };
                                    
                                    return (
                                        <Link href={`/dashboard/staking/invest/${plan.id}`} key={plan.id} style={{maxWidth: settings?.stakingSectionCardWidth ? `${settings.stakingSectionCardWidth}px` : 'none'}} className="mx-auto w-full">
                                            <div style={backgroundStyle} className="rounded-lg flex flex-col overflow-hidden border border-border/50 h-full hover:border-primary transition-all">
                                                <div className="relative h-24 w-full">
                                                    {plan.imageUrl && (
                                                        <Image src={plan.imageUrl} alt={plan.planName} layout="fill" objectFit="cover" />
                                                    )}
                                                     <div className="absolute top-2 right-2 px-2 py-0.5 rounded-md text-xs" style={{backgroundColor: stakingTemplate.durationBackgroundColor || 'rgba(0,0,0,0.5)', color: stakingTemplate.durationColor}}>
                                                        {plan.durationDays} Days
                                                    </div>
                                                </div>
                                                 <div className="relative h-12">
                                                    <div 
                                                        className="absolute left-1/2 -translate-x-1/2 -top-12 h-24 w-24 rounded-full flex items-center justify-center border-4"
                                                        style={{
                                                            backgroundColor: stakingTemplate.returnPercentageBackgroundColor || 'rgba(0,0,0,0.3)',
                                                            borderColor: stakingTemplate.cardBackgroundColor
                                                        }}
                                                    >
                                                        <p className="text-4xl font-bold" style={{color: stakingTemplate.returnPercentageColor}}>
                                                            {plan.returnPercentage}<span className="text-2xl">%</span>
                                                        </p>
                                                    </div>
                                                </div>
                                                <div className="p-4 pt-0 flex-grow flex flex-col" style={{color: stakingTemplate.cardTextColor}}>
                                                    <div className="text-center mb-4">
                                                        <h3 className="text-lg font-bold font-headline" style={{color: stakingTemplate.planNameColor}}>{plan.planName}</h3>
                                                        <p style={{color: stakingTemplate.durationColor}} className="text-xs mt-1">Total Return in {plan.durationDays} Days</p>
                                                    </div>
                                                    <div className="space-y-2 text-xs mt-auto">
                                                        <div className="flex justify-between items-center py-2 border-t" style={{borderColor: 'rgba(255,255,255,0.1)'}}>
                                                            <span style={{color: stakingTemplate.detailsLabelColor}}>Min Stake:</span> 
                                                            <span className="font-semibold" style={{color: stakingTemplate.detailsValueColor}}>{formatCurrency(plan.minAmount)}</span>
                                                        </div>
                                                         <div className="flex justify-between items-center pb-2 border-b" style={{borderColor: 'rgba(255,255,255,0.1)'}}>
                                                            <span style={{color: stakingTemplate.detailsLabelColor}}>Max Stake:</span> 
                                                            <span className="font-semibold" style={{color: stakingTemplate.detailsValueColor}}>{formatCurrency(plan.maxAmount)}</span>
                                                        </div>
                                                         <div className="flex justify-between items-center pb-2 border-b" style={{borderColor: 'rgba(255,255,255,0.1)'}}>
                                                            <span style={{color: stakingTemplate.detailsLabelColor}}>Capital Back:</span> 
                                                            <Badge style={{backgroundColor: stakingTemplate.badgeBackgroundColor, color: stakingTemplate.badgeTextColor}}>{plan.capitalBack ? "Yes" : "No"}</Badge>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </Link>
                                    )
                                })}
                                </div>
                            ) : <p className="text-center text-muted-foreground py-4">No new staking plans available.</p>}
                        </TabsContent>
                        <TabsContent value="my-stakes" className="pt-4">
                              {myStakes.length > 0 ? (
                                <div className="space-y-2">
                                {myStakes.map(stake => (
                                    <Link key={stake.id} href="/dashboard/staking/my-staking" className="block p-3 rounded-md hover:bg-muted/50 transition-colors">
                                        <div className="flex justify-between items-center">
                                            <p className="font-semibold">{stake.planName}</p>
                                            <p className="text-sm text-muted-foreground">{formatCurrency(stake.amount)}</p>
                                        </div>
                                    </Link>
                                ))}
                                </div>
                            ) : <p className="text-center text-muted-foreground py-4">You have no active stakes.</p>}
                        </TabsContent>
                    </Tabs>
                </CardContent>
            </div>
        </Card>
      ),
      chart: (
          <div className="rounded-lg overflow-hidden">
              <div style={balanceBarStyle} className="p-6 text-center relative rounded-t-lg">
                <div style={balanceBarOverlayStyle} className="rounded-t-lg"></div>
                <div className="relative z-10">
                    <p className="text-sm text-white/80">{currency.mainWalletName || 'Main Wallet Balance'}</p>
                    <h3 className="text-3xl font-bold text-white">{formatCurrency(userData?.balance || 0)}</h3>
                </div>
              </div>
              <Card style={chartCardStyle} className="rounded-t-none">
                  <div style={chartOverlayStyle}></div>
                  <div className="relative z-10">
                      <CardHeader>
                          <CardTitle>Last 15 Days Activity</CardTitle>
                      </CardHeader>
                      <CardContent className="h-[300px]">
                            {settings?.chartType === 'bar' ? (
                              <ResponsiveContainer width="100%" height="100%">
                                  <BarChart data={dailyData}>
                                      <CartesianGrid strokeDasharray="3 3" vertical={true} />
                                      <XAxis dataKey="name" stroke="#888888" fontSize={12} tickLine={false} axisLine={false}/>
                                      <YAxis stroke="#888888" fontSize={12} tickLine={false} axisLine={false} tickFormatter={(value) => `${currency.symbol}${value}`}/>
                                      <Tooltip cursor={{fill: 'hsla(var(--muted))'}} contentStyle={{backgroundColor: 'hsl(var(--background))'}} formatter={(value: number) => formatCurrency(value)} />
                                      <Legend/>
                                      {settings.chartSeriesVisibility?.investment && <Bar dataKey="Investment" fill={settings.barChartColors.investment} radius={[4, 4, 0, 0]} />}
                                      {settings.chartSeriesVisibility?.staking && <Bar dataKey="Staking" fill={settings.barChartColors.staking} radius={[4, 4, 0, 0]} />}
                                      {settings.chartSeriesVisibility?.pool && <Bar dataKey="Pool" fill={settings.barChartColors.pool} radius={[4, 4, 0, 0]} />}
                                      {settings.chartSeriesVisibility?.deposit && <Bar dataKey="Deposit" fill={settings.barChartColors.deposit} radius={[4, 4, 0, 0]} />}
                                      {settings.chartSeriesVisibility?.referral && <Bar dataKey="Referral" fill={settings.barChartColors.referral} radius={[4, 4, 0, 0]} />}
                                  </BarChart>
                              </ResponsiveContainer>
                          ) : (
                              <ChartContainer config={chartConfig} className="h-full w-full">
                                      <LineChart data={dailyData}>
                                      <CartesianGrid strokeDasharray="3 3" vertical={true} />
                                      <XAxis dataKey="name" tickLine={false} axisLine={false} tickMargin={8} stroke="#888888" fontSize={12} />
                                      <YAxis tickLine={false} axisLine={false} stroke="#888888" fontSize={12} tickFormatter={(value) => `${currency.symbol}${value}`} />
                                      {settings && <ChartTooltip content={<ChartTooltipContent formatter={(value) => formatCurrency(Number(value))}/>} />}
                                      <Legend />
                                      {settings && settings.chartSeriesVisibility && Object.entries(settings.chartSeriesVisibility).map(([key, visible]) => {
                                        if (!visible) return null;
                                        const capKey = key.charAt(0).toUpperCase() + key.slice(1);
                                        return <Line key={key} dataKey={capKey} type="monotone" stroke={(settings.lineChartColors as any)[key]} strokeWidth={2} dot={false} />
                                      })}
                                      </LineChart>
                              </ChartContainer>
                          )}
                      </CardContent>
                  </div>
              </Card>
          </div>
      ),
      recentTransactions: (
        <Card style={transactionsCardStyle} className="text-white overflow-hidden">
            <div style={transactionsOverlayStyle}></div>
            <div className="relative z-10">
                <CardHeader>
                    <CardTitle>Recent Transactions</CardTitle>
                </CardHeader>
                <CardContent>
                    {recentTransactions.length > 0 ? (
                    <ul className="space-y-4">
                        {recentTransactions.map(tx => (
                            <li key={tx.id} className="flex items-center justify-between">
                                <div>
                                    <p className="font-semibold">{tx.title}</p>
                                    <p className="text-sm text-white/80">{format(tx.date.toDate(), 'MMM d, yyyy')}</p>
                                </div>
                                <div className="text-right">
                                    <p className={`font-bold ${tx.type === 'deposit' || tx.type === 'investment' ? 'text-green-400' : 'text-red-400'}`}>
                                        {tx.type === 'deposit' || tx.type === 'investment' ? '+' : '-'} {formatCurrency(tx.amount)}
                                    </p>
                                    <Badge variant={tx.status === 'completed' ? 'default' : (tx.status === 'pending' ? 'secondary' : 'destructive')} className="capitalize mt-1">{tx.status}</Badge>
                                </div>
                            </li>
                        ))}
                    </ul>
                    ) : (
                        <p className="text-center text-white/80">No recent transactions.</p>
                    )}
                </CardContent>
            </div>
        </Card>
    ),
  };


  return (
    <DashboardLayout>
        <div className="space-y-8">
            {loading ? (
                 <div className="flex items-center justify-center p-16">
                    <Loader2 className="h-10 w-10 animate-spin"/>
                </div>
            ) : settings ? (
                (settings.sections || []).map(section => {
                    if (!section.visible) return null;

                    if (section.key.startsWith('stats_')) {
                        const statSectionData = settings.statCardSections.find(s => s.id === section.key);
                        if (!statSectionData) return null;
                        
                        return (
                            <div key={section.key}>
                                {statSectionData.title && (
                                    <div className="mb-4">
                                    <h2 className="text-2xl font-bold font-headline">{statSectionData.title}</h2>
                                    {statSectionData.subtitle && <p className="text-muted-foreground">{statSectionData.subtitle}</p>}
                                    </div>
                                )}
                                <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                                    {(statSectionData.cards || []).map(card => <StatCard key={card.id} card={card} />)}
                                </div>
                            </div>
                        )
                    }

                    if (section.key.startsWith('icon_boxes_')) {
                        const iconBoxSectionData = settings.iconBoxSections.find(s => s.id === section.key);
                        if (!iconBoxSectionData) return null;

                        return (
                            <div key={section.key}>
                                {iconBoxSectionData.title && (
                                    <div className="mb-4">
                                        <h2 className="text-2xl font-bold font-headline">{iconBoxSectionData.title}</h2>
                                        {iconBoxSectionData.subtitle && <p className="text-muted-foreground">{iconBoxSectionData.subtitle}</p>}
                                    </div>
                                )}
                                <div className="grid gap-4" style={{ gridTemplateColumns: `repeat(auto-fill, minmax(${(iconBoxSectionData.boxes[0]?.boxMinWidth || 180)}px, 1fr))` }}>
                                    {(iconBoxSectionData.boxes || []).map(box => <IconBox key={box.id} box={box} />)}
                                </div>
                            </div>
                        )
                    }

                    return (
                        <div key={section.key}>
                            {dashboardSections[section.key as keyof typeof dashboardSections]}
                        </div>
                    )
                })
            ) : (
                <div className="text-center text-muted-foreground p-8">
                     <h1 className="text-3xl font-bold font-headline tracking-tight">Welcome, {userData?.firstName || userData?.username}</h1>
                    <p>Your dashboard is being set up.</p>
                </div>
            )}
            <style jsx>{`
                .animate-marquee-wrapper {
                    overflow: hidden;
                    white-space: nowrap;
                    width: 100%;
                }

                @keyframes marquee {
                    from { transform: translateX(50%); }
                    to { transform: translateX(-50%); }
                }
                
                .animate-marquee {
                    display: inline-block;
                    animation: marquee ${settings?.announcementSpeed || 25}s linear infinite;
                    will-change: transform;
                }
            `}</style>
        </div>
    </DashboardLayout>
  );
}
