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 = { 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(null); const [category, setCategory] = useState(null); const [bodyFat, setBodyFat] = useState(null); const [dailyCalories, setDailyCalories] = useState(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 (
{/* Hero Section */}

Free BMI Calculator Online

Calculate your Body Mass Index, ideal weight, body fat percentage & daily calories for weight loss - Get instant, personalized health recommendations

✓ Instant Results ✓ No Signup Required ✓ 100% Free ✓ Medically Accurate
{/* Left Sidebar - SEO Content */}
{/* SEO Content Section */} Free BMI Calculator Online

Our free BMI calculator online provides instant, accurate body mass index calculations with comprehensive health analysis. Calculate BMI, body fat percentage, and daily calorie needs in seconds.

Get your ideal weight range and personalized health recommendations for weight loss, fitness goals, and optimal wellness based on age, gender, and activity level.

Perfect for weight management, fitness tracking, and health monitoring. Trusted by thousands daily for accurate health assessment and weight loss planning. Learn more about our mission.

📊 Popular Searches: "BMI calculator for weight loss", "healthy BMI range", "ideal weight calculator", "body fat percentage"

Weight Loss Calculator

Calculate calories for weight loss with our advanced calculator that determines your daily caloric needs based on your BMI and fitness goals.

Track your progress toward healthy weight goals with personalized diet and exercise recommendations for sustainable weight management.

{/* Calculator Section */}
{/* Unit Toggle */} Free BMI Calculator - Calculate Your Body Mass Index {/* Weight Input */}
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" />
{/* Height Input(s) */}
{heightUnit === "ft" ? (
setFeet(e.target.value)} placeholder="Feet" min="1" max="10" step="1" data-testid="input-feet" /> setInches(e.target.value)} placeholder="Inches" min="0" max="11" step="1" data-testid="input-inches" />
) : ( setHeight(e.target.value)} placeholder="Enter height in centimeters" min="50" max="300" step="0.1" data-testid="input-height" /> )}
{/* Age and Gender */}
setAge(e.target.value)} placeholder="Enter age" min="1" max="120" data-testid="input-age" />
{/* Activity Level and Goal */}
{/* Body Measurements for Body Fat */}
Body Measurements (Optional - for body fat estimation)
setWaist(e.target.value)} placeholder="Centimeters" min="1" step="0.1" data-testid="input-waist" />
setNeck(e.target.value)} placeholder="Centimeters" min="1" step="0.1" data-testid="input-neck" />
{gender === "female" && (
setHip(e.target.value)} placeholder="Centimeters" min="1" step="0.1" data-testid="input-hip" />
)}
{/* Error Message */} {error && ( {error} )}
{/* Results Section */} {bmi && category && ( Your Results {/* BMI Value */}
{bmi.toFixed(1)}
Your BMI
{/* BMI Progress Bar */}
Underweight Normal Overweight Obese
18.5 25 30 35+
{/* Category and Message */}
{category.name}
{category.message}
)} {/* Additional Health Metrics */} {bmi && (bodyFat || dailyCalories || idealWeightRange) && ( Additional Health Metrics
{/* Body Fat Percentage */} {bodyFat && (
{bodyFat.toFixed(1)}%
Body Fat
{bodyFat < 10 ? "Very Low" : bodyFat < 15 ? "Low" : bodyFat < 20 ? "Normal" : bodyFat < 25 ? "Moderate" : "High"}
)} {/* Daily Calorie Needs */} {dailyCalories && (
{dailyCalories.toLocaleString()}
Daily Calories
To {goal === "lose" ? "lose weight" : goal === "gain" ? "gain weight" : "maintain weight"}
)} {/* Ideal Weight Range */} {idealWeightRange && (
{idealWeightRange.min.toFixed(0)} - {idealWeightRange.max.toFixed(0)}
Ideal Range ({weightUnit})
{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"}
)}
{/* Enhanced BMI Interpretation */} {age && (

Age-Adjusted Analysis

{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." }

)}
)} {/* Personalized Recommendations */} {bmi && category && ( Personalized Recommendations {/* Sports & Exercise */}

Sports & Exercise

    {category.recommendations.sports.map((sport, index) => (
  • {sport}
  • ))}
{/* Nutrition */}

Nutrition Guidelines

    {category.recommendations.nutrition.map((nutrition, index) => (
  • {nutrition}
  • ))}
{/* Lifestyle */}

Lifestyle Tips

    {category.recommendations.lifestyle.map((lifestyle, index) => (
  • {lifestyle}
  • ))}
)}
{/* Information Section */}
{/* BMI Categories */} Understanding BMI Categories {Object.entries(bmiCategories).map(([key, cat]) => (
{cat.name}
{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'}
))}
{/* Health Tips */} Healthy Weight Management Tips {[ "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) => (
{tip}
))}
{/* SEO Content Section */} How to Use This BMI Calculator

Step 1: Enter Your Measurements

Input your height and weight using either metric (kg/cm) or imperial (lbs/ft/in) units. Our calculator supports both measurement systems.

Step 2: Add Personal Details

Provide your age, gender, and activity level for more accurate body fat and calorie calculations.

Step 3: Get Your Results

Instantly receive your BMI score, body fat percentage, daily calorie needs, and personalized health recommendations.

{/* Disclaimer */} Disclaimer: This BMI calculator is for informational purposes only and should not replace professional medical advice. Always consult with healthcare providers for medical concerns.
{/* SEO Content Section */}

Complete Health Assessment & Weight Management Guide

{/* Key Features */}

BMI Calculator

Instant body mass index calculation with WHO standards

Weight Loss Goals

Calculate calories needed for healthy weight loss

Body Fat Analysis

Estimate body fat percentage for better health insights

Health Tracking

Monitor progress toward your ideal weight range

{/* Health Tips */}

Expert Tips for Healthy Weight Management

Nutrition for Weight Loss

  • • Create a moderate calorie deficit (300-500 calories daily)
  • • Focus on whole foods: lean proteins, vegetables, fruits
  • • Control portion sizes using the plate method
  • • Stay hydrated with 8-10 glasses of water daily
  • • Avoid processed foods and sugary drinks

Exercise for Optimal BMI

  • • Combine cardio and strength training 4-5x weekly
  • • Aim for 150 minutes moderate aerobic activity
  • • Include resistance training 2-3x per week
  • • Start with walking 30 minutes daily
  • • Gradually increase intensity and duration

Lifestyle for Health

  • • Get 7-9 hours of quality sleep nightly
  • • Manage stress through meditation or yoga
  • • Track progress with regular BMI checks
  • • Set realistic, achievable weight goals
  • • Consult healthcare professionals when needed
{/* SEO Footer Content */}

BMI Calculator Features

  • • Free BMI calculation
  • • Body fat percentage estimation
  • • Daily calorie needs calculator
  • • Ideal weight range
  • • Personalized recommendations
  • • Metric and imperial units

Health Resources

  • • Understanding BMI categories
  • • Weight management tips
  • • Nutrition guidelines
  • • Exercise recommendations
  • • Age-adjusted BMI analysis
  • • Body composition insights

About Our Calculator

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.

Perfect for fitness tracking, weight management, and maintaining a healthy lifestyle.

{/* Footer */}
); }