'use client';

import { useState, useMemo, useRef, useCallback } from 'react';
import { useAppStore } from '@/lib/store';
import { t } from '@/lib/i18n';
import { mockProducts } from '@/lib/mock-data';

import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';

import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetDescription,
} from '@/components/ui/sheet';
import { useToast } from '@/hooks/use-toast';
import {
  Search,
  Pill,
  Upload,
  MapPin,
  Heart,
  Star,
  Plus,
  ShoppingCart,
  Check,
  FileText,
  AlertTriangle,
  Navigation,
  Clock,
  Phone,
  X,
  ArrowLeft,
  ChevronRight,
  Share2,
  Bookmark,
  ExternalLink,
  Info,
  ShieldCheck,
  Truck,
  MessageCircle,
  RotateCcw,
  Trash2,
  Minus,
} from 'lucide-react';

const mockPharmacies = [
  {
    id: 'ph1',
    name: 'HealthPlus Pharmacy',
    address: 'Road 27, Dhanmondi, Dhaka',
    distance: '0.5 km',
    rating: 4.8,
    reviewCount: 120,
    isOpen: true,
    phone: '+8801712345678',
    hours: '8:00 AM - 11:00 PM',
    services: ['Prescription', 'Delivery', '24/7 Emergency'],
    lat: 23.7461,
    lng: 90.3742,
  },
  {
    id: 'ph2',
    name: 'Lazz Pharma',
    address: 'Mirpur 10, Dhaka',
    distance: '1.2 km',
    rating: 4.6,
    reviewCount: 89,
    isOpen: true,
    phone: '+8801798765432',
    hours: '9:00 AM - 10:00 PM',
    services: ['Prescription', 'Delivery', 'Surgical'],
    lat: 23.8041,
    lng: 90.3692,
  },
  {
    id: 'ph3',
    name: 'Square Pharmacy',
    address: 'Gulshan 2, Dhaka',
    distance: '2.1 km',
    rating: 4.5,
    reviewCount: 56,
    isOpen: false,
    phone: '+8801555123456',
    hours: '10:00 AM - 9:00 PM',
    services: ['Prescription', 'Cosmetics'],
    lat: 23.7935,
    lng: 90.4066,
  },
  {
    id: 'ph4',
    name: 'Popular Diagnostic Pharmacy',
    address: 'Uttara Sector 7, Dhaka',
    distance: '3.4 km',
    rating: 4.7,
    reviewCount: 73,
    isOpen: true,
    phone: '+8801612345678',
    hours: '8:00 AM - 12:00 AM',
    services: ['Prescription', 'Delivery', 'Pathology', '24/7 Emergency'],
    lat: 23.8736,
    lng: 90.3969,
  },
];

const healthTips = [
  {
    id: 'ht1',
    title: 'Stay Hydrated',
    titleBn: 'পানি পান করুন',
    description: 'Drink at least 8 glasses of water daily for better health.',
    descriptionBn: 'সুস্বাস্থ্যের জন্য প্রতিদিন কমপক্ষে ৮ গ্লাস পানি পান করুন।',
    icon: '💧',
    color: 'bg-orange-100 dark:bg-orange-900/30',
    details: [
      'Start your day with a glass of warm water',
      'Carry a water bottle everywhere you go',
      'Set reminders to drink water every hour',
      'Eat water-rich fruits like watermelon, cucumber',
      'Avoid excessive caffeine and sugary drinks',
    ],
    detailsBn: [
      'দিন শুরু করুন এক গ্লাস কুসুম গরম পানি দিয়ে',
      'সব জায়গায় পানির বোতল সাথে রাখুন',
      'প্রতি ঘণ্টায় পানি পানের রিমাইন্ডার সেট করুন',
      'তরমুজ, শসা জাতীয় ফল খান',
      'অতিরিক্ত ক্যাফেইন ও মিষ্টি পানীয় এড়িয়ে চলুন',
    ],
  },
  {
    id: 'ht2',
    title: 'Regular Exercise',
    titleBn: 'নিয়মিত ব্যায়াম',
    description: '30 minutes of daily exercise can improve your overall health.',
    descriptionBn: 'প্রতিদিন ৩০ মিনিট ব্যায়াম আপনার সামগ্রিক স্বাস্থ্য উন্নত করতে পারে।',
    icon: '🏃',
    color: 'bg-green-100 dark:bg-green-900/30',
    details: [
      'Walk at least 30 minutes daily',
      'Do stretching exercises every morning',
      'Take stairs instead of elevators',
      'Join a fitness class or sports group',
      'Take breaks from sitting every 30 minutes',
    ],
    detailsBn: [
      'প্রতিদিন কমপক্ষে ৩০ মিনিট হাঁটুন',
      'প্রতি সকালে স্ট্রেচিং ব্যায়াম করুন',
      'লিফটের বদলে সিঁড়ি ব্যবহার করুন',
      'ফিটনেস ক্লাস বা স্পোর্টস গ্রুপে যোগ দিন',
      'প্রতি ৩০ মিনিটে বসা থেকে বিরতি নিন',
    ],
  },
  {
    id: 'ht3',
    title: 'Proper Sleep',
    titleBn: 'পর্যাপ্ত ঘুম',
    description: 'Get 7-8 hours of quality sleep every night.',
    descriptionBn: 'প্রতি রাতে ৭-৮ ঘণ্টা মানসম্মত ঘুম নিন।',
    icon: '😴',
    color: 'bg-amber-100 dark:bg-amber-900/30',
    details: [
      'Maintain a consistent sleep schedule',
      'Avoid screens 1 hour before bed',
      'Keep your bedroom cool and dark',
      'Avoid heavy meals before sleeping',
      'Practice relaxation techniques before bed',
    ],
    detailsBn: [
      'নিয়মিত ঘুমের সময়সূচী মেনে চলুন',
      'ঘুমানোর ১ ঘণ্টা আগে স্ক্রিন এড়িয়ে চলুন',
      'বেডরুম ঠান্ডা ও অন্ধকার রাখুন',
      'ঘুমানোর আগে ভারী খাবার এড়িয়ে চলুন',
      'ঘুমানোর আগে রিল্যাক্সেশন টেকনিক অনুশীলন করুন',
    ],
  },
  {
    id: 'ht4',
    title: 'Balanced Diet',
    titleBn: 'সুষম খাদ্য',
    description: 'Include fruits, vegetables, and protein in every meal.',
    descriptionBn: 'প্রতি খাবারে ফল, শাকসবজি ও প্রোটিন রাখুন।',
    icon: '🥗',
    color: 'bg-orange-100 dark:bg-orange-900/30',
    details: [
      'Eat 5 servings of fruits and vegetables daily',
      'Include protein in every meal',
      'Limit processed and fast food',
      'Choose whole grains over refined grains',
      'Control portion sizes and eat mindfully',
    ],
    detailsBn: [
      'প্রতিদিন ৫ পরিবেশন ফল ও শাকসবজি খান',
      'প্রতি খাবারে প্রোটিন রাখুন',
      'প্রক্রিয়াজাত ও ফাস্ট ফুড সীমিত করুন',
      'পরিশোধিত শস্যের বদলে সম্পূর্ণ শস্য বেছে নিন',
      'পরিমাণ নিয়ন্ত্রণ করুন এবং মনোযোগ দিয়ে খান',
    ],
  },
  {
    id: 'ht5',
    title: 'Mental Wellness',
    titleBn: 'মানসিক সুস্থতা',
    description: 'Take care of your mental health with mindfulness and rest.',
    descriptionBn: 'মাইন্ডফুলনেস ও বিশ্রামের মাধ্যমে মানসিক স্বাস্থ্যের যত্ন নিন।',
    icon: '🧘',
    color: 'bg-orange-100 dark:bg-orange-900/30',
    details: [
      'Practice meditation for 10 minutes daily',
      'Connect with friends and family regularly',
      'Take breaks when you feel overwhelmed',
      'Seek professional help when needed',
      'Engage in hobbies and activities you enjoy',
    ],
    detailsBn: [
      'প্রতিদিন ১০ মিনিট ধ্যান অনুশীলন করুন',
      'নিয়মিত বন্ধু ও পরিবারের সাথে যোগাযোগ রাখুন',
      'চাপ অনুভব করলে বিরতি নিন',
      'প্রয়োজনে পেশাদার সাহায্য নিন',
      'আপনার পছন্দের শখ ও কাজে নিযুক্ত থাকুন',
    ],
  },
  {
    id: 'ht6',
    title: 'Regular Check-ups',
    titleBn: 'নিয়মিত স্বাস্থ্য পরীক্ষা',
    description: 'Visit your doctor for regular health screenings.',
    descriptionBn: 'নিয়মিত স্বাস্থ্য পরীক্ষার জন্য ডাক্তার দেখান।',
    icon: '🩺',
    color: 'bg-rose-100 dark:bg-rose-900/30',
    details: [
      'Get an annual health check-up',
      'Monitor blood pressure regularly',
      'Check blood sugar levels periodically',
      'Don\'t ignore persistent symptoms',
      'Keep vaccination records up to date',
    ],
    detailsBn: [
      'বার্ষিক স্বাস্থ্য পরীক্ষা করান',
      'রক্তচাপ নিয়মিত পরীক্ষা করুন',
      'রক্তে শর্করার মাত্রা মাঝে মাঝে পরীক্ষা করুন',
      'দীর্ঘস্থায়ী লক্ষণ উপেক্ষা করবেন না',
      'টিকাদানের রেকর্ড আপডেট রাখুন',
    ],
  },
];



