import React, { useState, useEffect, useRef } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Image,
  Modal,
  TextInput,
  Alert,
  Pressable,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Plus, Minus, X } from 'lucide-react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { API_URL, STORE_ID } from '../../config';
import { useLocalSearchParams } from 'expo-router';
import AgeVerificationModal from '../../components/AgeVerificationModal';
import MaintenanceModal from '../../components/MaintenanceModal';
import StaffOperationModal from '../../components/StaffOperationModal';
import TableSetupModal from '../../components/TableSetupModal';
import TimeLimitDisplay from '../../components/TimeLimitDisplay';
import { useCart, CartItem } from '../../contexts/CartContext';
import { useRouter } from 'expo-router';
import { useTableStatus } from '../../hooks/useTableStatus';
import { useCustomerId } from '../../hooks/useCustomerId';
import { useLanguage, Language } from '../../contexts/LanguageContext';
import { useTranslation } from '../../hooks/useTranslation';
import { normalizeLanguage } from '../../utils/languages';

interface MenuItem {
  id: string;
  name: string;
  price: number;
  description: string;
  image: string;
  largeCategory: string;
  mediumCategory: string;
  smallCategory: string;
  options?: { name: string; price: number }[];
  requiresAgeVerification?: boolean;
}



interface CategoryWithOrder {
  name: string;
  order: number;
}

function normalizeProductOptions(raw: unknown): { name: string; price: number }[] {
  if (Array.isArray(raw)) {
    return raw as { name: string; price: number }[]
  }
  if (typeof raw === 'string') {
    try {
      const parsed = JSON.parse(raw)
      return Array.isArray(parsed) ? parsed : []
    } catch {
      return []
    }
  }
  return []
}

