import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
// Import all required icons for the component
import { Calculator, Scale, Heart, CheckCircle, AlertTriangle, Info, Dumbbell, Apple, Target, TrendingUp, User } from "lucide-react";

interface BMICategory {
  name: string;
  message: string;
  color: string;
  position: number;
  bgColor: string;
  borderColor: string;
  textColor: string;
  recommendations: {
    sports: string[];
    nutrition: string[];
    lifestyle: string[];
  };
}

const bmiCategories: Record<string, BMICategory> = {
  underweight: {
    name: "Underweight",
    message: "You may be underweight. Consider consulting a healthcare provider for guidance on healthy weight gain.",
    color: "bg-blue-500",
    position: 10,
    bgColor: "bg-blue-50",
    borderColor: "border-blue-200",
    textColor: "text-blue-800",
    recommendations: {
      sports: [
        "Strength training with weights to build muscle mass",
        "Swimming for low-impact full-body exercise",
        "Yoga to improve flexibility and appetite",
        "Rock climbing for functional strength building"
      ],
      nutrition: [
        "Increase caloric intake with healthy, nutrient-dense foods",
        "Add protein-rich foods: eggs, lean meats, fish, legumes",
        "Include healthy fats: avocados, nuts, olive oil",
        "Eat frequent smaller meals throughout the day",
        "Consider protein smoothies as snacks"
      ],
      lifestyle: [
        "Focus on building lean muscle through resistance training",
        "Get adequate sleep (7-9 hours) for muscle recovery",
        "Reduce stress which can suppress appetite",
        "Consider working with a nutritionist for meal planning"
      ]
    }
  },
  normal: {
    name: "Normal Weight", 
    message: "Great job! You have a healthy body weight. Keep maintaining your current lifestyle!",
    color: "bg-green-500",
    position: 40,
    bgColor: "bg-green-50",
    borderColor: "border-green-200", 
    textColor: "text-green-800",
    recommendations: {
      sports: [
        "Mix cardio and strength training 3-5 times per week",
        "Try new activities: tennis, hiking, cycling, dancing",
        "Join group fitness classes for motivation",
        "Aim for 150 minutes of moderate aerobic activity weekly"
      ],
      nutrition: [
        "Maintain a balanced diet with variety",
        "Fill half your plate with vegetables and fruits",
        "Choose whole grains over refined carbohydrates",
        "Stay hydrated with 8-10 glasses of water daily",
        "Practice portion control and mindful eating"
      ],
      lifestyle: [
        "Continue your current healthy habits",
        "Regular health check-ups to monitor wellness",
        "Manage stress through meditation or hobbies",
        "Stay active throughout the day, take stairs when possible"
      ]
    }
  },
  overweight: {
    name: "Overweight",
    message: "You're in the overweight range. Consider incorporating more physical activity and healthy eating habits.",
    color: "bg-yellow-500",
    position: 65,
    bgColor: "bg-yellow-50",
    borderColor: "border-yellow-200",
    textColor: "text-yellow-800",
    recommendations: {
      sports: [
        "Start with 30 minutes of brisk walking daily",
        "Low-impact exercises: swimming, cycling, elliptical",
        "Strength training 2-3 times per week",
        "Join recreational sports leagues for fun motivation"
      ],
      nutrition: [
        "Create a moderate caloric deficit (300-500 calories)",
        "Reduce portion sizes and eat slowly",
        "Limit processed foods, sugary drinks, and snacks",
        "Increase fiber intake with vegetables and whole grains",
        "Plan and prep meals to avoid unhealthy choices"
      ],
      lifestyle: [
        "Set realistic weight loss goals (1-2 pounds per week)",
        "Track food intake and physical activity",
        "Find active hobbies: gardening, dancing, hiking",
        "Build a support system of family and friends"
      ]
    }
  },
  obese1: {
    name: "Obese (Class I)",
    message: "You're in the obese range. It's recommended to consult with a healthcare professional for a weight management plan.",
    color: "bg-orange-500",
    position: 80,
    bgColor: "bg-orange-50",
    borderColor: "border-orange-200",
    textColor: "text-orange-800",
    recommendations: {
      sports: [
        "Start with gentle, low-impact activities",
        "Water aerobics and swimming for joint-friendly exercise",
        "Seated exercises and chair yoga to begin",
        "Gradually increase walking duration and frequency"
      ],
      nutrition: [
        "Work with a dietitian for personalized meal planning",
        "Focus on whole, unprocessed foods",
        "Control portions using smaller plates and bowls",
        "Eliminate sugary beverages and replace with water",
        "Keep a food diary to identify eating patterns"
      ],
      lifestyle: [
        "Consult healthcare providers before starting exercise",
        "Set small, achievable goals and celebrate progress",
        "Address emotional eating triggers",
        "Consider joining support groups or weight loss programs"
      ]
    }
  },
  obese2: {
    name: "Obese (Class II+)",
    message: "You're in the severely obese range. Please consult with a healthcare professional immediately for proper medical guidance.",
    color: "bg-red-500",
    position: 95,
    bgColor: "bg-red-50",
    borderColor: "border-red-200",
    textColor: "text-red-800",
    recommendations: {
      sports: [
        "Begin with supervised, medically-approved activities",
        "Chair exercises and gentle stretching",
        "Water-based exercises for reduced joint stress",
        "Physical therapy may be beneficial initially"
      ],
      nutrition: [
        "Work closely with healthcare team and registered dietitian",
        "Consider medically supervised weight loss programs",
        "Focus on nutrient-dense, low-calorie foods",
        "Meal replacement options under medical guidance",
        "Address underlying health conditions affecting weight"
      ],
      lifestyle: [
        "Immediate medical consultation is essential",
        "Comprehensive health assessment including blood work",
        "Mental health support for sustainable lifestyle changes",
        "Family involvement in lifestyle modification plan"
      ]
    }
  }
};

