import React, { useState, useEffect } from 'react';
import { AlertDialog, AlertDialogAction, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Slider } from '@/components/ui/slider';
import { Progress } from '@/components/ui/progress';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Toast } from '@/components/ui/toast';
import { Leaf, Heart, ShoppingCart, User, Home, Star, Clock } from 'lucide-react';

// Mock data for fashion items (unchanged)
const fashionItems = [
  { id: 1, name: "Eco-Chic Blouse", material: "organic cotton", style: "casual", sustainabilityScore: 8, image: "/api/placeholder/280/200", price: 89.99 },
  { id: 2, name: "Sustainable Suit", material: "recycled polyester", style: "professional", sustainabilityScore: 9, image: "/api/placeholder/280/200", price: 299.99 },
  { id: 3, name: "Upcycled Denim Jacket", material: "upcycled denim", style: "casual", sustainabilityScore: 10, image: "/api/placeholder/280/200", price: 129.99 },
  { id: 4, name: "Bamboo Lounge Set", material: "bamboo fiber", style: "casual", sustainabilityScore: 7, image: "/api/placeholder/280/200", price: 79.99 },
  { id: 5, name: "Hemp Office Dress", material: "hemp", style: "professional", sustainabilityScore: 8, image: "/api/placeholder/280/200", price: 159.99 },
  { id: 6, name: "Tencel Boho Skirt", material: "tencel", style: "eclectic", sustainabilityScore: 9, image: "/api/placeholder/280/200", price: 69.99 },
];

// Mock data for challenges and quests
const challenges = [
  { id: 1, name: "Eco Warrior", description: "Purchase 5 items with sustainability score 8+", reward: 100, status: "incomplete" },
  { id: 2, name: "Material Master", description: "Buy items made from 3 different sustainable materials", reward: 150, status: "incomplete" },
  { id: 3, name: "Stylish Saver", description: "Invest in a bond for 30 days", reward: 200, status: "incomplete" },
];

// Token assignment and calculation functions (unchanged)
const getOnboardingTokens = (style, sustainabilityFocus) => {
  let tokens = 0;
  if (style === 'eclectic') tokens += 50;
  if (sustainabilityFocus === 'materials') tokens += 30;
  return tokens;
};

const getPurchaseTokens = (price) => Math.floor(price / 10);