export default function MenuScreen() {
  const router = useRouter();
  const params = useLocalSearchParams();
  const isFromKitchen = params.fromKitchen === '1' || params.fromKitchen === 'true';
  const [menuItems, setMenuItems] = useState<MenuItem[]>([]);
  const [largeCategories, setLargeCategories] = useState<CategoryWithOrder[]>([]);
  const [mediumCategories, setMediumCategories] = useState<Record<string, CategoryWithOrder[]>>({});
  const [smallCategories, setSmallCategories] = useState<Record<string, CategoryWithOrder[]>>({});
  const [loading, setLoading] = useState(true);
  const [selectedLargeCategory, setSelectedLargeCategory] = useState('');
  const [selectedMediumCategory, setSelectedMediumCategory] = useState('');
  const [selectedSmallCategory, setSelectedSmallCategory] = useState('');
  const [selectedItem, setSelectedItem] = useState<MenuItem | null>(null);
  const [quantity, setQuantity] = useState(1);
  const { cart, addToCart, getCartTotal, getCartItemCount } = useCart();
  const [showItemModal, setShowItemModal] = useState(false);
  const [selectedOptions, setSelectedOptions] = useState<string[]>([]);
  const [showAgeVerificationModal, setShowAgeVerificationModal] = useState(false);
  const [ageVerificationConfirmed, setAgeVerificationConfirmed] = useState(false);
  const [pendingCartItem, setPendingCartItem] = useState<{item: MenuItem; quantity: number; options: string[]} | null>(null);
  
  // メンテナンス関連の状態
  const [showMaintenanceModal, setShowMaintenanceModal] = useState(false);
  const [showTableSetupModal, setShowTableSetupModal] = useState(false);
  const { customerId, setCustomerId, refreshCustomerId } = useCustomerId();
  const [timeLimitMinutes, setTimeLimitMinutes] = useState(0);
  const [storeTimeLimitMinutes, setStoreTimeLimitMinutes] = useState(0);
  const [firstOrderTime, setFirstOrderTime] = useState<Date | null>(null);
  const [timeRemaining, setTimeRemaining] = useState(0);
  const [currentStoreId, setCurrentStoreId] = useState(STORE_ID);
  const [show401Error, setShow401Error] = useState(false);
  const [customerInfo, setCustomerInfo] = useState<{
    id: number;
    drinkAllYouCanEnabled: boolean;
    timeLimitEnabled: boolean;
    timeLimitMinutes: number;
  } | null>(null);
  const { language, setAvailableLanguages, setLanguage } = useLanguage();
  const { t } = useTranslation();

  const longPressTimerRef = useRef<number | null>(null);

  // URLパラメータからstoreIdとtableIdを取得（セッションストレージからも復元）
  const [urlStoreId, setUrlStoreId] = useState(params.storeId as string);
  const [urlTableId, setUrlTableId] = useState(params.tableId as string);

  // URLパラメータが変更された時に状態を更新（最優先）
  useEffect(() => {
    if (params.storeId && params.tableId) {
      setUrlStoreId(params.storeId as string);
      setUrlTableId(params.tableId as string);
    }
  }, [params.storeId, params.tableId]);

  // AsyncStorageからURLパラメータを復元（URLパラメータがない場合のみ）
  useEffect(() => {
    const restoreUrlParams = async () => {
      // URLパラメータが既に存在する場合は復元しない
      if (params.storeId && params.tableId) {
        return;
      }
      
      try {
        const storedUrlStoreId = await AsyncStorage.getItem('urlStoreId');
        const storedUrlTableId = await AsyncStorage.getItem('urlTableId');
        
        if (storedUrlStoreId && storedUrlTableId) {
          setUrlStoreId(storedUrlStoreId);
          setUrlTableId(storedUrlTableId);
        }
      } catch (error) {
        console.error('URLパラメータ復元エラー:', error);
      }
    };

    restoreUrlParams();
  }, [params.storeId, params.tableId]);

  // useTableStatusをURLパラメータの後に呼び出し
  const {
    tableNumber, 
    setTableNumber, 
    tableId, 
    setTableId, 
    storeId, 
    setStoreId, 
    locked,
    setLocked,
    isInitialized,
    checkTableStatusByNumber,
    setIsUrlAccess,
    isUrlAccess,
    saveTableSession
  } = useTableStatus(!isFromKitchen && (!!(params.storeId && params.tableId) || !!(urlStoreId && urlTableId)));

  // URLパラメータの検証（店員操作待ち状態にする）
  useEffect(() => {
    // URLパラメータを最優先で使用
    const currentStoreId = params.storeId as string || urlStoreId;
    const currentTableId = params.tableId as string || urlTableId;

    // URLパラメータが存在する場合の処理
    if (currentStoreId && currentTableId) {

      // URLでテーブルが指定されている場合、アクセス元に応じた処理を行う
      const setTableForStaffOperation = async () => {
        try {
          // まず古いセッションをクリア
          try {
            await fetch(`${API_URL}/session/table`, {
              method: 'DELETE',
              credentials: 'include',
              headers: {
                'X-App-Type': 'front'
              }
            });

            await fetch(`${API_URL}/session/customer-id`, {
              method: 'DELETE',
              credentials: 'include',
              headers: {
                'X-App-Type': 'front'
              }
            });

          } catch (error) {
            console.error('セッションクリアエラー:', error);
          }

          // キッチンからのアクセスの場合はURLアクセス扱いにしない
          if (isFromKitchen) {
            setIsUrlAccess(false);
            setLocked(false);

            // テーブル情報をローカル状態に設定
            setCurrentStoreId(currentStoreId);

            // 新しいテーブル情報をセッションに保存（currentTableIdはテーブル番号、テーブルIDは後で取得）
            await saveTableSession(currentTableId, 0, parseInt(currentStoreId));

            // テーブルの状態を確認（通常のアクセスとして処理）
            await checkTableStatusByNumber(currentTableId, parseInt(currentStoreId));
          } else {
            // URLアクセス状態を設定（これによりlockedがtrueになる）
            setIsUrlAccess(true);
            setLocked(true); // 明示的にlockedをtrueに設定

            // URLパラメータをAsyncStorageに保存
            try {
              await AsyncStorage.setItem('urlStoreId', currentStoreId);
              await AsyncStorage.setItem('urlTableId', currentTableId);
            } catch (error) {
              console.error('URLパラメータ保存エラー:', error);
            }

            // テーブル情報をローカル状態に設定
            setCurrentStoreId(currentStoreId);

            // 新しいテーブル情報をセッションに保存（currentTableIdはテーブル番号、テーブルIDは後で取得）
            await saveTableSession(currentTableId, 0, parseInt(currentStoreId)); // テーブルIDは一時的に0

            // テーブルの状態を確認（店員操作待ち状態になる）
            // この処理でテーブル情報が正しく設定される
            const tableStatus = await checkTableStatusByNumber(currentTableId, parseInt(currentStoreId), true); // isUrlAccessをtrueで渡す

            // URLアクセス時は確実に店員操作待ち状態にする
            if (tableStatus) {
              setLocked(true);
            }
          }
        } catch (error) {
          console.error('テーブル状態確認エラー:', error);
        }
      };

      setTableForStaffOperation();
    } else if (currentStoreId || currentTableId) {
      // URLパラメータが不完全な場合は401エラー
      setShow401Error(true);
    } else {
      // URLパラメータがない場合は、テーブル番号の入力を待つ
      setShowTableSetupModal(true);
    }
  }, [urlStoreId, urlTableId, params.storeId, params.tableId, isFromKitchen]);

  // セッションからテーブル情報を復元（URLパラメータがない場合のみ）
  useEffect(() => {
    // URLパラメータがある場合はセッションから取得しない
    if (params.storeId || params.tableId || urlStoreId || urlTableId) {
      return;
    }

    const fetchTableSession = async () => {
      try {
        const response = await fetch(`${API_URL}/session/table`, {
          credentials: 'include',
          headers: {
            'X-App-Type': 'front'
          }
        });
        
        if (response.ok) {
          const data = await response.json();
          if (data.tableNumber && data.storeId) {
            // セッションからテーブル情報を復元
            setCurrentStoreId(data.storeId.toString());
            setTableNumber(data.tableNumber);
            setStoreId(parseInt(data.storeId));
            
            // テーブルの状態を確認
            checkTableStatusByNumber(data.tableNumber, parseInt(data.storeId));
          }
        } else if (response.status === 401) {
          // 認証エラーの場合はデフォルトのstoreIdを使用
        }
      } catch (error) {
        console.error('テーブルセッション取得エラー:', error);
      }
    };

    fetchTableSession();
  }, [urlStoreId, urlTableId, params.storeId, params.tableId]);

  // デバッグ用: locked状態をログに出力
  useEffect(() => {
  }, [locked, tableNumber, currentStoreId]);

  // 店舗の時間制限設定を取得
  useEffect(() => {
    const fetchStoreTimeLimit = async () => {
      try {
        const response = await fetch(`${API_URL}/customers/store-time-limit`, {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            'X-App-Type': 'front',
          },
          body: JSON.stringify({ store_id: currentStoreId }),
        });
        
        if (response.ok) {
          const data = await response.json();
          setStoreTimeLimitMinutes(data.timeLimitMinutes || 0);
        }
      } catch (error) {
        console.error('店舗時間制限設定取得エラー:', error);
      }
    };

    fetchStoreTimeLimit();
  }, [currentStoreId]);

  // 最初の注文時間を取得
  useEffect(() => {
    const fetchFirstOrderTime = async () => {
      if (!customerId) return;
      
      try {
        const response = await fetch(`${API_URL}/customers/orders`, {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            'X-App-Type': 'front'
          },
          body: JSON.stringify({ customer_id: customerId }),
        });
        
        if (response.ok) {
          const data = await response.json();
          if (data.length > 0) {
            const firstOrder = data[0]; // 最初の注文
            if (firstOrder.orderedAt) {
              setFirstOrderTime(new Date(firstOrder.orderedAt));
            }
          }
        }
      } catch (error) {
        console.error('最初の注文時間取得エラー:', error);
      }
    };

    fetchFirstOrderTime();
  }, [customerId]);

  // 時間制限の計算
  useEffect(() => {
    if (!firstOrderTime || timeLimitMinutes === 0) {
      setTimeRemaining(0);
      return;
    }

    const timeLimit = timeLimitMinutes * 60;
    const startTime = firstOrderTime.getTime();
    const currentTime = Date.now();
    const elapsedTime = Math.floor((currentTime - startTime) / 1000);
    const remainingTime = Math.max(0, timeLimit - elapsedTime);

    setTimeRemaining(remainingTime);

    const timer = setInterval(() => {
      setTimeRemaining(prev => Math.max(0, prev - 1));
    }, 1000);

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

  // 最初の注文時間が変更された時にtimeRemainingをリセット
  useEffect(() => {
    if (!firstOrderTime) {
      setTimeRemaining(0);
    }
  }, [firstOrderTime]);

  // 時間制限をチェックする関数
  const isTimeLimitExceeded = () => {
    if (timeLimitMinutes === 0) return false; // 制限なし
    if (!firstOrderTime) return false; // 最初の注文がない場合は制限なし
    return timeRemaining <= 0;
  };

  // 長押し処理
  const handleLongPress = () => {
    setShowMaintenanceModal(true);
  };

  const handlePressIn = () => {
    longPressTimerRef.current = window.setTimeout(() => {
      handleLongPress();
    }, 5000); // 5秒
  };

  const handlePressOut = () => {
    if (longPressTimerRef.current) {
      clearTimeout(longPressTimerRef.current);
      longPressTimerRef.current = null;
    }
  };

  const handleTableChange = async (newTableNumber: string) => {
    setTableNumber(newTableNumber);

    // セッションストレージに保存
    try {
      const tableResponse = await fetch(`${API_URL}/session/table`, {
        method: 'POST',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ tableNumber: newTableNumber }),
      });

      if (tableResponse.status === 401) {
        return;
      }

      // まず、既存の顧客IDがあるかチェック（自動設定）
      const existingCustomerResponse = await fetch(`${API_URL}/session/customer-id`, {
        credentials: 'include'
      });
      
      if (existingCustomerResponse.status === 401) {
        return;
      }
      
      if (existingCustomerResponse.ok) {
        const existingCustomerData = await existingCustomerResponse.json();
        if (existingCustomerData.customerId) {
          return;
        }
      }

      // 既存の顧客IDがない場合、指定のテーブルの現在の顧客を取得
      const tableNumberValue = parseInt(newTableNumber.replace(/\D/g, ''));
      
      const customerResponse = await fetch(`${API_URL}/stores/${currentStoreId}/customers/current?tableId=${tableNumberValue}`, {
        credentials: 'include',
        headers: {
          'X-App-Type': 'front'
        }
      });

      if (customerResponse.status === 401) {
        return;
      }

      if (customerResponse.ok) {
        const customer = await customerResponse.json();
        
        // 顧客IDをセッションに保存
        await setCustomerId(customer.id);
      } else if (customerResponse.status === 404) {
      } else {
        const errorText = await customerResponse.text();
        console.error('顧客取得エラー:', customerResponse.status, errorText);
      }
    } catch (error) {
      console.error('テーブル番号の保存エラー:', error);
    }
  };

  // 顧客情報を取得する関数
  const fetchCustomerInfo = async () => {
    
    if (!customerId) {
      setCustomerInfo(null);
      return;
    }

    try {
      const response = await fetch(`${API_URL}/customers/${customerId}`, {
        credentials: 'include',
        headers: {
          'X-App-Type': 'front'
        }
      });

      if (response.ok) {
        const customerData = await response.json();
        setCustomerInfo({
          id: customerData.id,
          drinkAllYouCanEnabled: customerData.drinkAllYouCanEnabled || false,
          timeLimitEnabled: customerData.timeLimitEnabled || false,
          timeLimitMinutes: customerData.timeLimitMinutes || 0
        });
      } else if (response.status === 401) {
        setCustomerInfo(null);
      } else {
        console.error('顧客情報の取得に失敗しました:', response.status);
        setCustomerInfo(null);
      }
    } catch (error) {
      console.error('顧客情報取得エラー:', error);
      setCustomerInfo(null);
    }
  };

  // セッションから年齢確認状態を読み込み
  useEffect(() => {
    const loadAgeVerification = async () => {
      try {
        const response = await fetch(`${API_URL}/session/age-verification`, { credentials: 'include' });
        if (response.ok) {
          const data = await response.json();
          setAgeVerificationConfirmed(!!data.ageVerified);
        }
      } catch (error) {
        console.error('年齢確認状態の読み込みエラー:', error);
      }
    };

    loadAgeVerification();
  }, []);

  // customerIdが変更された時に顧客情報を取得
  useEffect(() => {
    fetchCustomerInfo();
  }, [customerId]);

  // customerInfoの状態変化を監視
  useEffect(() => {

    if (customerInfo?.drinkAllYouCanEnabled && customerInfo.timeLimitEnabled) {
      setTimeLimitMinutes(customerInfo.timeLimitMinutes || storeTimeLimitMinutes);
      if (selectedLargeCategory !== '飲み放題') {
        setSelectedLargeCategory('飲み放題');
      }
    } else {
      setTimeLimitMinutes(0);
    }
  }, [customerInfo, storeTimeLimitMinutes]);

  // 店員操作待ち状態が解除された時にcustomerIdを再取得
  useEffect(() => {
    
    if (!locked && tableNumber && storeId) {
      // 少し遅延を入れてからcustomerIdを再取得
      setTimeout(() => {
        refreshCustomerId();
      }, 1000);
    }
  }, [locked, tableNumber, storeId, refreshCustomerId]);

  // 店舗情報・カテゴリを取得
  useEffect(() => {

    const fetchStoreData = async () => {
      try {
        const storeResponse = await fetch(`${API_URL}/stores/public/${currentStoreId}`, { 
          credentials: 'include',
          headers: {
            'X-App-Type': 'front'
          }
        });
        const storeData = await storeResponse.json();
        const langs: Language[] = (storeData.languages || []).map((l: string) =>
          normalizeLanguage(l)
        );
        if (!langs.includes('ja')) {
          langs.unshift('ja');
        }
        setAvailableLanguages(langs);
        if (!langs.includes(language)) {
          setLanguage(langs[0]);
        }

        // カテゴリーデータの設定
        const largeCats = storeData.largeCategories || [
          { name: 'ドリンク', order: 1 },
          { name: 'フード', order: 2 },
          { name: 'デザート', order: 3 }
        ];
        

        
        // 表示順でソート
        const sortedLargeCategories = largeCats.sort((a: CategoryWithOrder, b: CategoryWithOrder) => a.order - b.order);
        setLargeCategories(sortedLargeCategories);
        setMediumCategories(storeData.mediumCategories || {});
        setSmallCategories(storeData.smallCategories || {});
        setSelectedLargeCategory(sortedLargeCategories[0]?.name || 'ドリンク');
        
        // カテゴリー初期化は商品データ取得後に動的に行うため、ここでは最小限の設定のみ
        const firstLargeCategory = sortedLargeCategories[0]?.name || 'ドリンク';
        setSelectedLargeCategory(firstLargeCategory);
        setSelectedMediumCategory('その他');
        setSelectedSmallCategory('その他');


        
      } catch (error) {
        console.error('店舗データの取得に失敗しました:', error);
        // デフォルト値を設定
        const defaultLargeCategories = [
          { name: 'ドリンク', order: 1 },
          { name: 'フード', order: 2 },
          { name: 'デザート', order: 3 }
        ];
        setLargeCategories(defaultLargeCategories);
        setMediumCategories({});
        setSmallCategories({});
        setSelectedLargeCategory('ドリンク');
        setSelectedMediumCategory('その他');
        setSelectedSmallCategory('その他');
      }
    };

        const fetchProducts = async () => {
      try {
        // セッションからstoreIdを取得
        const sessionStoreId = storeId || currentStoreId;
        
        if (!sessionStoreId) {
          setLoading(false);
          return;
        }
        
        // 店舗別商品取得APIを使用
        const response = await fetch(`${API_URL}/stores/${sessionStoreId}/products`, { 
          credentials: 'include',
          headers: {
            'X-App-Type': 'front'
          }
        });
        
        if (response.status === 401) {
          setLoading(false);
          return;
        }
        
        if (!response.ok) {
          const errorData = await response.json();
          console.error('商品取得エラー:', errorData);
          Alert.alert('エラー', '商品データの取得に失敗しました: ' + (errorData.message || '不明なエラー'));
          return;
        }
        
        const data = await response.json();
        
        let formattedItems = data.map((product: any) => ({
          id: String(product.id),
          name: product.translations?.[language]?.name || product.name,
          price: product.price,
          description: product.translations?.[language]?.description || product.description || '',
          image: product.imageUrl || 'https://images.pexels.com/photos/1552630/pexels-photo-1552630.jpeg?auto=compress&cs=tinysrgb&w=300',
          largeCategory: product.largeCategory?.name || product.largeCategory || 'その他',
          mediumCategory: product.mediumCategory?.name || product.mediumCategory || 'その他',
          smallCategory: product.smallCategory?.name || product.smallCategory || 'その他',
          options: normalizeProductOptions(product.options),
          requiresAgeVerification: product.requiresAgeVerification || false,
        }));

        // 飲み放題設定が有効な場合、ドリンク商品を飲み放題商品として複製
        if (customerInfo?.drinkAllYouCanEnabled) {
          const drinkItems = formattedItems.filter((item: any) => item.largeCategory === 'ドリンク');
          const drinkAllYouCanItems = drinkItems.map((item: any) => ({
            ...item,
            id: `drink_${item.id}`, // ユニークなIDを生成
            largeCategory: '飲み放題',
            price: 0, // 飲み放題は無料
          }));
          formattedItems = [...formattedItems, ...drinkAllYouCanItems];
        }

        // 商品データから実際に存在するカテゴリーを取得
        let existingLargeCategories = [...new Set(formattedItems.map((item: any) => item.largeCategory))];
        const existingMediumCategories = [...new Set(formattedItems.map((item: any) => item.mediumCategory))];
        const existingSmallCategories = [...new Set(formattedItems.map((item: any) => item.smallCategory))];

        // 飲み放題設定が有効な場合、飲み放題カテゴリーを追加
        if (customerInfo?.drinkAllYouCanEnabled && !existingLargeCategories.includes('飲み放題')) {
          existingLargeCategories = ['飲み放題', ...existingLargeCategories];
        }



        // 実際に存在するカテゴリーで初期化（より安全な方法）
        if (existingLargeCategories.length > 0) {
          if (!existingLargeCategories.includes(selectedLargeCategory)) {
            setSelectedLargeCategory(existingLargeCategories[0] as string);
          }
          
          // 選択された大カテゴリーに対応する中カテゴリーを取得
          const currentLargeCategory = existingLargeCategories.includes(selectedLargeCategory) 
            ? selectedLargeCategory 
            : existingLargeCategories[0] as string;
          
          const mediumCategoriesForLarge = [...new Set(formattedItems
            .filter((item: any) => item.largeCategory === currentLargeCategory)
            .map((item: any) => item.mediumCategory))];
          
          if (mediumCategoriesForLarge.length > 0 && !mediumCategoriesForLarge.includes(selectedMediumCategory)) {
            setSelectedMediumCategory(mediumCategoriesForLarge[0] as string);
          }
          
          // 選択された中カテゴリーに対応する小カテゴリーを取得
          const currentMediumCategory = mediumCategoriesForLarge.includes(selectedMediumCategory)
            ? selectedMediumCategory
            : mediumCategoriesForLarge[0] as string;
          
          const smallCategoriesForMedium = [...new Set(formattedItems
            .filter((item: any) => item.largeCategory === currentLargeCategory && item.mediumCategory === currentMediumCategory)
            .map((item: any) => item.smallCategory))];
          
          if (smallCategoriesForMedium.length > 0 && !smallCategoriesForMedium.includes(selectedSmallCategory)) {
            setSelectedSmallCategory(smallCategoriesForMedium[0] as string);
          }
        }
        

        setMenuItems(formattedItems);
      } catch (error) {
        console.error('商品データの取得に失敗しました:', error);
        Alert.alert('エラー', '商品データの取得に失敗しました');
      } finally {
        setLoading(false);
      }
    };

    const fetchData = async () => {
      await fetchStoreData();
      await fetchProducts();
    };

    // データを取得
    fetchData();
  }, [currentStoreId, storeId, tableId, customerInfo, language]);
  
  // テーブル番号が設定されていない場合はテーブル設定モーダルを表示（URLでテーブルが指定されていない場合のみ）
  useEffect(() => {
    // セッションが開始されている場合はテーブル設定モーダルを表示しない
    if (tableNumber) {
      setShowTableSetupModal(false);
      return;
    }
    
    // URLでテーブルが指定されていない場合のみテーブル設定モーダルを表示
    if (!urlTableId) {
      setShowTableSetupModal(true);
    }
  }, [tableNumber, urlTableId]);

  const toggleOption = (name: string) => {
    setSelectedOptions((prev) =>
      prev.includes(name) ? prev.filter((o) => o !== name) : [...prev, name]
    )
  }

  // 商品データから動的にカテゴリーを取得
  const currentMediumCategories = menuItems.length > 0 
    ? [...new Set(menuItems
        .filter(item => {
          // 飲み放題カテゴリーが選択されている場合、飲み放題専用の中カテゴリーを表示
          if (selectedLargeCategory === '飲み放題') {
            return item.largeCategory === '飲み放題';
          }
          return item.largeCategory === selectedLargeCategory;
        })
        .map(item => item.mediumCategory))]
    : [];

  const currentSmallCategories = menuItems.length > 0 
    ? [...new Set(menuItems
        .filter(item => {
          // 飲み放題カテゴリーが選択されている場合、飲み放題専用の小カテゴリーを表示
          if (selectedLargeCategory === '飲み放題') {
            return item.largeCategory === '飲み放題' && item.mediumCategory === selectedMediumCategory;
          }
          return item.largeCategory === selectedLargeCategory && item.mediumCategory === selectedMediumCategory;
        })
        .map(item => item.smallCategory))]
    : [];

  // 大カテゴリー選択時に中カテゴリーを自動選択
  useEffect(() => {
    if (currentMediumCategories.length > 0 && !currentMediumCategories.includes(selectedMediumCategory)) {
      setSelectedMediumCategory(currentMediumCategories[0]);
    }
  }, [selectedLargeCategory, currentMediumCategories.join(',')]);



  // 中カテゴリー選択時に小カテゴリーを自動選択（全商品表示のため無効化）
  // useEffect(() => {
  //   if (currentSmallCategories.length > 0 && !currentSmallCategories.includes(selectedSmallCategory)) {
  //     setSelectedSmallCategory(currentSmallCategories[0]);
  //   }
  // }, [selectedMediumCategory, currentSmallCategories.join(',')]);



  // 中カテゴリーに属する全商品を取得（小カテゴリーでフィルタリングしない）
  const filteredItems = menuItems.filter(
    item => {
      // 飲み放題カテゴリーが選択されている場合、飲み放題専用の商品を表示
      if (selectedLargeCategory === '飲み放題') {
        return item.largeCategory === '飲み放題' && item.mediumCategory === selectedMediumCategory;
      }
      // 通常のフィルタリング
      return item.largeCategory === selectedLargeCategory && item.mediumCategory === selectedMediumCategory;
    }
  );

  // 小カテゴリーでグルーピング
  const groupedItems = filteredItems.reduce((groups: { [key: string]: any[] }, item) => {
    const smallCategory = item.smallCategory;
    if (!groups[smallCategory]) {
      groups[smallCategory] = [];
    }
    groups[smallCategory].push(item);
    return groups;
  }, {});

  // 小カテゴリーの順序を決定（「その他」を最後に）
  const sortedSmallCategories = Object.keys(groupedItems).sort((a, b) => {
    if (a === 'その他') return 1;
    if (b === 'その他') return -1;
    return a.localeCompare(b);
  });




  const handleAddToCart = () => {
    if (!selectedItem) return;

    // 店員操作待ち状態の場合は注文を無効化
    if (locked) {
      Alert.alert('店員操作待ち', '店員の入店処理が完了するまでお待ちください。');
      return;
    }

    // テーブル番号が選択されていない場合
    if (!tableNumber) {
      setShowTableSetupModal(true);
      return;
    }

    // 時間制限をチェック
    if (isTimeLimitExceeded()) {
      Alert.alert('時間制限', '制限時間を超過しています。注文できません。');
      return;
    }

    // 年齢確認が必要な商品で、まだ確認が済んでいない場合
    if (selectedItem.requiresAgeVerification && !ageVerificationConfirmed) {
      setPendingCartItem({ item: selectedItem, quantity, options: selectedOptions });
      setShowAgeVerificationModal(true);
      return;
    }

    // 通常のカート追加処理
    addItemToCart(selectedItem, quantity, selectedOptions);
  };

  const addItemToCart = (item: MenuItem, qty: number, options: string[]) => {
    // 飲み放題商品の場合、価格を0に設定
    const finalPrice = item.largeCategory === '飲み放題' ? 0 : item.price;
    
    const cartItem: CartItem = {
      ...item,
      price: finalPrice, // 飲み放題の場合は価格を0に
      options: item.options || [],
      requiresAgeVerification: item.requiresAgeVerification || false,
      quantity: qty,
      selectedOptions: options,
    };
    
    addToCart(cartItem);
    setShowItemModal(false);
    setQuantity(1);
    setSelectedOptions([]);
    
    const message = item.largeCategory === '飲み放題' 
      ? `${item.name} を飲み放題でカートに追加しました` 
      : `${item.name} をカートに追加しました`;
    Alert.alert('追加完了', message);
  };

  const handleAgeVerificationConfirm = async () => {
    try {
      const response = await fetch(`${API_URL}/session/age-verification`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ ageVerified: true }),
      });
      
    } catch (error) {
      console.error('年齢確認状態の更新エラー:', error);
    }

    setAgeVerificationConfirmed(true);
    setShowAgeVerificationModal(false);

    if (pendingCartItem) {
      addItemToCart(pendingCartItem.item, pendingCartItem.quantity, pendingCartItem.options);
      setPendingCartItem(null);
    }
  };

  // 注文完了時に年齢確認状態をリセット（他のページから呼び出し可能）
  const resetAgeVerification = async () => {
    setAgeVerificationConfirmed(false);
    try {
      const response = await fetch(`${API_URL}/session/age-verification`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ ageVerified: false }),
      });
      
    } catch (error) {
      console.error('年齢確認状態のリセットエラー:', error);
    }
  };

  const handleAgeVerificationCancel = () => {
    setShowAgeVerificationModal(false);
    setPendingCartItem(null);
  };



  return (
    <SafeAreaView style={styles.container}>
      {/* Header */}
      <View style={styles.header}>
        <Pressable
          onPressIn={handlePressIn}
          onPressOut={handlePressOut}
          style={styles.tableNumberContainer}
          android_ripple={null}
        >
          <Text style={styles.tableNumber}>
            {t('tableNumber')}: {tableNumber || t('notSelected')}
          </Text>
        </Pressable>


      </View>



      {/* Large Category Tabs */}
      <View style={styles.categoryTabs}>
        <ScrollView horizontal showsHorizontalScrollIndicator={false}>
          {/* 飲み放題設定が有効な場合、飲み放題カテゴリーを最初に表示 */}
          {customerInfo?.drinkAllYouCanEnabled && (
            <TouchableOpacity
              key="飲み放題"
              style={[styles.categoryTab, selectedLargeCategory === '飲み放題' && styles.categoryTabActive]}
              onPress={() => setSelectedLargeCategory('飲み放題')}
            >
              <Text style={[styles.categoryTabText, selectedLargeCategory === '飲み放題' && styles.categoryTabTextActive]}>
                飲み放題
              </Text>
            </TouchableOpacity>
          )}
          {/* 通常のカテゴリー */}
          {largeCategories.map((category) => (
            <TouchableOpacity
              key={category.name}
              style={[styles.categoryTab, selectedLargeCategory === category.name && styles.categoryTabActive]}
              onPress={() => setSelectedLargeCategory(category.name)}
            >
              <Text style={[styles.categoryTabText, selectedLargeCategory === category.name && styles.categoryTabTextActive]}>
                {category.name}
              </Text>
            </TouchableOpacity>
          ))}
        </ScrollView>
      </View>

      {/* Medium Category Tabs */}
      {currentMediumCategories.length > 0 && (
        <View style={styles.categoryTabs}>
          <ScrollView horizontal showsHorizontalScrollIndicator={false}>
            {currentMediumCategories.map((categoryName: string) => (
              <TouchableOpacity
                key={categoryName}
                style={[styles.categoryTab, selectedMediumCategory === categoryName && styles.categoryTabActive]}
                onPress={() => setSelectedMediumCategory(categoryName)}
              >
                <Text style={[styles.categoryTabText, selectedMediumCategory === categoryName && styles.categoryTabTextActive]}>
                  {categoryName}
                </Text>
              </TouchableOpacity>
            ))}
          </ScrollView>
        </View>
      )}

      {/* 小カテゴリータブは削除（グルーピング表示のため不要） */}

      {/* Menu Items - 小カテゴリーでグルーピング表示 */}
      <ScrollView style={styles.menuContainer}>
        {loading || !isInitialized ? (
          <View style={styles.loadingContainer}>
            <Text style={styles.loadingText}>
              {!isInitialized ? '初期化中...' : '商品を読み込み中...'}
            </Text>
          </View>
        ) : filteredItems.length === 0 ? (
          <View style={styles.emptyContainer}>
            <Text style={styles.emptyText}>この条件に該当する商品がありません</Text>
          </View>
        ) : (
          sortedSmallCategories.map((smallCategory) => (
            <View key={smallCategory} style={styles.categoryGroup}>
              {/* 小カテゴリーヘッダー */}
              <View style={styles.categoryHeader}>
                <Text style={styles.categoryHeaderText}>{smallCategory}</Text>
              </View>
              
              {/* 小カテゴリーに属する商品一覧 */}
              {groupedItems[smallCategory].map((item) => (
                <TouchableOpacity
                  key={item.id}
                  style={styles.menuItem}
                  onPress={() => {
                    setSelectedItem(item);
                    setSelectedOptions([]);
                    setQuantity(1);
                    setShowItemModal(true);
                  }}
                >
                  <Image source={{ uri: item.image }} style={styles.menuItemImage} />
                  <View style={styles.menuItemInfo}>
                    <Text style={styles.menuItemName}>{item.name}</Text>
                    <Text style={styles.menuItemDescription}>{item.description}</Text>
                    <Text style={[
                      styles.menuItemPrice,
                      item.largeCategory === '飲み放題' && styles.drinkAllYouCanPrice
                    ]}>
                      {item.largeCategory === '飲み放題' ? '🍺 飲み放題' : `¥${item.price}`}
                    </Text>
                  </View>
                  <View style={styles.addButton}>
                    <Plus size={24} color="#FFFFFF" />
                  </View>
                </TouchableOpacity>
              ))}
            </View>
          ))
        )}
      </ScrollView>

             {/* Time Limit Display */}
      <TimeLimitDisplay
        timeLimitMinutes={timeLimitMinutes}
        firstOrderTime={firstOrderTime}
        timeLimitExtensionMinutes={30}
      />

      {/* Cart Footer */}
       {cart.length > 0 && (
         <View style={styles.cartFooter}>
           <View style={styles.cartInfo}>
             <Text style={styles.cartItemCount}>{getCartItemCount()}点</Text>
             <Text style={styles.cartTotal}>¥{getCartTotal()}</Text>
           </View>
           {tableNumber && isInitialized ? (
             <TouchableOpacity 
               style={styles.viewCartButton}
               onPress={() => router.push('/cart')}
             >
               <Text style={styles.viewCartButtonText}>カートを見る</Text>
             </TouchableOpacity>
           ) : (
             <View style={styles.viewCartButtonDisabled}>
               <Text style={styles.viewCartButtonTextDisabled}>
                 {!isInitialized ? '初期化中...' : t('selectTableNumber')}
               </Text>
             </View>
           )}
         </View>
       )}

      {/* Item Detail Modal */}
      <Modal
        visible={showItemModal}
        animationType="slide"
        presentationStyle="pageSheet"
      >
        <SafeAreaView style={styles.modalContainer}>
          <View style={styles.modalHeader}>
            <TouchableOpacity
              style={styles.closeButton}
              onPress={() => setShowItemModal(false)}
            >
              <X size={24} color="#374151" />
            </TouchableOpacity>
            <Text style={styles.modalTitle}>{selectedItem?.name}</Text>
          </View>

          <ScrollView style={styles.modalContent}>
            {selectedItem && (
              <>
                <Image source={{ uri: selectedItem.image }} style={styles.modalImage} />
                <View style={styles.modalInfo}>
                  <Text style={styles.modalItemName}>{selectedItem.name}</Text>
                  <Text style={styles.modalItemPrice}>
                    ¥{(() => {
                      // 基本価格
                      let totalPrice = selectedItem.price;
                      
                      // 選択されたオプションの料金を加算
                      if (selectedItem.options) {
                        selectedOptions.forEach(selectedOption => {
                          const option = selectedItem.options!.find(opt => opt.name === selectedOption);
                          if (option && option.price) {
                            totalPrice += option.price;
                          }
                        });
                      }
                      
                      return totalPrice;
                    })()}
                  </Text>
                  <Text style={styles.modalItemDescription}>{selectedItem.description}</Text>

                  {selectedItem.options && (
                    <View style={styles.optionsContainer}>
                      <Text style={styles.optionsLabel}>オプション</Text>
                      {selectedItem.options.map((opt) => (
                        <TouchableOpacity
                          key={opt.name}
                          style={[
                            styles.optionItem,
                            selectedOptions.includes(opt.name) && styles.optionItemSelected,
                          ]}
                          onPress={() => toggleOption(opt.name)}
                        >
                          <Text style={styles.optionItemText}>
                            {opt.name} {opt.price ? `(＋¥${opt.price})` : ''}
                          </Text>
                        </TouchableOpacity>
                      ))}
                    </View>
                  )}

                  <View style={styles.quantityContainer}>
                    <Text style={styles.quantityLabel}>数量</Text>
                    <View style={styles.quantityControls}>
                      <TouchableOpacity
                        style={styles.quantityButton}
                        onPress={() => setQuantity(Math.max(1, quantity - 1))}
                      >
                        <Minus size={20} color="#374151" />
                      </TouchableOpacity>
                      <TextInput
                        style={styles.quantityInput}
                        value={quantity.toString()}
                        onChangeText={(text) => setQuantity(Math.max(1, parseInt(text) || 1))}
                        keyboardType="numeric"
                      />
                      <TouchableOpacity
                        style={styles.quantityButton}
                        onPress={() => setQuantity(quantity + 1)}
                      >
                        <Plus size={20} color="#374151" />
                      </TouchableOpacity>
                    </View>
                  </View>
                </View>
              </>
            )}
          </ScrollView>

                     <View style={styles.modalFooter}>
             <TouchableOpacity 
               style={[
                 styles.addToCartButton, 
                 isTimeLimitExceeded() && styles.addToCartButtonDisabled
               ]} 
               onPress={handleAddToCart}
               disabled={isTimeLimitExceeded()}
             >
               <Text style={styles.addToCartButtonText}>
                 {isTimeLimitExceeded() ? '時間制限超過' : `カートに追加 (¥${(() => {
                   if (!selectedItem) return 0;
                   
                   // 基本価格
                   let totalPrice = selectedItem.price;
                   
                   // 選択されたオプションの料金を加算
                   if (selectedItem.options) {
                     selectedOptions.forEach(selectedOption => {
                       const option = selectedItem.options!.find(opt => opt.name === selectedOption);
                       if (option && option.price) {
                         totalPrice += option.price;
                       }
                     });
                   }
                   
                   // 数量を掛ける
                   return totalPrice * quantity;
                 })()})`}
               </Text>
             </TouchableOpacity>
           </View>
        </SafeAreaView>
      </Modal>

      {/* Age Verification Modal */}
      <AgeVerificationModal
        visible={showAgeVerificationModal}
        onConfirm={handleAgeVerificationConfirm}
        onCancel={handleAgeVerificationCancel}
      />

             {/* Maintenance Modal */}
       <MaintenanceModal
         visible={showMaintenanceModal}
         onClose={() => setShowMaintenanceModal(false)}
         currentTableNumber={tableNumber}
         onTableChange={tableNumber ? undefined : handleTableChange} // セッション開始後は変更不可
       />

       {locked && (
         <StaffOperationModal 
           visible={true} 
           isWaitingForCheckIn={true}
           onReload={() => {
             // テーブル状態を再確認
             if (tableNumber && currentStoreId) {
               checkTableStatusByNumber(tableNumber, parseInt(currentStoreId));
             }
             // customerIdも再取得
             setTimeout(() => {
               refreshCustomerId();
             }, 1000);
           }}
         />
       )}
       

       


      {/* Table Setup Modal */}
      <TableSetupModal
        visible={showTableSetupModal}
        onClose={() => setShowTableSetupModal(false)}
        storeId={currentStoreId}
        onTableSet={async (tableNumber, tableId) => {
          try {
            // 前のテーブルのセッションをクリア
            await fetch(`${API_URL}/session/customer-id`, {
              method: 'DELETE',
              headers: { 
                'X-App-Type': 'front'
              },
              credentials: 'include',
            });
            
            // セッションにテーブル情報を保存（店員操作済みの場合のみ）
            if (tableId) {
              await saveTableSession(tableNumber, tableId, parseInt(currentStoreId));
            }
            
            // ローカル状態を更新
            setTableNumber(tableNumber);
            if (tableId) {
              setTableId(tableId);
            }
            setStoreId(parseInt(currentStoreId));
            
            // 店員操作完了時にAsyncStorageをクリア
            try {
              await AsyncStorage.removeItem('isUrlAccess');
              await AsyncStorage.removeItem('urlStoreId');
              await AsyncStorage.removeItem('urlTableId');
              
              // URLアクセス状態をリセット
              setIsUrlAccess(false);
            } catch (error) {
              console.error('AsyncStorageクリアエラー:', error);
            }
            
            // テーブル変更後に入店済みかどうかをチェック
            setTimeout(() => {
              checkTableStatusByNumber(tableNumber, parseInt(currentStoreId));
            }, 500);
            
            setShowTableSetupModal(false);
          } catch (error) {
            console.error('テーブルセッション保存エラー:', error);
          }
        }}
      />

      {/* 401 Error Modal */}
      {show401Error && (
        <Modal visible={true} transparent animationType="fade">
          <View style={styles.errorOverlay}>
            <View style={styles.errorContent}>
              <Text style={styles.errorTitle}>401</Text>
              <Text style={styles.errorText}>アクセス権限がありません</Text>
              <Text style={styles.errorSubText}>
                正しいURLでアクセスしてください
              </Text>
            </View>
          </View>
        </Modal>
      )}

    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F9FAFB',
  },
  header: {
    backgroundColor: '#FFFFFF',
    paddingHorizontal: 20,
    paddingVertical: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#E5E7EB',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  tableNumberContainer: {
    padding: 8,
  },
  tableNumber: {
    fontSize: 18,
    fontWeight: '700',
    color: '#111827',
    textAlign: 'center',
  },
  categoryTabs: {
    backgroundColor: '#FFFFFF',
    paddingVertical: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#E5E7EB',
  },
  categoryTab: {
    paddingHorizontal: 20,
    paddingVertical: 8,
    marginHorizontal: 8,
    borderRadius: 20,
    backgroundColor: '#F3F4F6',
  },
  categoryTabActive: {
    backgroundColor: '#3B82F6',
  },
  categoryTabText: {
    fontSize: 14,
    fontWeight: '600',
    color: '#6B7280',
  },
  categoryTabTextActive: {
    color: '#FFFFFF',
  },
  categoryTabDisabled: {
    backgroundColor: '#F3F4F6',
    opacity: 0.5,
  },
  categoryTabTextDisabled: {
    color: '#9CA3AF',
  },
  drinkAllYouCanMessage: {
    backgroundColor: '#FEF3C7',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderBottomWidth: 1,
    borderBottomColor: '#F59E0B',
  },
  drinkAllYouCanMessageText: {
    color: '#92400E',
    fontSize: 14,
    fontWeight: '600',
    textAlign: 'center',
  },
  drinkAllYouCanPrice: {
    color: '#059669',
    fontWeight: '800',
  },

  menuContainer: {
    flex: 1,
    padding: 16,
  },
  menuItem: {
    flexDirection: 'row',
    backgroundColor: '#FFFFFF',
    borderRadius: 12,
    padding: 16,
    marginBottom: 12,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  menuItemImage: {
    width: 80,
    height: 80,
    borderRadius: 8,
  },
  menuItemInfo: {
    flex: 1,
    marginLeft: 16,
    justifyContent: 'space-between',
  },
  menuItemName: {
    fontSize: 16,
    fontWeight: '700',
    color: '#111827',
    marginBottom: 4,
  },
  menuItemDescription: {
    fontSize: 14,
    color: '#6B7280',
    marginBottom: 8,
  },
  menuItemPrice: {
    fontSize: 16,
    fontWeight: '700',
    color: '#F97316',
  },
  addButton: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#3B82F6',
    justifyContent: 'center',
    alignItems: 'center',
    alignSelf: 'center',
  },
  cartFooter: {
    backgroundColor: '#FFFFFF',
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 20,
    paddingVertical: 16,
    borderTopWidth: 1,
    borderTopColor: '#E5E7EB',
  },
  cartInfo: {
    flex: 1,
  },
  cartItemCount: {
    fontSize: 14,
    color: '#6B7280',
  },
  cartTotal: {
    fontSize: 18,
    fontWeight: '700',
    color: '#111827',
  },
  viewCartButton: {
    backgroundColor: '#3B82F6',
    paddingHorizontal: 24,
    paddingVertical: 12,
    borderRadius: 8,
  },
  viewCartButtonText: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: '600',
  },
  viewCartButtonDisabled: {
    backgroundColor: '#9CA3AF',
    paddingHorizontal: 24,
    paddingVertical: 12,
    borderRadius: 8,
  },
  viewCartButtonTextDisabled: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: '600',
  },
  modalContainer: {
    flex: 1,
    backgroundColor: '#F9FAFB',
  },
  modalHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 20,
    paddingVertical: 16,
    backgroundColor: '#FFFFFF',
    borderBottomWidth: 1,
    borderBottomColor: '#E5E7EB',
  },
  closeButton: {
    padding: 8,
  },
  modalTitle: {
    flex: 1,
    fontSize: 18,
    fontWeight: '700',
    color: '#111827',
    textAlign: 'center',
    marginRight: 40,
  },
  modalContent: {
    flex: 1,
  },
  modalImage: {
    width: '100%',
    height: 200,
    resizeMode: 'cover',
  },
  modalInfo: {
    padding: 20,
    backgroundColor: '#FFFFFF',
  },
  modalItemName: {
    fontSize: 24,
    fontWeight: '700',
    color: '#111827',
    marginBottom: 8,
  },
  modalItemPrice: {
    fontSize: 20,
    fontWeight: '700',
    color: '#F97316',
    marginBottom: 12,
  },
  modalItemDescription: {
    fontSize: 16,
    color: '#6B7280',
    lineHeight: 24,
    marginBottom: 24,
  },
  quantityContainer: {
    marginBottom: 20,
  },
  quantityLabel: {
    fontSize: 16,
    fontWeight: '600',
    color: '#111827',
    marginBottom: 12,
  },
  quantityControls: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  quantityButton: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: '#F3F4F6',
    justifyContent: 'center',
    alignItems: 'center',
  },
  quantityInput: {
    width: 80,
    height: 44,
    marginHorizontal: 16,
    textAlign: 'center',
    fontSize: 18,
    fontWeight: '600',
    backgroundColor: '#FFFFFF',
    borderWidth: 1,
    borderColor: '#D1D5DB',
    borderRadius: 8,
  },
  optionsContainer: {
    marginBottom: 20,
  },
  optionsLabel: {
    fontSize: 16,
    fontWeight: '600',
    color: '#111827',
    marginBottom: 12,
  },
  optionItem: {
    paddingVertical: 8,
    paddingHorizontal: 12,
    borderWidth: 1,
    borderColor: '#D1D5DB',
    borderRadius: 8,
    marginBottom: 8,
  },
  optionItemSelected: {
    backgroundColor: '#DBEAFE',
    borderColor: '#3B82F6',
  },
  optionItemText: {
    fontSize: 16,
    color: '#111827',
  },
  modalFooter: {
    backgroundColor: '#FFFFFF',
    paddingHorizontal: 20,
    paddingVertical: 16,
    borderTopWidth: 1,
    borderTopColor: '#E5E7EB',
  },
  addToCartButton: {
    backgroundColor: '#3B82F6',
    paddingVertical: 16,
    borderRadius: 8,
    alignItems: 'center',
  },
  addToCartButtonDisabled: {
    backgroundColor: '#9CA3AF',
  },
  addToCartButtonText: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: '600',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 40,
  },
  loadingText: {
    fontSize: 16,
    color: '#6B7280',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 40,
  },
  emptyText: {
    fontSize: 16,
    color: '#6B7280',
    textAlign: 'center',
  },
  errorOverlay: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'rgba(0,0,0,0.5)',
  },
  errorContent: {
    backgroundColor: '#FFFFFF',
    padding: 40,
    borderRadius: 12,
    alignItems: 'center',
    maxWidth: 300,
  },
  errorTitle: {
    fontSize: 48,
    fontWeight: 'bold',
    color: '#EF4444',
    marginBottom: 16,
  },
  errorText: {
    fontSize: 20,
    fontWeight: '600',
    color: '#111827',
    marginBottom: 8,
    textAlign: 'center',
  },
  errorSubText: {
    fontSize: 14,
    color: '#6B7280',
    textAlign: 'center',
  },
  categoryGroup: {
    marginBottom: 24,
  },
  categoryHeader: {
    backgroundColor: '#F3F4F6',
    paddingHorizontal: 16,
    paddingVertical: 12,
    marginBottom: 8,
    borderRadius: 8,
  },
  categoryHeaderText: {
    fontSize: 16,
    fontWeight: '700',
    color: '#374151',
  },
});