export default function Home() {
  const [weightUnit, setWeightUnit] = useState("lbs");
  const [heightUnit, setHeightUnit] = useState("ft");
  const [weight, setWeight] = useState("");
  const [height, setHeight] = useState("");
  const [feet, setFeet] = useState("");
  const [inches, setInches] = useState("");
  const [age, setAge] = useState("");
  const [gender, setGender] = useState("male");
  const [activityLevel, setActivityLevel] = useState("sedentary");
  const [goal, setGoal] = useState("maintain");
  const [waist, setWaist] = useState("");
  const [neck, setNeck] = useState("");
  const [hip, setHip] = useState("");
  const [bmi, setBMI] = useState<number | null>(null);
  const [category, setCategory] = useState<BMICategory | null>(null);
  const [bodyFat, setBodyFat] = useState<number | null>(null);
  const [dailyCalories, setDailyCalories] = useState<number | null>(null);
  const [idealWeightRange, setIdealWeightRange] = useState<{min: number, max: number} | null>(null);
  const [error, setError] = useState("");

  const calculateBMI = () => {
    const weightNum = parseFloat(weight);
    let heightNum: number;

    if (heightUnit === "ft") {
      const feetNum = parseFloat(feet) || 0;
      const inchesNum = parseFloat(inches) || 0;
      heightNum = feetNum * 12 + inchesNum; // Total inches
    } else {
      heightNum = parseFloat(height);
    }

    // Validation
    if (!weightNum || !heightNum || weightNum <= 0 || heightNum <= 0) {
      setBMI(null);
      setCategory(null);
      setBodyFat(null);
      setDailyCalories(null);
      setIdealWeightRange(null);
      setError("");
      return;
    }

    if (weightUnit === "lbs" && heightUnit === "ft") {
      if (weightNum < 50 || weightNum > 1000 || heightNum < 36 || heightNum > 120) {
        setError('Please enter realistic weight (50-1000 lbs) and height (3-10 ft) values.');
        setBMI(null);
        setCategory(null);
        setBodyFat(null);
        setDailyCalories(null);
        setIdealWeightRange(null);
        return;
      }
    } else if (weightUnit === "kg" && heightUnit === "cm") {
      if (weightNum < 20 || weightNum > 500 || heightNum < 50 || heightNum > 300) {
        setError('Please enter realistic weight (20-500 kg) and height (50-300 cm) values.');
        setBMI(null);
        setCategory(null);
        setBodyFat(null);
        setDailyCalories(null);
        setIdealWeightRange(null);
        return;
      }
    } else {
      // Mixed units - convert to metric for validation
      const weightInKg = weightUnit === "lbs" ? weightNum * 0.453592 : weightNum;
      const heightInCm = heightUnit === "ft" ? heightNum * 2.54 : heightNum;
      if (weightInKg < 20 || weightInKg > 500 || heightInCm < 50 || heightInCm > 300) {
        setError('Please enter realistic measurements.');
        setBMI(null);
        setCategory(null);
        setBodyFat(null);
        setDailyCalories(null);
        setIdealWeightRange(null);
        return;
      }
    }

    // Calculate BMI
    let bmiValue: number;
    let heightInMeters: number;
    let weightInKg: number;
    
    // Convert to metric for calculations
    weightInKg = weightUnit === "lbs" ? weightNum * 0.453592 : weightNum;
    if (heightUnit === "ft") {
      heightInMeters = heightNum * 0.0254; // inches to meters
    } else {
      heightInMeters = heightNum / 100; // cm to meters
    }
    
    // Calculate BMI using metric units
    bmiValue = weightInKg / (heightInMeters * heightInMeters);

    // Age and gender adjusted BMI interpretation
    const ageNum = parseFloat(age) || 25;
    let selectedCategory: BMICategory;
    
    // Adjust BMI thresholds based on age
    let underweightThreshold = 18.5;
    let normalThreshold = 25;
    let overweightThreshold = 30;
    let obese1Threshold = 35;
    
    if (ageNum >= 65) {
      // Older adults can have slightly higher healthy BMI
      underweightThreshold = 22;
      normalThreshold = 27;
      overweightThreshold = 32;
    }
    
    if (bmiValue < underweightThreshold) {
      selectedCategory = bmiCategories.underweight;
    } else if (bmiValue < normalThreshold) {
      selectedCategory = bmiCategories.normal;
    } else if (bmiValue < overweightThreshold) {
      selectedCategory = bmiCategories.overweight;
    } else if (bmiValue < obese1Threshold) {
      selectedCategory = bmiCategories.obese1;
    } else {
      selectedCategory = bmiCategories.obese2;
    }

    // Calculate Body Fat Percentage (Navy Method)
    let bodyFatPercentage: number | null = null;
    const waistNum = parseFloat(waist);
    const neckNum = parseFloat(neck);
    const hipNum = parseFloat(hip);
    
    if (waistNum && neckNum) {
      // Convert measurements to cm if needed
      const waistCm = waistNum; // Assume measurements are in cm for now
      const neckCm = neckNum;
      const hipCm = hipNum;
      const heightCm = heightInMeters * 100;
      
      if (gender === "male") {
        bodyFatPercentage = 495 / (1.0324 - 0.19077 * Math.log10(waistCm - neckCm) + 0.15456 * Math.log10(heightCm)) - 450;
      } else if (hipCm) {
        bodyFatPercentage = 495 / (1.29579 - 0.35004 * Math.log10(waistCm + hipCm - neckCm) + 0.22100 * Math.log10(heightCm)) - 450;
      }
      
      // Ensure body fat is within realistic range
      if (bodyFatPercentage !== null) {
        if (bodyFatPercentage < 5) bodyFatPercentage = 5;
        if (bodyFatPercentage > 50) bodyFatPercentage = 50;
      }
    }
    
    // Calculate Daily Calorie Needs (Mifflin-St Jeor Equation)
    let bmr: number;
    if (gender === "male") {
      bmr = 10 * weightInKg + 6.25 * (heightInMeters * 100) - 5 * ageNum + 5;
    } else {
      bmr = 10 * weightInKg + 6.25 * (heightInMeters * 100) - 5 * ageNum - 161;
    }
    
    const activityMultipliers = {
      sedentary: 1.2,
      light: 1.375,
      moderate: 1.55,
      active: 1.725,
      very_active: 1.9
    };
    
    const tdee = bmr * activityMultipliers[activityLevel as keyof typeof activityMultipliers];
    
    let dailyCalorieNeeds = tdee;
    if (goal === "lose") {
      dailyCalorieNeeds = tdee - 500; // 500 calorie deficit for 1lb/week loss
    } else if (goal === "gain") {
      dailyCalorieNeeds = tdee + 500; // 500 calorie surplus for 1lb/week gain
    }
    
    // Calculate Ideal Weight Range (based on BMI 18.5-24.9)
    const minIdealWeight = 18.5 * (heightInMeters * heightInMeters);
    const maxIdealWeight = 24.9 * (heightInMeters * heightInMeters);
    
    // Convert to user's preferred weight unit
    let idealRange;
    if (weightUnit === "lbs") {
      idealRange = {
        min: minIdealWeight * 2.20462, // kg to lbs
        max: maxIdealWeight * 2.20462
      };
    } else {
      idealRange = {
        min: minIdealWeight,
        max: maxIdealWeight
      };
    }

    setBMI(bmiValue);
    setCategory(selectedCategory);
    setBodyFat(bodyFatPercentage);
    setDailyCalories(Math.round(dailyCalorieNeeds));
    setIdealWeightRange(idealRange);
    setError("");
  };

  useEffect(() => {
    calculateBMI();
  }, [weight, height, feet, inches, weightUnit, heightUnit, age, gender, activityLevel, goal, waist, neck, hip]);

  const resetCalculation = () => {
    setBMI(null);
    setCategory(null);
    setBodyFat(null);
    setDailyCalories(null);
    setIdealWeightRange(null);
    setError("");
  };

  const handleWeightUnitChange = (unit: string) => {
    setWeightUnit(unit);
    setWeight("");
    resetCalculation();
  };

  const handleHeightUnitChange = (unit: string) => {
    setHeightUnit(unit);
    setHeight("");
    setFeet("");
    setInches("");
    resetCalculation();
  };

  return (
    <div className="bg-gradient-to-br from-slate-50 to-blue-50">
      {/* Hero Section */}
      <div className="bg-white border-b border-slate-200">
        <div className="max-w-4xl mx-auto px-4 py-8">
          <div className="text-center">
            <h1 className="text-4xl font-bold text-blue-600 mb-4 flex items-center justify-center gap-3">
              <Scale className="h-10 w-10" />
              Free BMI Calculator Online
            </h1>
            <p className="text-xl text-slate-600 max-w-2xl mx-auto mb-4">
              Calculate your Body Mass Index, ideal weight, body fat percentage & daily calories for weight loss - Get instant, personalized health recommendations
            </p>
            <div className="flex flex-wrap justify-center gap-2 text-sm text-slate-500">
              <span className="bg-blue-100 text-blue-800 px-3 py-1 rounded-full">✓ Instant Results</span>
              <span className="bg-green-100 text-green-800 px-3 py-1 rounded-full">✓ No Signup Required</span>
              <span className="bg-purple-100 text-purple-800 px-3 py-1 rounded-full">✓ 100% Free</span>
              <span className="bg-orange-100 text-orange-800 px-3 py-1 rounded-full">✓ Medically Accurate</span>
            </div>
          </div>
        </div>
      </div>


      <main className="max-w-7xl mx-auto px-4 py-8">
        <div className="grid lg:grid-cols-3 gap-8">
          {/* Left Sidebar - SEO Content */}
          <div className="lg:order-1 space-y-6">
            <div className="sticky top-8">
              
              {/* SEO Content Section */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">Free BMI Calculator Online</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3 text-sm text-slate-700">
                  <p>Our <strong>free BMI calculator online</strong> provides instant, accurate body mass index calculations with comprehensive health analysis. Calculate BMI, body fat percentage, and daily calorie needs in seconds.</p>
                  <p>Get your <strong>ideal weight range</strong> and personalized health recommendations for <strong>weight loss</strong>, fitness goals, and optimal wellness based on age, gender, and activity level.</p>
                  <p>Perfect for <strong>weight management</strong>, fitness tracking, and health monitoring. Trusted by thousands daily for accurate health assessment and <strong>weight loss planning</strong>. <a href="/about" className="text-blue-600 hover:text-blue-800 underline">Learn more about our mission</a>.</p>
                  <div className="mt-4 p-3 bg-blue-50 rounded-lg">
                    <p className="text-xs text-blue-700 font-medium">📊 Popular Searches: "BMI calculator for weight loss", "healthy BMI range", "ideal weight calculator", "body fat percentage"</p>
                  </div>
                </CardContent>
              </Card>
              
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">Weight Loss Calculator</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3 text-sm text-slate-700">
                  <p><strong>Calculate calories for weight loss</strong> with our advanced calculator that determines your daily caloric needs based on your BMI and fitness goals.</p>
                  <p>Track your progress toward <strong>healthy weight goals</strong> with personalized diet and exercise recommendations for sustainable weight management.</p>
                </CardContent>
              </Card>
            </div>
          </div>
          {/* Calculator Section */}
          <div className="lg:order-2 lg:col-span-1 space-y-6">
            {/* Unit Toggle */}
            <Card>
              <CardHeader>
                <CardTitle>Free BMI Calculator - Calculate Your Body Mass Index</CardTitle>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Weight Input */}
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <Label htmlFor="weight">Weight</Label>
                    <Select value={weightUnit} onValueChange={handleWeightUnitChange}>
                      <SelectTrigger className="w-20" data-testid="select-weight-unit">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="lbs">lbs</SelectItem>
                        <SelectItem value="kg">kg</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <Input
                    id="weight"
                    type="number"
                    value={weight}
                    onChange={(e) => setWeight(e.target.value)}
                    placeholder={`Enter weight in ${weightUnit === "lbs" ? "pounds" : "kilograms"}`}
                    min="1"
                    max={weightUnit === "lbs" ? "1000" : "500"}
                    step="0.1"
                    data-testid="input-weight"
                  />
                </div>

                {/* Height Input(s) */}
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <Label htmlFor="height">Height</Label>
                    <Select value={heightUnit} onValueChange={handleHeightUnitChange}>
                      <SelectTrigger className="w-20" data-testid="select-height-unit">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="ft">ft</SelectItem>
                        <SelectItem value="cm">cm</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  {heightUnit === "ft" ? (
                    <div className="grid grid-cols-2 gap-4">
                      <Input
                        id="feet"
                        type="number"
                        value={feet}
                        onChange={(e) => setFeet(e.target.value)}
                        placeholder="Feet"
                        min="1"
                        max="10"
                        step="1"
                        data-testid="input-feet"
                      />
                      <Input
                        id="inches"
                        type="number"
                        value={inches}
                        onChange={(e) => setInches(e.target.value)}
                        placeholder="Inches"
                        min="0"
                        max="11"
                        step="1"
                        data-testid="input-inches"
                      />
                    </div>
                  ) : (
                    <Input
                      id="height"
                      type="number"
                      value={height}
                      onChange={(e) => setHeight(e.target.value)}
                      placeholder="Enter height in centimeters"
                      min="50"
                      max="300"
                      step="0.1"
                      data-testid="input-height"
                    />
                  )}
                </div>

                {/* Age and Gender */}
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="age">Age</Label>
                    <Input
                      id="age"
                      type="number"
                      value={age}
                      onChange={(e) => setAge(e.target.value)}
                      placeholder="Enter age"
                      min="1"
                      max="120"
                      data-testid="input-age"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="gender">Gender</Label>
                    <Select value={gender} onValueChange={setGender}>
                      <SelectTrigger data-testid="select-gender">
                        <SelectValue placeholder="Select gender" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="male">Male</SelectItem>
                        <SelectItem value="female">Female</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                {/* Activity Level and Goal */}
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="activity">Activity Level</Label>
                    <Select value={activityLevel} onValueChange={setActivityLevel}>
                      <SelectTrigger data-testid="select-activity">
                        <SelectValue placeholder="Select activity level" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="sedentary">Sedentary (Desk job)</SelectItem>
                        <SelectItem value="light">Light (1-3 days/week)</SelectItem>
                        <SelectItem value="moderate">Moderate (3-5 days/week)</SelectItem>
                        <SelectItem value="active">Active (6-7 days/week)</SelectItem>
                        <SelectItem value="very_active">Very Active (2x/day)</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="goal">Goal</Label>
                    <Select value={goal} onValueChange={setGoal}>
                      <SelectTrigger data-testid="select-goal">
                        <SelectValue placeholder="Select goal" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="lose">Lose Weight</SelectItem>
                        <SelectItem value="maintain">Maintain Weight</SelectItem>
                        <SelectItem value="gain">Gain Weight</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                {/* Body Measurements for Body Fat */}
                <div className="space-y-4">
                  <div className="text-sm font-medium text-slate-700">
                    Body Measurements (Optional - for body fat estimation)
                  </div>
                  <div className="grid grid-cols-3 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="waist">Waist (cm)</Label>
                      <Input
                        id="waist"
                        type="number"
                        value={waist}
                        onChange={(e) => setWaist(e.target.value)}
                        placeholder="Centimeters"
                        min="1"
                        step="0.1"
                        data-testid="input-waist"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="neck">Neck (cm)</Label>
                      <Input
                        id="neck"
                        type="number"
                        value={neck}
                        onChange={(e) => setNeck(e.target.value)}
                        placeholder="Centimeters"
                        min="1"
                        step="0.1"
                        data-testid="input-neck"
                      />
                    </div>
                    {gender === "female" && (
                      <div className="space-y-2">
                        <Label htmlFor="hip">Hip (cm)</Label>
                        <Input
                          id="hip"
                          type="number"
                          value={hip}
                          onChange={(e) => setHip(e.target.value)}
                          placeholder="Centimeters"
                          min="1"
                          step="0.1"
                          data-testid="input-hip"
                        />
                      </div>
                    )}
                  </div>
                </div>

                {/* Error Message */}
                {error && (
                  <Alert variant="destructive" data-testid="alert-error">
                    <AlertTriangle className="h-4 w-4" />
                    <AlertDescription>{error}</AlertDescription>
                  </Alert>
                )}
              </CardContent>
            </Card>

            {/* Results Section */}
            {bmi && category && (
              <Card className="result-animation" data-testid="card-results">
                <CardHeader>
                  <CardTitle>Your Results</CardTitle>
                </CardHeader>
                <CardContent className="space-y-6">
                  {/* BMI Value */}
                  <div className="text-center">
                    <div className="text-4xl font-bold text-blue-600 mb-2" data-testid="text-bmi-value">
                      {bmi.toFixed(1)}
                    </div>
                    <div className="text-slate-600">Your BMI</div>
                  </div>

                  {/* BMI Progress Bar */}
                  <div>
                    <div className="flex justify-between text-xs text-slate-600 mb-2">
                      <span>Underweight</span>
                      <span>Normal</span>
                      <span>Overweight</span>
                      <span>Obese</span>
                    </div>
                    <div className="bmi-progress relative">
                      <div
                        className="bmi-indicator absolute top-[-2px] w-3 h-3 bg-white border-2 border-slate-800 rounded-full transform -translate-x-1/2 transition-all duration-300 ease-in-out"
                        style={{ left: `${category.position}%` }}
                        data-testid="indicator-bmi"
                      />
                    </div>
                    <div className="flex justify-between text-xs text-slate-600 mt-1">
                      <span>18.5</span>
                      <span>25</span>
                      <span>30</span>
                      <span>35+</span>
                    </div>
                  </div>

                  {/* Category and Message */}
                  <div 
                    className={`text-center p-4 rounded-lg border ${category.bgColor} ${category.borderColor}`}
                    data-testid="display-category"
                  >
                    <div className={`text-lg font-semibold mb-2 ${category.textColor}`} data-testid="text-category-name">
                      {category.name}
                    </div>
                    <div className={`text-sm ${category.textColor}`} data-testid="text-category-message">
                      {category.message}
                    </div>
                  </div>
                </CardContent>
              </Card>
            )}

            {/* Additional Health Metrics */}
            {bmi && (bodyFat || dailyCalories || idealWeightRange) && (
              <Card className="result-animation" data-testid="card-health-metrics">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Calculator className="h-5 w-5 text-green-600" />
                    Additional Health Metrics
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-6">
                  <div className="grid md:grid-cols-3 gap-6">
                    {/* Body Fat Percentage */}
                    {bodyFat && (
                      <div className="text-center p-4 bg-blue-50 rounded-lg border border-blue-200" data-testid="display-body-fat">
                        <div className="text-2xl font-bold text-blue-600 mb-1">
                          {bodyFat.toFixed(1)}%
                        </div>
                        <div className="text-sm text-blue-800 font-medium">Body Fat</div>
                        <div className="text-xs text-blue-600 mt-1">
                          {bodyFat < 10 ? "Very Low" : 
                           bodyFat < 15 ? "Low" :
                           bodyFat < 20 ? "Normal" :
                           bodyFat < 25 ? "Moderate" : "High"}
                        </div>
                      </div>
                    )}

                    {/* Daily Calorie Needs */}
                    {dailyCalories && (
                      <div className="text-center p-4 bg-green-50 rounded-lg border border-green-200" data-testid="display-calories">
                        <div className="text-2xl font-bold text-green-600 mb-1">
                          {dailyCalories.toLocaleString()}
                        </div>
                        <div className="text-sm text-green-800 font-medium">Daily Calories</div>
                        <div className="text-xs text-green-600 mt-1">
                          To {goal === "lose" ? "lose weight" : goal === "gain" ? "gain weight" : "maintain weight"}
                        </div>
                      </div>
                    )}

                    {/* Ideal Weight Range */}
                    {idealWeightRange && (
                      <div className="text-center p-4 bg-purple-50 rounded-lg border border-purple-200" data-testid="display-ideal-weight">
                        <div className="text-lg font-bold text-purple-600 mb-1">
                          {idealWeightRange.min.toFixed(0)} - {idealWeightRange.max.toFixed(0)}
                        </div>
                        <div className="text-sm text-purple-800 font-medium">
                          Ideal Range ({weightUnit})
                        </div>
                        <div className="text-xs text-purple-600 mt-1">
                          {weight && parseFloat(weight) ? (
                            (() => {
                              const currentWeight = parseFloat(weight);
                              if (currentWeight < idealWeightRange.min) {
                                return `${(idealWeightRange.min - currentWeight).toFixed(0)} ${weightUnit} to gain`;
                              } else if (currentWeight > idealWeightRange.max) {
                                return `${(currentWeight - idealWeightRange.max).toFixed(0)} ${weightUnit} to lose`;
                              } else {
                                return "You're in the ideal range!";
                              }
                            })()
                          ) : "BMI 18.5-24.9 range"}
                        </div>
                      </div>
                    )}
                  </div>

                  {/* Enhanced BMI Interpretation */}
                  {age && (
                    <div className="bg-slate-50 rounded-lg p-4 border border-slate-200">
                      <h4 className="font-semibold text-slate-800 mb-2 flex items-center gap-2">
                        <TrendingUp className="h-4 w-4 text-slate-600" />
                        Age-Adjusted Analysis
                      </h4>
                      <p className="text-sm text-slate-700">
                        {parseFloat(age) >= 65 
                          ? "For adults 65+, slightly higher BMI values (up to 27) may be healthy and associated with better outcomes."
                          : parseFloat(age) < 18
                          ? "BMI calculations for children and teens require age and gender-specific percentiles. Please consult a healthcare provider."
                          : "Your BMI is interpreted using standard adult guidelines. Individual factors like muscle mass and bone density should also be considered."
                        }
                      </p>
                    </div>
                  )}
                </CardContent>
              </Card>
            )}

            {/* Personalized Recommendations */}
            {bmi && category && (
              <Card className="result-animation" data-testid="card-recommendations">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Target className="h-5 w-5 text-blue-600" />
                    Personalized Recommendations
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-6">
                  {/* Sports & Exercise */}
                  <div className="space-y-3">
                    <h4 className="font-semibold text-slate-800 flex items-center gap-2">
                      <Dumbbell className="h-4 w-4 text-blue-600" />
                      Sports & Exercise
                    </h4>
                    <ul className="space-y-2">
                      {category.recommendations.sports.map((sport, index) => (
                        <li key={index} className="flex items-start text-sm text-slate-700">
                          <CheckCircle className="h-4 w-4 text-green-500 mr-2 mt-0.5 flex-shrink-0" />
                          <span data-testid={`recommendation-sport-${index}`}>{sport}</span>
                        </li>
                      ))}
                    </ul>
                  </div>

                  {/* Nutrition */}
                  <div className="space-y-3">
                    <h4 className="font-semibold text-slate-800 flex items-center gap-2">
                      <Apple className="h-4 w-4 text-green-600" />
                      Nutrition Guidelines
                    </h4>
                    <ul className="space-y-2">
                      {category.recommendations.nutrition.map((nutrition, index) => (
                        <li key={index} className="flex items-start text-sm text-slate-700">
                          <CheckCircle className="h-4 w-4 text-green-500 mr-2 mt-0.5 flex-shrink-0" />
                          <span data-testid={`recommendation-nutrition-${index}`}>{nutrition}</span>
                        </li>
                      ))}
                    </ul>
                  </div>

                  {/* Lifestyle */}
                  <div className="space-y-3">
                    <h4 className="font-semibold text-slate-800 flex items-center gap-2">
                      <Heart className="h-4 w-4 text-red-500" />
                      Lifestyle Tips
                    </h4>
                    <ul className="space-y-2">
                      {category.recommendations.lifestyle.map((lifestyle, index) => (
                        <li key={index} className="flex items-start text-sm text-slate-700">
                          <CheckCircle className="h-4 w-4 text-green-500 mr-2 mt-0.5 flex-shrink-0" />
                          <span data-testid={`recommendation-lifestyle-${index}`}>{lifestyle}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                </CardContent>
              </Card>
            )}
          </div>

          {/* Information Section */}
          <div className="lg:order-3 lg:col-span-1 space-y-6">
            {/* BMI Categories */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Info className="h-5 w-5 text-blue-600" />
                  Understanding BMI Categories
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                {Object.entries(bmiCategories).map(([key, cat]) => (
                  <div
                    key={key}
                    className={`category-card flex items-center p-3 rounded-lg ${cat.bgColor} border ${cat.borderColor} transition-all hover:shadow-md hover:-translate-y-0.5`}
                  >
                    <div className={`w-4 h-4 ${cat.color} rounded-full mr-3`}></div>
                    <div className="flex-1">
                      <div className={`font-medium ${cat.textColor}`}>{cat.name}</div>
                      <div className={`text-sm ${cat.textColor.replace('800', '600')}`}>
                        {key === 'underweight' && 'BMI less than 18.5'}
                        {key === 'normal' && 'BMI 18.5 - 24.9'}
                        {key === 'overweight' && 'BMI 25 - 29.9'}
                        {key === 'obese1' && 'BMI 30 - 34.9'}
                        {key === 'obese2' && 'BMI 35 or greater'}
                      </div>
                    </div>
                  </div>
                ))}
              </CardContent>
            </Card>


            {/* Health Tips */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Heart className="h-5 w-5 text-red-500" />
                  Healthy Weight Management Tips
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3 text-sm text-slate-600">
                {[
                  "Maintain a balanced diet rich in fruits, vegetables, and lean proteins",
                  "Engage in regular physical activity for at least 150 minutes weekly", 
                  "Stay hydrated by drinking 8-10 glasses of water daily",
                  "Get sufficient sleep (7-9 hours) for optimal metabolism",
                  "Monitor your BMI regularly and consult healthcare professionals"
                ].map((tip, index) => (
                  <div key={index} className="flex items-start">
                    <CheckCircle className="h-4 w-4 text-green-500 mr-2 mt-0.5 flex-shrink-0" />
                    <span>{tip}</span>
                  </div>
                ))}
              </CardContent>
            </Card>

            {/* SEO Content Section */}
            <Card>
              <CardHeader>
                <CardTitle>How to Use This BMI Calculator</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4 text-sm text-slate-700">
                <div>
                  <h4 className="font-semibold mb-2">Step 1: Enter Your Measurements</h4>
                  <p>Input your height and weight using either metric (kg/cm) or imperial (lbs/ft/in) units. Our calculator supports both measurement systems.</p>
                </div>
                <div>
                  <h4 className="font-semibold mb-2">Step 2: Add Personal Details</h4>
                  <p>Provide your age, gender, and activity level for more accurate body fat and calorie calculations.</p>
                </div>
                <div>
                  <h4 className="font-semibold mb-2">Step 3: Get Your Results</h4>
                  <p>Instantly receive your BMI score, body fat percentage, daily calorie needs, and personalized health recommendations.</p>
                </div>
              </CardContent>
            </Card>

            {/* Disclaimer */}
            <Alert className="bg-yellow-50 border-yellow-200">
              <AlertTriangle className="h-4 w-4 text-yellow-600" />
              <AlertDescription className="text-yellow-800">
                <strong>Disclaimer:</strong> This BMI calculator is for informational purposes only and should not replace professional medical advice. Always consult with healthcare providers for medical concerns.
              </AlertDescription>
            </Alert>
          </div>
        </div>
        
        {/* SEO Content Section */}
        <div className="mt-16 bg-gradient-to-r from-blue-50 to-green-50 rounded-2xl p-8">
          <h2 className="text-3xl font-bold text-center text-slate-900 mb-8">Complete Health Assessment & Weight Management Guide</h2>
          
          {/* Key Features */}
          <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div className="text-center">
              <div className="bg-blue-100 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-3">
                <Calculator className="w-8 h-8 text-blue-600" />
              </div>
              <h3 className="font-semibold text-slate-800 mb-2">BMI Calculator</h3>
              <p className="text-sm text-slate-600">Instant body mass index calculation with WHO standards</p>
            </div>
            <div className="text-center">
              <div className="bg-green-100 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-3">
                <Target className="w-8 h-8 text-green-600" />
              </div>
              <h3 className="font-semibold text-slate-800 mb-2">Weight Loss Goals</h3>
              <p className="text-sm text-slate-600">Calculate calories needed for healthy weight loss</p>
            </div>
            <div className="text-center">
              <div className="bg-purple-100 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-3">
                <User className="w-8 h-8 text-purple-600" />
              </div>
              <h3 className="font-semibold text-slate-800 mb-2">Body Fat Analysis</h3>
              <p className="text-sm text-slate-600">Estimate body fat percentage for better health insights</p>
            </div>
            <div className="text-center">
              <div className="bg-orange-100 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-3">
                <TrendingUp className="w-8 h-8 text-orange-600" />
              </div>
              <h3 className="font-semibold text-slate-800 mb-2">Health Tracking</h3>
              <p className="text-sm text-slate-600">Monitor progress toward your ideal weight range</p>
            </div>
          </div>
          
          {/* Health Tips */}
          <div className="bg-white rounded-xl p-6 shadow-sm">
            <h3 className="text-2xl font-bold text-slate-900 mb-6 text-center">Expert Tips for Healthy Weight Management</h3>
            <div className="grid md:grid-cols-3 gap-6">
              <div>
                <h4 className="font-semibold text-slate-800 mb-3 flex items-center gap-2">
                  <Apple className="w-5 h-5 text-red-500" />
                  Nutrition for Weight Loss
                </h4>
                <ul className="space-y-2 text-sm text-slate-600">
                  <li>• Create a moderate calorie deficit (300-500 calories daily)</li>
                  <li>• Focus on whole foods: lean proteins, vegetables, fruits</li>
                  <li>• Control portion sizes using the plate method</li>
                  <li>• Stay hydrated with 8-10 glasses of water daily</li>
                  <li>• Avoid processed foods and sugary drinks</li>
                </ul>
              </div>
              <div>
                <h4 className="font-semibold text-slate-800 mb-3 flex items-center gap-2">
                  <Dumbbell className="w-5 h-5 text-blue-500" />
                  Exercise for Optimal BMI
                </h4>
                <ul className="space-y-2 text-sm text-slate-600">
                  <li>• Combine cardio and strength training 4-5x weekly</li>
                  <li>• Aim for 150 minutes moderate aerobic activity</li>
                  <li>• Include resistance training 2-3x per week</li>
                  <li>• Start with walking 30 minutes daily</li>
                  <li>• Gradually increase intensity and duration</li>
                </ul>
              </div>
              <div>
                <h4 className="font-semibold text-slate-800 mb-3 flex items-center gap-2">
                  <Heart className="w-5 h-5 text-green-500" />
                  Lifestyle for Health
                </h4>
                <ul className="space-y-2 text-sm text-slate-600">
                  <li>• Get 7-9 hours of quality sleep nightly</li>
                  <li>• Manage stress through meditation or yoga</li>
                  <li>• Track progress with regular BMI checks</li>
                  <li>• Set realistic, achievable weight goals</li>
                  <li>• Consult healthcare professionals when needed</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </main>


      {/* SEO Footer Content */}
      <section className="bg-white border-t border-slate-200 py-12">
        <div className="max-w-4xl mx-auto px-4">
          <div className="grid md:grid-cols-3 gap-8 mb-8">
            <div>
              <h3 className="font-semibold text-slate-800 mb-4">BMI Calculator Features</h3>
              <ul className="space-y-2 text-sm text-slate-600">
                <li>• Free BMI calculation</li>
                <li>• Body fat percentage estimation</li>
                <li>• Daily calorie needs calculator</li>
                <li>• Ideal weight range</li>
                <li>• Personalized recommendations</li>
                <li>• Metric and imperial units</li>
              </ul>
            </div>
            <div>
              <h3 className="font-semibold text-slate-800 mb-4">Health Resources</h3>
              <ul className="space-y-2 text-sm text-slate-600">
                <li>• Understanding BMI categories</li>
                <li>• Weight management tips</li>
                <li>• Nutrition guidelines</li>
                <li>• Exercise recommendations</li>
                <li>• Age-adjusted BMI analysis</li>
                <li>• Body composition insights</li>
              </ul>
            </div>
            <div>
              <h3 className="font-semibold text-slate-800 mb-4">About Our Calculator</h3>
              <p className="text-sm text-slate-600 mb-4">
                Our comprehensive BMI calculator provides accurate health assessments using scientifically proven formulas. 
                Calculate your body mass index, estimate body fat percentage, and determine daily calorie needs.
              </p>
              <p className="text-sm text-slate-600">
                Perfect for fitness tracking, weight management, and maintaining a healthy lifestyle.
              </p>
            </div>
          </div>
          
        </div>
      </section>

      {/* Footer */}
      <footer className="bg-slate-800 text-white py-8">
        <div className="max-w-4xl mx-auto px-4">
          <div className="text-center">
            <h2 className="text-2xl font-bold mb-4">Free BMI Calculator & Health Tools</h2>
            <p className="text-slate-300 mb-4">
              Calculate BMI, body fat percentage, and daily calorie needs. Get personalized health recommendations 
              based on your measurements, age, and activity level. Free, accurate, and easy to use.
            </p>
            <p className="text-slate-400 text-sm">
              &copy; 2024 BMI Health Calculator. Promoting healthy living through awareness and education.
            </p>
          </div>
        </div>
      </footer>
    </div>
  );
}