const App = () => {
  // Existing state variables
  const [step, setStep] = useState(0);
  const [username, setUsername] = useState('');
  const [style, setStyle] = useState('');
  const [sustainabilityFocus, setSustainabilityFocus] = useState('');
  const [priceRange, setPriceRange] = useState([200]);
  const [showRecommendation, setShowRecommendation] = useState(false);
  const [recommendations, setRecommendations] = useState([]);
  const [userTokens, setUserTokens] = useState(0);
  const [favorites, setFavorites] = useState([]);
  const [cart, setCart] = useState([]);
  const [userLevel, setUserLevel] = useState(1);

  // New state variables
  const [activeTab, setActiveTab] = useState('home');
  const [userChallenges, setUserChallenges] = useState(challenges);
  const [bonds, setBonds] = useState([]);
  const [showBondDialog, setShowBondDialog] = useState(false);
  const [bondAmount, setBondAmount] = useState(0);
  const [bondDuration, setBondDuration] = useState(30);
  const [notifications, setNotifications] = useState([]);

  // Existing effect for recommendations (unchanged)
  useEffect(() => {
    if (showRecommendation) {
      const filteredItems = fashionItems.filter(item => 
        item.style === style &&
        item.sustainabilityScore >= 7 &&
        item.price <= priceRange[0]
      );
      setRecommendations(filteredItems);
    }
  }, [showRecommendation, style, sustainabilityFocus, priceRange]);

  // New effect for bond countdown
  useEffect(() => {
    const timer = setInterval(() => {
      setBonds(prevBonds => 
        prevBonds.map(bond => {
          if (bond.timeRemaining > 0) {
            return { ...bond, timeRemaining: bond.timeRemaining - 1 };
          } else {
            addNotification(`Your bond of $${bond.amount} has matured!`);
            setUserTokens(prevTokens => prevTokens + bond.returnAmount);
            return null;
          }
        }).filter(Boolean)
      );
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  // Existing functions (handleNext, toggleFavorite, addToCart, removeFromCart, calculateTotal, applyDiscount, handlePurchase)

  // New functions
  const addNotification = (message) => {
    setNotifications(prev => [...prev, { id: Date.now(), message }]);
  };

  const removeNotification = (id) => {
    setNotifications(prev => prev.filter(notif => notif.id !== id));
  };

  const investInBond = () => {
    if (bondAmount <= userTokens) {
      const interestRate = 0.05; // 5% interest
      const returnAmount = bondAmount * (1 + interestRate * (bondDuration / 365));
      const newBond = {
        id: Date.now(),
        amount: bondAmount,
        duration: bondDuration,
        returnAmount: Math.round(returnAmount),
        timeRemaining: bondDuration * 24 * 60 * 60, // Convert days to seconds
      };
      setBonds(prev => [...prev, newBond]);
      setUserTokens(prev => prev - bondAmount);
      addNotification(`You've invested ${bondAmount} tokens in a new bond!`);
      setShowBondDialog(false);
    } else {
      addNotification("Not enough tokens to invest in this bond.");
    }
  };

  const retractBond = (bondId) => {
    const bond = bonds.find(b => b.id === bondId);
    if (bond) {
      const penalty = Math.round(bond.amount * 0.1); // 10% penalty
      const returnAmount = bond.amount - penalty;
      setUserTokens(prev => prev + returnAmount);
      setBonds(prev => prev.filter(b => b.id !== bondId));
      addNotification(`Bond retracted. You received ${returnAmount} tokens (including penalty).`);
    }
  };

  const updateChallengeStatus = (challengeId, newStatus) => {
    setUserChallenges(prev => 
      prev.map(challenge => 
        challenge.id === challengeId 
          ? { ...challenge, status: newStatus } 
          : challenge
      )
    );
    if (newStatus === 'complete') {
      const challenge = userChallenges.find(c => c.id === challengeId);
      setUserTokens(prev => prev + challenge.reward);
      addNotification(`Challenge completed! You earned ${challenge.reward} tokens.`);
    }
  };

  // Component for notifications
  const Notifications = () => (
    <div className="fixed top-4 right-4 z-50">
      {notifications.map(notif => (
        <Toast key={notif.id} className="mb-2">
          <div className="flex justify-between items-center">
            <span>{notif.message}</span>
            <Button variant="ghost" size="sm" onClick={() => removeNotification(notif.id)}>
              X
            </Button>
          </div>
        </Toast>
      ))}
    </div>
  );

  // Existing components (Onboarding, RecommendationCard, Recommendations, UserProfile, ShoppingCartComponent)

  // New components
  const ChallengesComponent = () => (
    <Card className="w-full max-w-lg m-2">
      <CardHeader>
        <CardTitle>Challenges</CardTitle>
      </CardHeader>
      <CardContent>
        {userChallenges.map(challenge => (
          <div key={challenge.id} className="mb-4">
            <h3 className="font-bold">{challenge.name}</h3>
            <p>{challenge.description}</p>
            <p>Reward: {challenge.reward} tokens</p>
            <Button 
              onClick={() => updateChallengeStatus(challenge.id, challenge.status === 'complete' ? 'incomplete' : 'complete')}
              variant={challenge.status === 'complete' ? 'outline' : 'default'}
            >
              {challenge.status === 'complete' ? 'Completed' : 'Mark as Complete'}
            </Button>
          </div>
        ))}
      </CardContent>
    </Card>
  );

  const InvestmentComponent = () => (
    <Card className="w-full max-w-lg m-2">
      <CardHeader>
        <CardTitle>Investments</CardTitle>
      </CardHeader>
      <CardContent>
        <Button onClick={() => setShowBondDialog(true)}>Invest in a New Bond</Button>
        {bonds.map(bond => (
          <div key={bond.id} className="mt-4">
            <p>Amount: {bond.amount} tokens</p>
            <p>Return: {bond.returnAmount} tokens</p>
            <p>Time remaining: {Math.floor(bond.timeRemaining / 86400)}d {Math.floor((bond.timeRemaining % 86400) / 3600)}h {Math.floor((bond.timeRemaining % 3600) / 60)}m</p>
            <Button variant="outline" onClick={() => retractBond(bond.id)}>Retract Bond</Button>
          </div>
        ))}
      </CardContent>
    </Card>
  );

  const BondDialog = () => (
    <AlertDialog open={showBondDialog} onOpenChange={setShowBondDialog}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Invest in a Bond</AlertDialogTitle>
          <AlertDialogDescription>
            Choose the amount and duration for your investment.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <div className="py-4">
          <Label>Amount (in tokens)</Label>
          <Input type="number" value={bondAmount} onChange={(e) => setBondAmount(parseInt(e.target.value))} />
          <Label className="mt-4">Duration (in days)</Label>
          <Input type="number" value={bondDuration} onChange={(e) => setBondDuration(parseInt(e.target.value))} />
        </div>
        <AlertDialogFooter>
          <AlertDialogAction onClick={investInBond}>Invest</AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );

  return (
    <div className="flex flex-col items-center justify-center min-h-screen bg-gray-100 p-4">
      <Notifications />
      {!showRecommendation ? (
        <Onboarding />
      ) : (
        <>
          <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full max-w-4xl">
            <TabsList className="grid w-full grid-cols-4">
              <TabsTrigger value="home"><Home className="mr-2" />Home</TabsTrigger>
              <TabsTrigger value="profile"><User className="mr-2" />Profile</TabsTrigger>
              <TabsTrigger value="wishlist"><Star className="mr-2" />Wishlist</TabsTrigger>
              <TabsTrigger value="cart"><ShoppingCart className="mr-2" />Cart</TabsTrigger>
            </TabsList>
            <TabsContent value="home">
              <Recommendations />
              <ChallengesComponent />
              <InvestmentComponent />
            </TabsContent>
            <TabsContent value="profile">
              <UserProfile />
            </TabsContent>
            <TabsContent value="wishlist">
              <Card className="w-full max-w-lg">
                <CardHeader>
                  <CardTitle>Your Wishlist</CardTitle>
                </CardHeader>
                <CardContent>
                  {favorites.map(item => (
                    <div key={item.id} className="flex justify-between items-center mb-2">
                      <span>{item.name}</span>
                      <Button variant="outline" onClick={() => addToCart(item)}>Add to Cart</Button>
                    </div>
                  ))}
                </CardContent>
              </Card>
            </TabsContent>
            <TabsContent value="cart">
              <ShoppingCartComponent />
            </TabsContent>
          </Tabs>
        </>
      )}
      <BondDialog />
    </div>
  );
};

export default App;


import React, { useState, useEffect } from 'react';
import { AlertDialog, AlertDialogAction, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Slider } from '@/components/ui/slider';
import { Progress } from '@/components/ui/progress';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Toast } from '@/components/ui/toast';
import { Leaf, Heart, ShoppingCart, User, Home, Star, Clock } from 'lucide-react';

// Mock data for fashion items
const fashionItems = [
  { id: 1, name: "Eco-Chic Blouse", material: "organic cotton", style: "casual", sustainabilityScore: 8, image: "/api/placeholder/280/200", price: 89.99 },
  { id: 2, name: "Sustainable Suit", material: "recycled polyester", style: "professional", sustainabilityScore: 9, image: "/api/placeholder/280/200", price: 299.99 },
  { id: 3, name: "Upcycled Denim Jacket", material: "upcycled denim", style: "casual", sustainabilityScore: 10, image: "/api/placeholder/280/200", price: 129.99 },
  { id: 4, name: "Bamboo Lounge Set", material: "bamboo fiber", style: "casual", sustainabilityScore: 7, image: "/api/placeholder/280/200", price: 79.99 },
  { id: 5, name: "Hemp Office Dress", material: "hemp", style: "professional", sustainabilityScore: 8, image: "/api/placeholder/280/200", price: 159.99 },
  { id: 6, name: "Tencel Boho Skirt", material: "tencel", style: "eclectic", sustainabilityScore: 9, image: "/api/placeholder/280/200", price: 69.99 },
];

// Mock data for challenges and quests
const challenges = [
  { id: 1, name: "Eco Warrior", description: "Purchase 5 items with sustainability score 8+", reward: 100, status: "incomplete" },
  { id: 2, name: "Material Master", description: "Buy items made from 3 different sustainable materials", reward: 150, status: "incomplete" },
  { id: 3, name: "Stylish Saver", description: "Invest in a bond for 30 days", reward: 200, status: "incomplete" },
];

// Token assignment and calculation functions
const getOnboardingTokens = (style, sustainabilityFocus) => {
  let tokens = 0;
  if (style === 'eclectic') tokens += 50;
  if (sustainabilityFocus === 'materials') tokens += 30;
  return tokens;
};

const getPurchaseTokens = (price) => Math.floor(price / 10);

const App = () => {
  // State variables
  const [step, setStep] = useState(0);
  const [username, setUsername] = useState('');
  const [style, setStyle] = useState('');
  const [sustainabilityFocus, setSustainabilityFocus] = useState('');
  const [priceRange, setPriceRange] = useState([200]);
  const [showRecommendation, setShowRecommendation] = useState(false);
  const [recommendations, setRecommendations] = useState([]);
  const [userTokens, setUserTokens] = useState(0);
  const [favorites, setFavorites] = useState([]);
  const [cart, setCart] = useState([]);
  const [userLevel, setUserLevel] = useState(1);
  const [activeTab, setActiveTab] = useState('home');
  const [userChallenges, setUserChallenges] = useState(challenges);
  const [bonds, setBonds] = useState([]);
  const [showBondDialog, setShowBondDialog] = useState(false);
  const [bondAmount, setBondAmount] = useState(0);
  const [bondDuration, setBondDuration] = useState(30);
  const [notifications, setNotifications] = useState([]);

  // Effects
  useEffect(() => {
    if (showRecommendation) {
      const filteredItems = fashionItems.filter(item => 
        item.style === style &&
        item.sustainabilityScore >= 7 &&
        item.price <= priceRange[0]
      );
      setRecommendations(filteredItems);
    }
  }, [showRecommendation, style, sustainabilityFocus, priceRange]);

  useEffect(() => {
    const timer = setInterval(() => {
      setBonds(prevBonds => 
        prevBonds.map(bond => {
          if (bond.timeRemaining > 0) {
            return { ...bond, timeRemaining: bond.timeRemaining - 1 };
          } else {
            addNotification(`Your bond of $${bond.amount} has matured!`);
            setUserTokens(prevTokens => prevTokens + bond.returnAmount);
            return null;
          }
        }).filter(Boolean)
      );
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  // Functions
  const handleNext = () => {
    if (step < 4) {
      setStep(step + 1);
    } else {
      const onboardingTokens = getOnboardingTokens(style, sustainabilityFocus);
      setUserTokens(onboardingTokens);
      setShowRecommendation(true);
    }
  };

  const toggleFavorite = (item) => {
    setFavorites(prevFavorites => 
      prevFavorites.some(fav => fav.id === item.id)
        ? prevFavorites.filter(fav => fav.id !== item.id)
        : [...prevFavorites, item]
    );
  };

  const addToCart = (item) => {
    setCart(prevCart => [...prevCart, item]);
  };

  const removeFromCart = (itemId) => {
    setCart(prevCart => prevCart.filter(item => item.id !== itemId));
  };

  const calculateTotal = () => {
    return cart.reduce((total, item) => total + item.price, 0);
  };

  const applyDiscount = () => {
    const total = calculateTotal();
    const maxDiscount = total * 0.2; // 20% max discount
    const discountToApply = Math.min(userTokens, maxDiscount);
    return total - discountToApply;
  };

  const handlePurchase = () => {
    const total = applyDiscount();
    const earnedTokens = getPurchaseTokens(total);
    setUserTokens(prevTokens => prevTokens + earnedTokens);
    setUserLevel(prevLevel => Math.min(10, prevLevel + 1));
    setCart([]);
    addNotification(`Purchase successful! You earned ${earnedTokens} tokens.`);
  };

  const addNotification = (message) => {
    setNotifications(prev => [...prev, { id: Date.now(), message }]);
  };

  const removeNotification = (id) => {
    setNotifications(prev => prev.filter(notif => notif.id !== id));
  };

  const investInBond = () => {
    if (bondAmount <= userTokens) {
      const interestRate = 0.05; // 5% interest
      const returnAmount = bondAmount * (1 + interestRate * (bondDuration / 365));
      const newBond = {
        id: Date.now(),
        amount: bondAmount,
        duration: bondDuration,
        returnAmount: Math.round(returnAmount),
        timeRemaining: bondDuration * 24 * 60 * 60, // Convert days to seconds
      };
      setBonds(prev => [...prev, newBond]);
      setUserTokens(prev => prev - bondAmount);
      addNotification(`You've invested ${bondAmount} tokens in a new bond!`);
      setShowBondDialog(false);
    } else {
      addNotification("Not enough tokens to invest in this bond.");
    }
  };

  const retractBond = (bondId) => {
    const bond = bonds.find(b => b.id === bondId);
    if (bond) {
      const penalty = Math.round(bond.amount * 0.1); // 10% penalty
      const returnAmount = bond.amount - penalty;
      setUserTokens(prev => prev + returnAmount);
      setBonds(prev => prev.filter(b => b.id !== bondId));
      addNotification(`Bond retracted. You received ${returnAmount} tokens (including penalty).`);
    }
  };

  const updateChallengeStatus = (challengeId, newStatus) => {
    setUserChallenges(prev => 
      prev.map(challenge => 
        challenge.id === challengeId 
          ? { ...challenge, status: newStatus } 
          : challenge
      )
    );
    if (newStatus === 'complete') {
      const challenge = userChallenges.find(c => c.id === challengeId);
      setUserTokens(prev => prev + challenge.reward);
      addNotification(`Challenge completed! You earned ${challenge.reward} tokens.`);
    }
  };

  // Components
  const Notifications = () => (
    <div className="fixed top-4 right-4 z-50">
      {notifications.map(notif => (
        <Toast key={notif.id} className="mb-2">
          <div className="flex justify-between items-center">
            <span>{notif.message}</span>
            <Button variant="ghost" size="sm" onClick={() => removeNotification(notif.id)}>
              X
            </Button>
          </div>
        </Toast>
      ))}
    </div>
  );

  const Onboarding = () => (
    <Card className="w-[350px]">
      <CardHeader>
        <CardTitle>Welcome to EcoStyle</CardTitle>
        <CardDescription>Let's personalize your sustainable fashion journey</CardDescription>
      </CardHeader>
      <CardContent>
        {step === 0 && (
          <div className="grid w-full items-center gap-4">
            <div className="flex flex-col space-y-1.5">
              <Label htmlFor="name">Name</Label>
              <Input id="name" placeholder="Enter your name" value={username} onChange={(e) => setUsername(e.target.value)} />
            </div>
          </div>
        )}
        {step === 1 && (
          <div className="grid w-full items-center gap-4">
            <div className="flex flex-col space-y-1.5">
              <Label htmlFor="style">Your Style</Label>
              <Select onValueChange={setStyle}>
                <SelectTrigger id="style">
                  <SelectValue placeholder="Select your style" />
                </SelectTrigger>
                <SelectContent position="popper">
                  <SelectItem value="casual">Casual</SelectItem>
                  <SelectItem value="professional">Professional</SelectItem>
                  <SelectItem value="eclectic">Eclectic</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        )}
        {step === 2 && (
          <div className="grid w-full items-center gap-4">
            <div className="flex flex-col space-y-1.5">
              <Label htmlFor="sustainability">Sustainability Focus</Label>
              <Select onValueChange={setSustainabilityFocus}>
                <SelectTrigger id="sustainability">
                  <SelectValue placeholder="Select your focus" />
                </SelectTrigger>
                <SelectContent position="popper">
                  <SelectItem value="materials">Sustainable Materials</SelectItem>
                  <SelectItem value="fairTrade">Fair Trade</SelectItem>
                  <SelectItem value="localProduction">Local Production</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        )}
        {step === 3 && (
          <div className="grid w-full items-center gap-4">
            <Label htmlFor="price">Preferred Price Range</Label>
            <Slider
              id="price"
              max={500}
              step={10}
              value={priceRange}
              onValueChange={setPriceRange}
            />
            <div className="text-center">Up to ${priceRange[0]}</div>
          </div>
        )}
      </CardContent>
      <CardFooter className="flex justify-between">
        <Button variant="outline" onClick={() => setStep(Math.max(0, step - 1))}>Back</Button>
        <Button onClick={handleNext}>Next</Button>
      </CardFooter>
    </Card>
  );

  const RecommendationCard = ({ item }) => (
    <Card className="w-[280px] m-2">
      <CardHeader>
        <CardTitle>{item.name}</CardTitle>
        <CardDescription>{item.material}</CardDescription>
      </CardHeader>
      <CardContent>
        <img src={item.image} alt={item.name} className="w-full h-[200px] object-cover rounded-md" />
        <div className="flex items-center justify-between mt-2">
          <div className="flex items-center">
            <Leaf className="text-green-500 mr-1" size={16} />
            <span className="text-sm font-medium">Score: {item.sustainabilityScore}/10</span>
          </div>
          <span className="text-sm font-bold">${item.price.toFixed(2)}</span>
        </div>
      </CardContent>
      <CardFooter className="flex justify-between">
        <Button variant="ghost" size="icon" onClick={() => toggleFavorite(item)}>
          <Heart className={`h-4 w-4 ${favorites.some(fav => fav.id === item.id) ? 'fill-red-500' : ''}`} />
        </Button>
        <Button onClick={() => addToCart(item)}>Add to Cart</Button>
      </CardFooter>
    </Card>
  );

  const Recommendations = () => (
    <div className="w-full max-w-4xl">
      <h2 className="text-2xl font-bold mb-4">Your Sustainable Recommendations</h2>
      <div className="flex flex-wrap justify-center">
        {recommendations.map(item => (
          <RecommendationCard key={item.id} item={item} />
        ))}
      </div>
    </div>
  );

  const UserProfile = () => (
    <Card className="w-[300px] m-2">
      <CardHeader>
        <CardTitle>{username}'s Profile</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="mb-4">
          <Label>Level {userLevel}</Label>
          <Progress value={(userLevel / 10) * 100} className="mt


complete the incomplete code.