export default function MedicineModule() {
  const { language, addToCart, removeFromCart, cart, setCurrentSection, setOpenChatWith } = useAppStore();
  const { toast } = useToast();

  const [searchQuery, setSearchQuery] = useState('');
  const [prescriptionFiles, setPrescriptionFiles] = useState<File[]>([]);
  const [prescriptionUploaded, setPrescriptionUploaded] = useState(false);
  const [isDragOver, setIsDragOver] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [addedToCart, setAddedToCart] = useState<Set<string>>(new Set());
  const [selectedTipId, setSelectedTipId] = useState<string | null>(null);
  const [savedTips, setSavedTips] = useState<Set<string>>(new Set());
  const [selectedPharmacyId, setSelectedPharmacyId] = useState<string | null>(null);
  const [cartOpen, setCartOpen] = useState(false);
  const [nearbyDistance, setNearbyDistance] = useState<string>('all');
  const fileInputRef = useRef<HTMLInputElement>(null);

  const hasActiveLocationFilters = nearbyDistance !== 'all';
  const resetLocationFilters = () => setNearbyDistance('all');

  // Refs for scrolling to sections
  const orderSectionRef = useRef<HTMLDivElement>(null);
  const prescriptionSectionRef = useRef<HTMLDivElement>(null);
  const pharmacySectionRef = useRef<HTMLDivElement>(null);
  const tipsSectionRef = useRef<HTMLDivElement>(null);

  // Medicine products from mock data
  const medicineProducts = useMemo(() => {
    return mockProducts.filter((p) => p.category === 'medicine');
  }, []);

  // Filter medicines by search
  const filteredMedicines = useMemo(() => {
    if (!searchQuery) return medicineProducts;
    return medicineProducts.filter(
      (p) =>
        p.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
        p.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
        p.subcategory.toLowerCase().includes(searchQuery.toLowerCase())
    );
  }, [medicineProducts, searchQuery]);

  // Filter pharmacies by distance
  const filteredPharmacies = useMemo(() => {
    if (nearbyDistance === 'all') return mockPharmacies;
    const maxDist = parseFloat(nearbyDistance);
    return mockPharmacies.filter((pharmacy) => {
      const dist = parseFloat(pharmacy.distance);
      return !isNaN(dist) && dist <= maxDist;
    });
  }, [nearbyDistance]);

  const nearbyOptions = [
    { key: 'all', label: language === 'bn' ? 'সব' : 'All', labelBn: 'সব' },
    { key: '1', label: language === 'bn' ? '১ কি.মি. এর মধ্যে' : 'Within 1 km', labelBn: '১ কি.মি. এর মধ্যে' },
    { key: '3', label: language === 'bn' ? '৩ কি.মি. এর মধ্যে' : 'Within 3 km', labelBn: '৩ কি.মি. এর মধ্যে' },
    { key: '5', label: language === 'bn' ? '৫ কি.মি. এর মধ্যে' : 'Within 5 km', labelBn: '৫ কি.মি. এর মধ্যে' },
    { key: '10', label: language === 'bn' ? '১০ কি.মি. এর মধ্যে' : 'Within 10 km', labelBn: '১০ কি.মি. এর মধ্যে' },
  ];

  const scrollToSection = useCallback((ref: React.RefObject<HTMLDivElement | null>) => {
    ref.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }, []);

  const handleFileSelect = (file: File) => {
    const validTypes = ['image/jpeg', 'image/png', 'image/jpg', 'application/pdf'];
    if (validTypes.includes(file.type)) {
      setPrescriptionFiles((prev) => [...prev, file]);
      setPrescriptionUploaded(false);
    } else {
      toast({
        title: language === 'en' ? 'Invalid File Type' : 'ভুল ফাইলের ধরন',
        description: language === 'en' ? 'Please upload JPG, PNG, or PDF files only' : 'শুধুমাত্র JPG, PNG বা PDF ফাইল আপলোড করুন',
        variant: 'destructive',
      });
    }
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(true);
  };

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);
    const files = Array.from(e.dataTransfer.files);
    files.forEach((file) => handleFileSelect(file));
  };

  const handleFileInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files ? Array.from(e.target.files) : [];
    files.forEach((file) => handleFileSelect(file));
    // Reset input value so the same file(s) can be selected again
    e.target.value = '';
  };

  const handleUploadPrescription = async () => {
    if (prescriptionFiles.length === 0) return;
    setIsUploading(true);
    // Simulate upload
    await new Promise((resolve) => setTimeout(resolve, 1500));
    setIsUploading(false);
    setPrescriptionUploaded(true);
    setPrescriptionFiles([]);
    toast({
      title: language === 'en' ? 'Prescription Uploaded!' : 'প্রেসক্রিপশন আপলোড হয়েছে!',
      description: language === 'en'
        ? `${prescriptionFiles.length} file(s) uploaded. Our pharmacist will verify and prepare your order shortly.`
        : `${prescriptionFiles.length}টি ফাইল আপলোড হয়েছে। আমাদের ফার্মাসিস্ট শীঘ্রই যাচাই করে আপনার অর্ডার প্রস্তুত করবেন।`,
      duration: 4000,
    });
  };

  const handleOrderMedicine = (product: typeof medicineProducts[0]) => {
    const discountedPrice = product.discount > 0
      ? Math.round(product.price * (1 - product.discount / 100))
      : product.price;
    addToCart({
      productId: product.id,
      title: product.title,
      price: discountedPrice,
      quantity: 1,
      image: product.images[0],
      unit: product.unit,
    });
    setAddedToCart((prev) => new Set(prev).add(product.id));
    toast({
      title: language === 'en' ? 'Added to Cart' : 'কার্টে যোগ হয়েছে',
      description: `${product.title} — ৳${discountedPrice}`,
      duration: 2000,
    });
    setTimeout(() => {
      setAddedToCart((prev) => {
        const next = new Set(prev);
        next.delete(product.id);
        return next;
      });
    }, 1500);
  };

  const handleCall = (phone: string, pharmacyName: string) => {
    window.open(`tel:${phone}`, '_self');
    toast({
      title: language === 'en' ? `Calling ${pharmacyName}` : `${pharmacyName}-এ কল হচ্ছে`,
      description: phone,
      duration: 3000,
    });
  };

  const handleGetDirections = (pharmacy: typeof mockPharmacies[0]) => {
    const url = `https://www.google.com/maps/dir/?api=1&destination=${pharmacy.lat},${pharmacy.lng}&travelmode=driving`;
    window.open(url, '_blank');
    toast({
      title: language === 'en' ? 'Opening Maps' : 'ম্যাপ খুলছে',
      description: language === 'en'
        ? `Getting directions to ${pharmacy.name}`
        : `${pharmacy.name}-এর দিকনির্দেশ দেখা হচ্ছে`,
      duration: 2000,
    });
  };

  const handlePharmacyMessage = (pharmacy: typeof mockPharmacies[0]) => {
    setSelectedPharmacyId(null);
    setOpenChatWith({
      id: `pharmacy-${pharmacy.id}`,
      name: pharmacy.name,
      listingTitle: language === 'en' ? 'Pharmacy Inquiry' : 'ফার্মেসি সংক্রান্ত জিজ্ঞাসা',
    });
    setCurrentSection('messages');
  };

  const toggleSaveTip = (tipId: string, e?: React.MouseEvent) => {
    e?.stopPropagation();
    setSavedTips((prev) => {
      const next = new Set(prev);
      if (next.has(tipId)) {
        next.delete(tipId);
        toast({
          title: language === 'en' ? 'Tip Removed' : 'টিপস সরানো হয়েছে',
          duration: 1500,
        });
      } else {
        next.add(tipId);
        toast({
          title: language === 'en' ? 'Tip Saved!' : 'টিপস সংরক্ষিত!',
          duration: 1500,
        });
      }
      return next;
    });
  };

  const selectedTip = healthTips.find((tip) => tip.id === selectedTipId);
  const selectedPharmacy = mockPharmacies.find((p) => p.id === selectedPharmacyId);

  const renderStars = (rating: number) => {
    const full = Math.floor(rating);
    const half = rating % 1 >= 0.5;
    const stars = [];
    for (let i = 0; i < 5; i++) {
      if (i < full) {
        stars.push(<Star key={i} className="h-3 w-3 fill-amber-400 text-amber-400" />);
      } else if (i === full && half) {
        stars.push(<Star key={i} className="h-3 w-3 fill-amber-400/50 text-amber-400" />);
      } else {
        stars.push(<Star key={i} className="h-3 w-3 text-muted-foreground/30" />);
      }
    }
    return stars;
  };

  return (
    <div className="flex flex-col gap-5 px-4 py-4 pb-24">
      {/* Header */}
      <div className="flex items-center gap-3">
        <Button variant="ghost" size="icon" onClick={() => setCurrentSection('home')} className="shrink-0">
          <ArrowLeft className="h-5 w-5" />
        </Button>
        <div>
          <h1 className="text-xl font-bold text-foreground">
            {t('medicine.title', language)}
          </h1>
          <p className="text-xs text-muted-foreground">
            {language === 'en' ? 'Order medicines & health products' : 'ওষুধ ও স্বাস্থ্য পণ্য অর্ডার করুন'}
          </p>
        </div>
      </div>

      {/* Search Bar */}
      <div className="flex items-center gap-2">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder={t('medicine.search', language)}
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-9 pr-9 h-10 rounded-xl border-primary/10 bg-card focus:border-primary/30"
          />
          {searchQuery && (
            <button
              onClick={() => setSearchQuery('')}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
            >
              <X className="h-4 w-4" />
            </button>
          )}
        </div>

      </div>

      {/* Quick Action Cards */}
      <div className="grid grid-cols-2 gap-3">
        {/* Order Medicine */}
        <Card
          className="cursor-pointer border-0 bg-gradient-to-br from-primary to-primary/80 text-primary-foreground transition-all duration-200 hover:shadow-lg hover:shadow-primary/20 active:scale-[0.97]"
          onClick={() => scrollToSection(orderSectionRef)}
        >
          <CardContent className="flex flex-col items-center gap-2 p-4 text-center">
            <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-white/20">
              <Pill className="h-6 w-6" />
            </div>
            <div>
              <p className="text-sm font-bold">{t('medicine.orderMedicine', language)}</p>
              <p className="text-[10px] text-primary-foreground/70">
                {language === 'en' ? 'Browse & order' : 'ব্রাউজ ও অর্ডার'}
              </p>
            </div>
          </CardContent>
        </Card>

        {/* Upload Prescription */}
        <Card
          className="cursor-pointer border border-border bg-card transition-all duration-200 hover:border-primary/20 hover:shadow-md active:scale-[0.97] relative overflow-hidden"
          onClick={() => {
            scrollToSection(prescriptionSectionRef);
            setTimeout(() => fileInputRef.current?.click(), 300);
          }}
        >
          <CardContent className="flex flex-col items-center gap-2 p-4 text-center">
            <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-orange-100 dark:bg-orange-900/30 relative">
              <Upload className="h-6 w-6 text-orange-600 dark:text-orange-400" />
              <span className="absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full bg-primary text-primary-foreground">
                <Plus className="h-3 w-3" />
              </span>
            </div>
            <div>
              <p className="text-sm font-bold text-foreground">{t('medicine.uploadPrescription', language)}</p>
              <p className="text-[10px] text-muted-foreground">
                {language === 'en' ? 'Tap to upload' : 'ট্যাপ করে আপলোড'}
              </p>
            </div>
            <span className="mt-0.5 animate-pulse rounded-full bg-primary/10 px-2 py-0.5 text-[9px] font-semibold text-primary">
              {language === 'en' ? 'Tap to upload' : 'আপলোড করুন'}
            </span>
          </CardContent>
        </Card>

        {/* Nearby Pharmacy */}
        <Card
          className="cursor-pointer border border-border bg-card transition-all duration-200 hover:border-primary/20 hover:shadow-md active:scale-[0.97]"
          onClick={() => scrollToSection(pharmacySectionRef)}
        >
          <CardContent className="flex flex-col items-center gap-2 p-4 text-center">
            <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-green-100 dark:bg-green-900/30">
              <MapPin className="h-6 w-6 text-green-600 dark:text-green-400" />
            </div>
            <div>
              <p className="text-sm font-bold text-foreground">{t('medicine.nearbyPharmacy', language)}</p>
              <p className="text-[10px] text-muted-foreground">
                {language === 'en' ? 'Find nearby' : 'কাছাকাছি খুঁজুন'}
              </p>
            </div>
          </CardContent>
        </Card>

        {/* Health Tips */}
        <Card
          className="cursor-pointer border border-border bg-card transition-all duration-200 hover:border-primary/20 hover:shadow-md active:scale-[0.97]"
          onClick={() => scrollToSection(tipsSectionRef)}
        >
          <CardContent className="flex flex-col items-center gap-2 p-4 text-center">
            <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-red-100 dark:bg-red-900/30">
              <Heart className="h-6 w-6 text-red-500 dark:text-red-400" />
            </div>
            <div>
              <p className="text-sm font-bold text-foreground">
                {language === 'en' ? 'Health Tips' : 'স্বাস্থ্য পরামর্শ'}
              </p>
              <p className="text-[10px] text-muted-foreground">
                {language === 'en' ? 'Stay healthy' : 'সুস্থ থাকুন'}
              </p>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* ─── Popular Medicines Section ─── */}
      <section ref={orderSectionRef}>
        <div className="flex items-center justify-between">
          <h2 className="text-base font-bold text-foreground">
            {language === 'en' ? 'Popular Medicines' : 'জনপ্রিয় ওষুধ'}
          </h2>
          {addedToCart.size > 0 && (
            <Button
              variant="ghost"
              size="sm"
              className="gap-1 text-xs text-primary"
              onClick={() => setCurrentSection('checkout')}
            >
              <ShoppingCart className="h-3.5 w-3.5" />
              {language === 'en' ? 'View Cart' : 'কার্ট দেখুন'}
            </Button>
          )}
        </div>

        <div className="mt-3 grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
          {filteredMedicines.length === 0 ? (
            <div className="col-span-full flex items-center justify-center py-8">
              <p className="text-sm text-muted-foreground">{t('common.noResults', language)}</p>
            </div>
          ) : (
            filteredMedicines.map((medicine) => {
              const discountedPrice = medicine.discount > 0
                ? Math.round(medicine.price * (1 - medicine.discount / 100))
                : medicine.price;

              return (
                <Card
                  key={medicine.id}
                  className="group border-border/50 bg-card py-0 transition-all duration-200 hover:border-primary/20 hover:shadow-lg hover:-translate-y-0.5"
                >
                  {/* Image Area */}
                  <div className="relative h-32 overflow-hidden bg-gradient-to-br from-red-400 to-rose-500">
                    {medicine.images && medicine.images.length > 0 ? (
                      <img src={medicine.images[0]} alt={medicine.title} className="h-full w-full object-cover" loading="lazy" />
                    ) : (
                      <div className="flex h-full items-center justify-center">
                        <span className="text-4xl opacity-50">💊</span>
                      </div>
                    )}
                    {medicine.discount > 0 && (
                      <Badge className="absolute left-2 top-2 bg-destructive text-destructive-foreground text-[10px] font-bold px-1.5 py-0">
                        -{medicine.discount}%
                      </Badge>
                    )}
                  </div>
                  <CardContent className="space-y-1.5 p-3">
                    <h3 className="line-clamp-2 text-xs font-semibold leading-tight text-foreground group-hover:text-primary transition-colors">
                      {medicine.title}
                    </h3>

                    <p className="text-[10px] text-muted-foreground">
                      {medicine.subcategory} · {medicine.unit}
                    </p>

                    <div className="flex items-center gap-0.5">
                      {renderStars(medicine.rating)}
                      <span className="text-[9px] text-muted-foreground ml-0.5">
                        ({medicine.reviewCount})
                      </span>
                    </div>

                    <div className="flex items-baseline gap-1">
                      <span className="text-sm font-bold text-primary">৳{discountedPrice}</span>
                      {medicine.discount > 0 && (
                        <span className="text-[10px] text-muted-foreground line-through">
                          ৳{medicine.price}
                        </span>
                      )}
                    </div>

                    <Button
                      size="sm"
                      className={`w-full rounded-lg text-[11px] font-semibold transition-all duration-300 ${
                        addedToCart.has(medicine.id)
                          ? 'bg-green-500 text-white hover:bg-green-600'
                          : 'bg-primary text-primary-foreground hover:bg-primary/90'
                      }`}
                      onClick={() => handleOrderMedicine(medicine)}
                    >
                      {addedToCart.has(medicine.id) ? (
                        <>
                          <Check className="mr-1 h-3 w-3" />
                          {language === 'en' ? 'Added' : 'যোগ হয়েছে'}
                        </>
                      ) : (
                        <>
                          <ShoppingCart className="mr-1 h-3 w-3" />
                          {language === 'en' ? 'Add to Cart' : 'কার্টে যোগ'}
                        </>
                      )}
                    </Button>
                  </CardContent>
                </Card>
              );
            })
          )}
        </div>

        {/* Medicine delivery info banner */}
        <Card className="mt-3 border-primary/10 bg-primary/5">
          <CardContent className="flex items-center gap-3 p-3">
            <Truck className="h-5 w-5 shrink-0 text-primary" />
            <div className="flex-1">
              <p className="text-xs font-semibold text-foreground">
                {language === 'en' ? 'Free delivery on orders ৳500+' : '৳৫০০+ অর্ডারে ফ্রি ডেলিভারি'}
              </p>
              <p className="text-[10px] text-muted-foreground">
                {language === 'en' ? 'Estimated delivery: 30-60 minutes' : 'আনুমানিক ডেলিভারি: ৩০-৬০ মিনিট'}
              </p>
            </div>
          </CardContent>
        </Card>
      </section>

      {/* ─── Upload Prescription Section ─── */}
      <section ref={prescriptionSectionRef}>
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Upload className="h-5 w-5 text-primary" />
            <h2 className="text-base font-bold text-foreground">
              {t('medicine.uploadPrescription', language)}
            </h2>
          </div>
          <Button
            size="icon"
            className="h-8 w-8 rounded-full bg-primary text-primary-foreground hover:bg-primary/90"
            onClick={() => fileInputRef.current?.click()}
          >
            <Plus className="h-4 w-4" />
          </Button>
        </div>

        {prescriptionUploaded ? (
          <Card className="mt-3 border-green-200 bg-green-50 dark:border-green-800 dark:bg-green-900/10">
            <CardContent className="flex flex-col items-center gap-3 p-6 text-center">
              <div className="flex h-14 w-14 items-center justify-center rounded-full bg-green-100 dark:bg-green-900/30">
                <ShieldCheck className="h-7 w-7 text-green-600 dark:text-green-400" />
              </div>
              <div>
                <p className="text-sm font-bold text-green-700 dark:text-green-300">
                  {language === 'en' ? 'Prescription Uploaded Successfully!' : 'প্রেসক্রিপশন সফলভাবে আপলোড হয়েছে!'}
                </p>
                <p className="mt-1 text-xs text-green-600 dark:text-green-400">
                  {language === 'en'
                    ? 'Our pharmacist will verify and contact you within 30 minutes.'
                    : 'আমাদের ফার্মাসিস্ট ৩০ মিনিটের মধ্যে যাচাই করে আপনার সাথে যোগাযোগ করবেন।'}
                </p>
              </div>
              <div className="flex gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  className="text-xs"
                  onClick={() => setPrescriptionUploaded(false)}
                >
                  {language === 'en' ? 'Upload Another' : 'আরেকটি আপলোড করুন'}
                </Button>
              </div>
            </CardContent>
          </Card>
        ) : (
          <Card className="mt-3 border-dashed border-2 border-primary/20 bg-card">
            <CardContent className="p-4">
              <div
                className={`flex flex-col items-center gap-3 rounded-xl border-2 border-dashed p-6 transition-colors cursor-pointer ${
                  isDragOver
                    ? 'border-primary bg-primary/5'
                    : prescriptionFiles.length > 0
                    ? 'border-green-400 bg-green-50 dark:bg-green-900/10'
                    : 'border-muted-foreground/20 hover:border-primary/40 hover:bg-primary/5'
                }`}
                onDragOver={handleDragOver}
                onDragLeave={handleDragLeave}
                onDrop={handleDrop}
                onClick={() => fileInputRef.current?.click()}
              >
                <div className={`flex h-12 w-12 items-center justify-center rounded-2xl ${
                  prescriptionFiles.length > 0 ? 'bg-green-100 dark:bg-green-900/30' : 'bg-primary/10'
                }`}>
                  {prescriptionFiles.length > 0 ? (
                    <FileText className="h-6 w-6 text-green-600 dark:text-green-400" />
                  ) : (
                    <Upload className="h-6 w-6 text-primary" />
                  )}
                </div>

                {prescriptionFiles.length > 0 ? (
                  <div className="w-full space-y-2" onClick={(e) => e.stopPropagation()}>
                    {prescriptionFiles.map((file, index) => (
                      <div key={`${file.name}-${index}`} className="flex items-center gap-2 rounded-lg bg-background/80 p-2">
                        <FileText className="h-4 w-4 shrink-0 text-green-600 dark:text-green-400" />
                        <div className="flex-1 min-w-0">
                          <p className="text-xs font-medium text-foreground truncate">{file.name}</p>
                          <p className="text-[10px] text-muted-foreground">
                            {(file.size / 1024).toFixed(1)} KB
                          </p>
                        </div>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-6 w-6 shrink-0 text-muted-foreground hover:text-destructive"
                          onClick={() => {
                            setPrescriptionFiles((prev) => prev.filter((_, i) => i !== index));
                          }}
                        >
                          <X className="h-3 w-3" />
                        </Button>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center">
                    <p className="text-sm font-medium text-foreground">
                      {language === 'en'
                        ? 'Drag & drop your prescription'
                        : 'আপনার প্রেসক্রিপশন টেনে আনুন'}
                    </p>
                    <p className="text-xs text-muted-foreground">
                      {language === 'en'
                        ? 'or click to browse (JPG, PNG, PDF)'
                        : 'বা ব্রাউজ করতে ক্লিক করুন (JPG, PNG, PDF)'}
                    </p>
                  </div>
                )}

                <div className="flex gap-2" onClick={(e) => e.stopPropagation()}>
                  <Button
                    variant="outline"
                    size="sm"
                    className="border-primary/20 text-primary text-xs"
                    onClick={() => fileInputRef.current?.click()}
                  >
                    {prescriptionFiles.length > 0
                      ? (language === 'en' ? 'Add More Files' : 'আরও ফাইল যোগ করুন')
                      : (language === 'en' ? 'Choose File' : 'ফাইল বেছে নিন')}
                  </Button>
                  {prescriptionFiles.length > 0 && (
                    <Button
                      size="sm"
                      className="bg-primary text-primary-foreground text-xs"
                      disabled={isUploading}
                      onClick={handleUploadPrescription}
                    >
                      {isUploading
                        ? t('common.loading', language)
                        : language === 'en'
                        ? `Upload (${prescriptionFiles.length})`
                        : `আপলোড (${prescriptionFiles.length})`}
                    </Button>
                  )}
                  {prescriptionFiles.length > 0 && (
                    <Button
                      variant="ghost"
                      size="sm"
                      className="text-xs text-muted-foreground hover:text-destructive"
                      onClick={() => setPrescriptionFiles([])}
                    >
                      <Trash2 className="h-3 w-3 mr-1" />
                      {language === 'en' ? 'Clear All' : 'সব সরান'}
                    </Button>
                  )}
                </div>

                <input
                  ref={fileInputRef}
                  type="file"
                  accept=".jpg,.jpeg,.png,.pdf"
                  multiple
                  className="hidden"
                  onChange={handleFileInput}
                />
              </div>

              {/* Warning */}
              <div className="mt-3 flex items-start gap-2 rounded-lg bg-amber-50 p-3 dark:bg-amber-900/10">
                <AlertTriangle className="h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400 mt-0.5" />
                <p className="text-xs text-amber-700 dark:text-amber-300 leading-relaxed">
                  {language === 'en'
                    ? 'Prescription verification required. Our pharmacist will verify your prescription before processing the order.'
                    : 'প্রেসক্রিপশন যাচাই প্রয়োজন। অর্ডার প্রসেস করার আগে আমাদের ফার্মাসিস্ট আপনার প্রেসক্রিপশন যাচাই করবেন।'}
                </p>
              </div>
            </CardContent>
          </Card>
        )}
      </section>

      {/* ─── Nearby Pharmacies ─── */}
      <section ref={pharmacySectionRef}>
        <div className="flex items-center gap-2">
          <MapPin className="h-5 w-5 text-primary" />
          <h2 className="text-base font-bold text-foreground">
            {t('medicine.nearbyPharmacy', language)}
          </h2>
        </div>

        {/* Nearby Distance Filter */}
        <div className="mt-3 space-y-2">
          <div className="flex items-center gap-2">
            <MapPin className="h-4 w-4 text-primary shrink-0" />
            <span className="text-xs font-medium">{language === 'en' ? 'Nearby pharmacy:' : 'কাছাকাছি ফার্মেসি:'}</span>
          </div>
          <div className="flex flex-wrap gap-1.5">
            {nearbyOptions.map((option) => (
              <button
                key={option.key}
                onClick={() => setNearbyDistance(option.key)}
                className={`shrink-0 rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${
                  nearbyDistance === option.key
                    ? 'border-primary bg-primary text-primary-foreground'
                    : 'border-border text-muted-foreground hover:border-primary/30 hover:bg-primary/5'
                }`}
              >
                {option.label}
              </button>
            ))}
          </div>
        </div>

        <div className="mt-3 space-y-3">
          {filteredPharmacies.length === 0 ? (
            <div className="flex flex-col items-center justify-center gap-3 py-8">
              <MapPin className="h-8 w-8 text-muted-foreground/30" />
              <p className="text-sm text-muted-foreground">{t('common.noResults', language)}</p>
              {hasActiveLocationFilters && (
                <Button variant="outline" size="sm" onClick={resetLocationFilters}>
                  <RotateCcw className="mr-1.5 h-3.5 w-3.5" />
                  {language === 'bn' ? 'ফিল্টার রিসেট' : 'Reset Filters'}
                </Button>
              )}
            </div>
          ) : (
            filteredPharmacies.map((pharmacy) => (
            <Card
              key={pharmacy.id}
              className="border-border/50 bg-card transition-all duration-200 hover:border-primary/20 hover:shadow-md cursor-pointer"
              onClick={() => setSelectedPharmacyId(pharmacy.id)}
            >
              <CardContent className="p-4">
                <div className="flex items-start justify-between gap-3">
                  <div className="flex items-start gap-3">
                    {/* Pharmacy Icon */}
                    <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-primary/10">
                      <Pill className="h-5 w-5 text-primary" />
                    </div>

                    <div>
                      <div className="flex items-center gap-2">
                        <h3 className="text-sm font-bold text-foreground">{pharmacy.name}</h3>
                        {pharmacy.isOpen ? (
                          <Badge className="bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400 text-[10px] px-1.5 py-0">
                            {language === 'en' ? 'Open' : 'খোলা'}
                          </Badge>
                        ) : (
                          <Badge className="bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400 text-[10px] px-1.5 py-0">
                            {language === 'en' ? 'Closed' : 'বন্ধ'}
                          </Badge>
                        )}
                      </div>

                      <p className="mt-0.5 text-xs text-muted-foreground">{pharmacy.address}</p>

                      <div className="mt-1.5 flex items-center gap-3">
                        <div className="flex items-center gap-1">
                          <MapPin className="h-3 w-3 text-primary" />
                          <span className="text-xs font-medium text-primary">{pharmacy.distance}</span>
                        </div>
                        <div className="flex items-center gap-1">
                          {renderStars(pharmacy.rating)}
                          <span className="text-[10px] text-muted-foreground">({pharmacy.reviewCount})</span>
                        </div>
                      </div>

                      <div className="mt-1 flex items-center gap-1">
                        <Clock className="h-3 w-3 text-muted-foreground" />
                        <span className="text-[10px] text-muted-foreground">
                          {pharmacy.isOpen
                            ? pharmacy.hours
                            : language === 'en'
                            ? 'Closed now'
                            : 'এখন বন্ধ'}
                        </span>
                      </div>
                    </div>
                  </div>
                  <ChevronRight className="h-5 w-5 shrink-0 text-muted-foreground" />
                </div>

                <Separator className="my-3" />

                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    className="flex-1 border-primary/20 text-primary text-xs"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleGetDirections(pharmacy);
                    }}
                  >
                    <Navigation className="mr-1 h-3 w-3" />
                    {language === 'en' ? 'Directions' : 'দিকনির্দেশ'}
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    className="flex-1 border-border text-foreground text-xs"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleCall(pharmacy.phone, pharmacy.name);
                    }}
                  >
                    <Phone className="mr-1 h-3 w-3" />
                    {language === 'en' ? 'Call' : 'কল'}
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))
          )}
        </div>
      </section>



      {/* ─── Health Tips ─── */}
      <section ref={tipsSectionRef}>
        <div className="flex items-center gap-2">
          <Heart className="h-5 w-5 text-primary" />
          <h2 className="text-base font-bold text-foreground">
            {language === 'en' ? 'Health Tips' : 'স্বাস্থ্য পরামর্শ'}
          </h2>
        </div>

        <div className="mt-3 grid grid-cols-2 gap-3">
          {healthTips.map((tip) => (
            <Card
              key={tip.id}
              className="border-border/50 bg-card transition-all duration-200 hover:border-primary/20 hover:shadow-md cursor-pointer active:scale-[0.97]"
              onClick={() => setSelectedTipId(tip.id)}
            >
              <CardContent className="p-3">
                <div className="flex items-start justify-between">
                  <span className="text-2xl">{tip.icon}</span>
                  <button
                    onClick={(e) => toggleSaveTip(tip.id, e)}
                    className="rounded-full p-1 transition-colors hover:bg-primary/10"
                  >
                    <Bookmark
                      className={`h-4 w-4 ${
                        savedTips.has(tip.id)
                          ? 'fill-primary text-primary'
                          : 'text-muted-foreground/50'
                      }`}
                    />
                  </button>
                </div>
                <h3 className="mt-1.5 text-xs font-bold text-foreground">
                  {language === 'en' ? tip.title : tip.titleBn}
                </h3>
                <p className="mt-0.5 text-[10px] leading-relaxed text-muted-foreground">
                  {language === 'en' ? tip.description : tip.descriptionBn}
                </p>
                <div className="mt-2 flex items-center gap-1 text-[10px] text-primary">
                  <Info className="h-3 w-3" />
                  <span>{language === 'en' ? 'Tap for details' : 'বিস্তারিত দেখুন'}</span>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      </section>

      {/* ─── Pharmacy Detail Dialog ─── */}
      <Dialog open={!!selectedPharmacyId} onOpenChange={(open) => { if (!open) setSelectedPharmacyId(null); }}>
        <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-lg custom-scrollbar">
          {selectedPharmacy && (
            <div className="space-y-4">
              {/* Back Button */}
              <Button variant="ghost" size="sm" onClick={() => setSelectedPharmacyId(null)} className="gap-1.5 text-orange-600 hover:text-orange-700 hover:bg-orange-50 dark:text-orange-400 dark:hover:bg-orange-950/30">
                <ArrowLeft className="h-4 w-4" />
                <span>{language === 'en' ? 'Back to Pharmacies' : 'ফার্মেসিতে ফিরুন'}</span>
              </Button>
              {/* Pharmacy Header */}
              <div className="flex items-start gap-3">
                <div className="flex h-14 w-14 shrink-0 items-center justify-center rounded-xl bg-primary/10">
                  <Pill className="h-7 w-7 text-primary" />
                </div>
                <div className="flex-1">
                  <DialogHeader>
                    <DialogTitle className="text-lg">{selectedPharmacy.name}</DialogTitle>
                    <DialogDescription className="sr-only">{selectedPharmacy.address}</DialogDescription>
                  </DialogHeader>
                  <div className="mt-1 flex items-center gap-2">
                    {selectedPharmacy.isOpen ? (
                      <Badge className="bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400 text-[10px]">
                        {language === 'en' ? 'Open Now' : 'এখন খোলা'}
                      </Badge>
                    ) : (
                      <Badge className="bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400 text-[10px]">
                        {language === 'en' ? 'Closed' : 'বন্ধ'}
                      </Badge>
                    )}
                    <div className="flex items-center gap-0.5">
                      {renderStars(selectedPharmacy.rating)}
                      <span className="text-[10px] text-muted-foreground ml-0.5">
                        {selectedPharmacy.rating} ({selectedPharmacy.reviewCount})
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              <Separator />

              {/* Info Grid */}
              <div className="grid grid-cols-2 gap-3">
                <div className="flex flex-col items-center gap-1 rounded-lg bg-primary/5 p-3">
                  <MapPin className="h-5 w-5 text-primary" />
                  <span className="text-xs font-semibold text-primary">{selectedPharmacy.distance}</span>
                  <span className="text-[10px] text-muted-foreground">
                    {language === 'en' ? 'Distance' : 'দূরত্ব'}
                  </span>
                </div>
                <div className="flex flex-col items-center gap-1 rounded-lg bg-primary/5 p-3">
                  <Clock className="h-5 w-5 text-primary" />
                  <span className="text-xs font-semibold">{selectedPharmacy.hours}</span>
                  <span className="text-[10px] text-muted-foreground">
                    {language === 'en' ? 'Hours' : 'সময়সূচী'}
                  </span>
                </div>
              </div>

              {/* Address */}
              <div>
                <h4 className="mb-1.5 text-sm font-semibold text-foreground">
                  {language === 'en' ? 'Address' : 'ঠিকানা'}
                </h4>
                <p className="text-xs text-muted-foreground">{selectedPharmacy.address}</p>
              </div>

              {/* Services */}
              <div>
                <h4 className="mb-2 text-sm font-semibold text-foreground">
                  {language === 'en' ? 'Services' : 'সেবাসমূহ'}
                </h4>
                <div className="flex flex-wrap gap-2">
                  {selectedPharmacy.services.map((service) => (
                    <Badge
                      key={service}
                      variant="secondary"
                      className="text-[10px] gap-1"
                    >
                      <Check className="h-2.5 w-2.5 text-primary" />
                      {service}
                    </Badge>
                  ))}
                </div>
              </div>

              <Separator />

              {/* Action Buttons */}
              <div className="flex flex-col gap-2 pt-1">
                <Button
                  className="w-full bg-gradient-to-r from-primary to-primary/90 font-semibold"
                  onClick={() => handleGetDirections(selectedPharmacy)}
                >
                  <Navigation className="mr-2 h-4 w-4" />
                  {language === 'en' ? 'Get Directions' : 'দিকনির্দেশ নিন'}
                </Button>
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    className="flex-1"
                    onClick={() => handleCall(selectedPharmacy.phone, selectedPharmacy.name)}
                  >
                    <Phone className="mr-1.5 h-4 w-4" />
                    {language === 'en' ? 'Call' : 'কল'}
                  </Button>
                  <Button
                    variant="outline"
                    className="flex-1"
                    onClick={() => handlePharmacyMessage(selectedPharmacy)}
                  >
                    <MessageCircle className="mr-1.5 h-4 w-4" />
                    {language === 'en' ? 'Message' : 'মেসেজ'}
                  </Button>
                </div>
                <Button
                  variant="ghost"
                  className="w-full text-xs text-muted-foreground"
                  onClick={() => {
                    const url = `https://www.google.com/maps/search/?api=1&query=${selectedPharmacy.lat},${selectedPharmacy.lng}`;
                    window.open(url, '_blank');
                  }}
                >
                  <ExternalLink className="mr-1.5 h-3.5 w-3.5" />
                  {language === 'en' ? 'View on Google Maps' : 'Google Maps-এ দেখুন'}
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* ─── Health Tip Detail Dialog ─── */}
      <Dialog open={!!selectedTipId} onOpenChange={(open) => { if (!open) setSelectedTipId(null); }}>
        <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-lg custom-scrollbar">
          {selectedTip && (
            <div className="space-y-4">
              {/* Back Button */}
              <Button variant="ghost" size="sm" onClick={() => setSelectedTipId(null)} className="gap-1.5 text-orange-600 hover:text-orange-700 hover:bg-orange-50 dark:text-orange-400 dark:hover:bg-orange-950/30">
                <ArrowLeft className="h-4 w-4" />
                <span>{language === 'en' ? 'Back to Tips' : 'টিপসে ফিরুন'}</span>
              </Button>
              {/* Tip Header */}
              <div className="flex items-start gap-4">
                <div className={`flex h-16 w-16 shrink-0 items-center justify-center rounded-2xl ${selectedTip.color}`}>
                  <span className="text-3xl">{selectedTip.icon}</span>
                </div>
                <div className="flex-1">
                  <DialogHeader>
                    <DialogTitle className="text-lg">
                      {language === 'en' ? selectedTip.title : selectedTip.titleBn}
                    </DialogTitle>
                    <DialogDescription className="sr-only">
                      {language === 'en' ? selectedTip.description : selectedTip.descriptionBn}
                    </DialogDescription>
                  </DialogHeader>
                  <p className="mt-1 text-sm text-muted-foreground leading-relaxed">
                    {language === 'en' ? selectedTip.description : selectedTip.descriptionBn}
                  </p>
                </div>
              </div>

              <Separator />

              {/* Tips List */}
              <div>
                <h4 className="mb-3 text-sm font-semibold text-foreground">
                  {language === 'en' ? 'Tips to Follow' : 'অনুসরণ করার টিপস'}
                </h4>
                <div className="space-y-3">
                  {(language === 'en' ? selectedTip.details : selectedTip.detailsBn).map((detail, idx) => (
                    <div key={idx} className="flex items-start gap-3">
                      <div className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-primary/10 text-xs font-bold text-primary">
                        {idx + 1}
                      </div>
                      <p className="text-sm text-foreground leading-relaxed pt-0.5">{detail}</p>
                    </div>
                  ))}
                </div>
              </div>

              <Separator />

              {/* Action Buttons */}
              <div className="flex gap-2">
                <Button
                  variant={savedTips.has(selectedTip.id) ? 'default' : 'outline'}
                  className="flex-1"
                  onClick={() => toggleSaveTip(selectedTip.id)}
                >
                  <Bookmark className={`mr-1.5 h-4 w-4 ${savedTips.has(selectedTip.id) ? 'fill-current' : ''}`} />
                  {savedTips.has(selectedTip.id)
                    ? (language === 'en' ? 'Saved' : 'সংরক্ষিত')
                    : (language === 'en' ? 'Save Tip' : 'টিপস সংরক্ষণ')}
                </Button>
                <Button
                  variant="outline"
                  className="flex-1"
                  onClick={() => {
                    const text = language === 'en'
                      ? `${selectedTip.title}: ${selectedTip.details.join('. ')}`
                      : `${selectedTip.titleBn}: ${selectedTip.detailsBn.join('. ')}`;
                    if (navigator.share) {
                      navigator.share({ title: selectedTip.title, text }).catch(() => {});
                    } else {
                      navigator.clipboard.writeText(text);
                      toast({
                        title: language === 'en' ? 'Copied to clipboard!' : 'ক্লিপবোর্ডে কপি হয়েছে!',
                        duration: 1500,
                      });
                    }
                  }}
                >
                  <Share2 className="mr-1.5 h-4 w-4" />
                  {language === 'en' ? 'Share' : 'শেয়ার'}
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* ─── Floating Cart Button ─── */}
      {cart.length > 0 && !cartOpen && (
        <button
          onClick={() => setCartOpen(true)}
          className="fixed bottom-20 right-4 z-50 flex h-14 w-14 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-xl shadow-primary/30 transition-all duration-300 hover:scale-110 hover:shadow-2xl active:scale-95 animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-4"
          aria-label={language === 'en' ? 'Open Cart' : 'কার্ট খুলুন'}
        >
          <ShoppingCart className="h-6 w-6" />
          <span className="absolute -right-1 -top-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-destructive text-[10px] font-bold text-white px-1">
            {cart.reduce((sum, item) => sum + item.quantity, 0)}
          </span>
        </button>
      )}

      {/* ─── Cart Drawer ─── */}
      <Sheet open={cartOpen} onOpenChange={setCartOpen}>
        <SheetContent side="bottom" className="mx-auto max-w-lg rounded-t-2xl">
          <SheetHeader>
            <SheetTitle className="flex items-center gap-2">
              <ShoppingCart className="h-5 w-5 text-primary" />
              {language === 'en' ? 'Your Cart' : 'আপনার কার্ট'}
              <Badge variant="secondary" className="text-[10px]">
                {cart.reduce((sum, item) => sum + item.quantity, 0)} {language === 'en' ? 'items' : 'আইটেম'}
              </Badge>
            </SheetTitle>
            <SheetDescription className="sr-only">
              {language === 'en' ? 'Review and manage your cart items' : 'কার্টের আইটেম দেখুন ও পরিচালনা করুন'}
            </SheetDescription>
          </SheetHeader>

          {cart.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
              <ShoppingCart className="mb-3 h-12 w-12 opacity-30" />
              <p className="text-sm font-medium">{language === 'en' ? 'Cart is empty' : 'কার্ট খালি'}</p>
              <p className="text-xs">{language === 'en' ? 'Add medicines to get started' : 'শুরু করতে ওষুধ যোগ করুন'}</p>
            </div>
          ) : (
            <div className="mt-4 space-y-3 max-h-[50vh] overflow-y-auto custom-scrollbar">
              {cart.map((item) => (
                <div
                  key={item.productId}
                  className="flex items-center gap-3 rounded-xl border bg-card p-3 transition-all hover:shadow-sm"
                >
                  {/* Product Image Placeholder */}
                  <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-red-400 to-rose-500">
                    <span className="text-lg opacity-70">💊</span>
                  </div>

                  {/* Info */}
                  <div className="min-w-0 flex-1">
                    <h4 className="truncate text-sm font-semibold text-foreground">{item.title}</h4>
                    <div className="mt-0.5 flex items-center gap-2">
                      <span className="text-sm font-bold text-primary">৳{item.price}</span>
                      {item.unit && (
                        <span className="text-[10px] text-muted-foreground">/ {item.unit}</span>
                      )}
                      <span className="text-[10px] text-muted-foreground">× {item.quantity}</span>
                    </div>
                  </div>

                  {/* Price Total & Delete */}
                  <div className="flex flex-col items-end gap-1">
                    <span className="text-sm font-bold text-foreground">
                      ৳{(item.price * item.quantity).toLocaleString()}
                    </span>
                    <button
                      onClick={() => {
                        removeFromCart(item.productId);
                        toast({
                          title: language === 'en' ? 'Removed from Cart' : 'কার্ট থেকে সরানো হয়েছে',
                          description: item.title,
                          duration: 1500,
                        });
                      }}
                      className="flex items-center gap-0.5 text-[10px] text-destructive hover:text-destructive/80 transition-colors"
                    >
                      <Trash2 className="h-3 w-3" />
                      {language === 'en' ? 'Remove' : 'সরান'}
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}

          {cart.length > 0 && (
            <div className="mt-4 space-y-3 border-t pt-4">
              {/* Total */}
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium text-muted-foreground">
                  {language === 'en' ? 'Subtotal' : 'সাবটোটাল'}
                </span>
                <span className="text-lg font-bold text-foreground">
                  ৳{cart.reduce((sum, item) => sum + item.price * item.quantity, 0).toLocaleString()}
                </span>
              </div>

              <Button
                className="w-full bg-gradient-to-r from-primary to-primary/90 font-semibold"
                onClick={() => {
                  setCartOpen(false);
                  setCurrentSection('orders');
                }}
              >
                {language === 'en' ? 'Proceed to Checkout' : 'চেকআউটে যান'}
              </Button>
            </div>
          )}
        </SheetContent>
      </Sheet>
    </div>
  );
}
