import React, { useState, useRef, useEffect, useCallback } from "react";
import {
  View,
  StyleSheet,
  TouchableOpacity,
  TextInput,
  Image,
  ScrollView,
  FlatList,
  KeyboardAvoidingView,
  Platform,
} from "react-native";
import { router } from "expo-router";
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
import { FLEX, COLOR_SCALES } from "@/theme";
import { title, paragraph } from "@/theme/typography";
import Text from "@/components/common/Text";
import Loading from "@/components/common/Loading";
import Empty from "@/components/common/Empty";
import Toast from "@/components/common/Toast";
import { OPENAI_API_KEY } from "@/constants/api";
import { getProfile, checkUserPackage, checkExerciseNotification, getExerciseQuestiom } from "@/services/user";
import { surveys, submitSurvey } from "@/services/survey";
import { getLokmaNotification, saveLokmaNotification, getFoodTypes, getActiveNotification } from "@/services/notifications";
import useAuth from "@/hooks/useAuth";
import useGuest from "@/hooks/useGuest";
import useToast from "@/hooks/useToast";
import { Ionicons } from "@expo/vector-icons";

// ✅ API key centralized in constants

export default function LokmaChatScreen() {
  const insets = useSafeAreaInsets();
  const { user: authUser } = useAuth();
  const { toast, showToast, hideToast } = useToast();
  const { isGuest } = useGuest();
  const [inputText, setInputText] = useState("");
  const [isChatStarted, setIsChatStarted] = useState(false);
  const [messages, setMessages] = useState([]);
  const scrollViewRef = useRef();
  const [isLoading, setIsLoading] = useState(false);
  const [userName, setUserName] = useState("Kullanıcı");
  const [hasPackage, setHasPackage] = useState(false);
  const [isPackageLoading, setIsPackageLoading] = useState(true);
  const [userAvatarSource, setUserAvatarSource] = useState(require("@/assets/images/default.png"));
  const [inputHeight, setInputHeight] = useState(72);
  
  // Survey states
  const [currentSurvey, setCurrentSurvey] = useState(null);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [surveyAnswers, setSurveyAnswers] = useState([]);
  const [currentAnswer, setCurrentAnswer] = useState(null);
  const [isSurveyMode, setIsSurveyMode] = useState(false);
  const [surveyLoading, setSurveyLoading] = useState(false);
  
  // Exercise states
  const [currentExercise, setCurrentExercise] = useState(null);
  const [exerciseQuestions, setExerciseQuestions] = useState([]);
  const [currentQuestionIdx, setCurrentQuestionIdx] = useState(0);
  const [selectedAnswer, setSelectedAnswer] = useState(null);
  const [timeLeft, setTimeLeft] = useState(15);
  const [isExerciseMode, setIsExerciseMode] = useState(false);
  const [exerciseLoading, setExerciseLoading] = useState(false);
  
  // Lokma notification states
  const [currentStep, setCurrentStep] = useState("idle");
  const [foodType, setFoodType] = useState([]);
  const [selectedMealId, setSelectedMealId] = useState(null);
  const [selectedFoodTypeIds, setSelectedFoodTypeIds] = useState([]);
  const [selectedPlaceId, setSelectedPlaceId] = useState(null);
  const [isLokmaMode, setIsLokmaMode] = useState(false);
  const [lokmaLoading, setLokmaLoading] = useState(false);
  const [guestToastShown, setGuestToastShown] = useState(false);

  useEffect(() => {
    let isMounted = true;
    const load = async () => {
      try {
        // Önce auth içindeki kullanıcıyı kullan
        if (isMounted && authUser) {
          const fromAuth = authUser?.name
            ?? authUser?.fullName
            ?? authUser?.username
            ?? `${authUser?.firstName ?? ''} ${authUser?.lastName ?? ''}`.trim();
          if (fromAuth && fromAuth.length > 0) {
            setUserName(fromAuth);
          }
        }
        const [profileRes, packageRes] = await Promise.allSettled([
          getProfile(),
          checkUserPackage(),
        ]);
        if (isMounted && profileRes.status === 'fulfilled') {
          const resp = profileRes.value;
          const data = resp?.data ?? resp;
          const u = data?.user ?? data;
          const candidate = u?.name
            ?? u?.fullName
            ?? u?.username
            ?? `${u?.firstName ?? ''} ${u?.lastName ?? ''}`.trim();
          setUserName(candidate && candidate.length > 0 ? candidate : 'Kullanıcı');

          // Avatar belirle - ProfileHeader'daki resolveAvatarSource mantığını kullan
          const resolveAvatarSource = (userData) => {
            try {
              const rawAvatar = userData?.avatar;
              const profileImage = userData?.profile_image;

              // 1. Önce rawAvatar'ı kontrol et (local file veya full URL)
              if (typeof rawAvatar === 'string' && rawAvatar.length > 0) {
                if (rawAvatar.startsWith('http') || rawAvatar.startsWith('file:') || rawAvatar.startsWith('content:')) {
                  return { uri: rawAvatar };
                }
              }

              // 2. Backend'den gelen profile_image'ı kontrol et
              if (typeof profileImage === 'string' && profileImage.length > 0) {
                if (profileImage.startsWith('http')) {
                  return { uri: profileImage };
                }
                // Relative path - build full URL
                const fullUrl = `https://api.bugunyap.com/src/uploads/profile/${String(profileImage)}`;
                return { uri: fullUrl };
              }

              // 3. Fallback - default image
              return require('@/assets/images/default.png');
            } catch (e) {
              return require('@/assets/images/default.png');
            }
          };

          setUserAvatarSource(resolveAvatarSource(u));
        }
        if (isMounted) {
          if (packageRes.status === 'fulfilled') {
            const raw = packageRes.value;
            const d = raw?.data ?? raw;
            let owned = false;
            if (d && typeof d === 'object' && Object.prototype.hasOwnProperty.call(d, 'hasPackage')) {
              owned = Boolean(d.hasPackage);
            } else if (typeof d === 'boolean') {
              owned = d;
            } else if (Array.isArray(d)) {
              owned = d.length > 0;
            } else if (d && typeof d === 'object') {
              owned = Object.values(d)?.some?.((v) => v === true || v === 1) ?? false;
            }
            setHasPackage(Boolean(owned));
          } else {
            setHasPackage(false);
          }
        }
      } catch (_) {
        if (isMounted) setHasPackage(false);
      } finally {
        if (isMounted) setIsPackageLoading(false);
      }
    };
    load();
    return () => { isMounted = false; };
  }, []);

  const handleBackPress = () => {
    router.back();
  };

  const handleChatModalToggle = async () => {
    try {
      const res = await getActiveNotification();
      const hasData = !!res?.data;
      
      if (res?.success && hasData) {
        // Aktif bildirim varsa Lokma modunu başlat
        await startLokmaMode();
      } else {
        // Aktif bildirim yoksa uygun mesaj göster
        const noNotificationMessage = {
          id: generateUniqueId(),
          type: "lokma",
          text: res?.message ?? "Aktif bildiriminiz bulunmamaktadır",
          lokmaName: "Lokma'm",
          lokmaAvatar: require("@/assets/images/package-lokma.png"),
        };
        setMessages((prev) => [...prev, noNotificationMessage]);
      }
    } catch (err) {
      const errorMessage = {
        id: generateUniqueId(),
        type: "lokma",
        text: err?.message ?? "Aktif bildirim kontrol edilemedi",
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };
      setMessages((prev) => [...prev, errorMessage]);
    }
  };

  // Gıda dışı konuları filtrele
  const isFoodRelatedTopic = (message) => {
    const foodKeywords = [
      'gıda', 'yemek', 'beslenme', 'israf', 'atık', 'çöp', 'saklama', 'muhafaza',
      'alışveriş', 'market', 'süpermarket', 'tarım', 'sebze', 'meyve', 'et', 'tavuk',
      'balık', 'süt', 'peynir', 'yoğurt', 'ekmek', 'pirinç', 'makarna', 'pilav',
      'salata', 'çorba', 'tatlı', 'kek', 'börek', 'pizza', 'hamburger', 'döner',
      'kebap', 'lahmacun', 'pide', 'mantı', 'köfte', 'karnıyarık', 'dolma',
      'sarma', 'börek', 'gözleme', 'pancake', 'waffle', 'toast', 'sandwich',
      'tost', 'omlet', 'menemen', 'kaymak', 'bal', 'reçel', 'marmelat',
      'konserve', 'dondurulmuş', 'dondurma', 'dondurucu', 'buzdolabı',
      'fırın', 'ocak', 'tava', 'tencere', 'tava', 'kepçe', 'kaşık', 'çatal',
      'bıçak', 'tabak', 'bardak', 'kase', 'servis', 'sofra', 'masa',
      'mutfak', 'tarif', 'yemek tarifi', 'pişirme', 'kızartma', 'haşlama',
      'kavurma', 'fırınlama', 'kaynatma', 'dondurma', 'çözme', 'ısıtma',
      'soğutma', 'saklama', 'muhafaza', 'konserve', 'turşu', 'salamura',
      'tuzlama', 'kurutma', 'dondurma', 'dondurucu', 'buzdolabı', 'derin dondurucu',
      'gıda güvenliği', 'hijyen', 'temizlik', 'sterilizasyon', 'pastörizasyon',
      'besin değeri', 'kalori', 'protein', 'karbonhidrat', 'yağ', 'vitamin',
      'mineral', 'lif', 'antioksidan', 'organik', 'doğal', 'katkı maddesi',
      'koruyucu', 'renklendirici', 'tatlandırıcı', 'aroma', 'lezzet',
      'tuz', 'şeker', 'baharat', 'ot', 'çeşni', 'sos', 'ketçap', 'mayonez',
      'hardal', 'sirke', 'limon', 'sarımsak', 'soğan', 'domates', 'biber',
      'patlıcan', 'kabak', 'havuç', 'patates', 'lahana', 'marul', 'roka',
      'maydanoz', 'dereotu', 'nane', 'fesleğen', 'kekik', 'biberiye',
      'zeytin', 'zeytinyağı', 'ayçiçek yağı', 'tereyağı', 'margarin',
      'sıvı yağ', 'katı yağ', 'kızartma yağı', 'yemek yağı', 'pişirme yağı'
    ];
    
    const messageLower = message.toLowerCase();
    return foodKeywords.some(keyword => messageLower.includes(keyword));
  };

  // 🔥 Lokma'dan cevap al
  const getLokmaResponse = async (userMessage) => {
    if (!hasPackage) return;
    
    // Gıda dışı konuları filtrele
    if (!isFoodRelatedTopic(userMessage)) {
      const filteredResponse = {
        id: generateUniqueId(),
        type: "lokma",
        text: "Bu konu hakkında fikir belirtemiyorum 😊 Gıda israfı, saklama yöntemleri ve alışveriş konularında sana yardımcı olabilirim!",
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };
      setMessages((prev) => [...prev, filteredResponse]);
      return;
    }
    
    if (!OPENAI_API_KEY) {
      const errorResponse = {
        id: Date.now() + 2,
        type: "lokma",
        text: "API anahtarı bulunamadı. Lütfen yapılandırmayı kontrol edin.",
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };
      setMessages((prev) => [...prev, errorResponse]);
      return;
    }
    if (isLoading) return;

    try {
      setIsLoading(true);
      const response = await fetch("https://api.openai.com/v1/chat/completions", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          Authorization: `Bearer ${OPENAI_API_KEY}`,
        },
        body: JSON.stringify({
          model: "gpt-4o-mini",
          messages: [
            { role: "system", content: "Sen Lokma adında sevimli bir yardımcı botsun. SADECE gıda israfı, saklama yöntemleri, alışveriş ipuçları ve gıda eğitimleri konularında kullanıcılara eğlenceli ve samimi bir dille yardımcı ol. Diğer konularda 'Bu konu hakkında fikir belirtemiyorum 😊' şeklinde yanıt ver." },
            { role: "user", content: userMessage },
          ],
          max_tokens: 250,
        }),
      });

      if (!response.ok) {
        let errJson = null;
        try { errJson = await response.json(); } catch (_) {}
        const message = errJson?.error?.message ?? `API hata durum kodu: ${response.status}`;
        throw new Error(message);
      }

      const data = await response.json();
      const reply = data?.choices?.[0]?.message?.content ?? "Üzgünüm, şu an cevap veremiyorum 😔";

      const lokmaResponse = {
        id: generateUniqueId(),
        type: "lokma",
        text: reply,
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };

      setMessages((prev) => [...prev, lokmaResponse]);
    } catch (error) {
      console.error("OpenAI API Error:", error);
      const errorResponse = {
        id: generateUniqueId(),
        type: "lokma",
        text: error?.message ?? "Bir hata oluştu, lütfen tekrar deneyin ⚠️",
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };
      setMessages((prev) => [...prev, errorResponse]);
    } finally {
      setIsLoading(false);
    }
  };
  // Paket yoksa chat başlatılamaz; aktif sohbeti kapat
  useEffect(() => {
    if (!hasPackage) {
      setIsChatStarted(false);
    }
  }, [hasPackage]);

  const generateUniqueId = () => {
    return `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  };

  const handleRequirePackage = useCallback(() => {
    if (isGuest) {
      showToast({
        type: "warning",
        title: "Üye Ol Gerekli",
        message: "Paket erişimi yalnızca üyeler içindir. Lütfen giriş yapın.",
      });
    } else {
      router.push("/(tabs)/packages");
    }
  }, [isGuest, showToast]);

  useEffect(() => {
    if (isGuest && !guestToastShown) {
      showToast({
        type: "warning",
        title: "Üye Ol Gerekli",
        message: "Paket özellikleri misafir kullanıcılar için kapalıdır.",
      });
      setGuestToastShown(true);
    }
  }, [isGuest, guestToastShown, showToast]);

  const handleSendMessage = () => {
    if (!hasPackage) {
      handleRequirePackage();
      return;
    }
    if (inputText.trim()) {
      const newMessage = {
        id: generateUniqueId(),
        type: "user",
        text: inputText.trim(),
        userName: userName ?? "Kullanıcı",
        userAvatar: userAvatarSource,
      };

      setMessages((prev) => [...prev, newMessage]);
      setInputText("");

      if (!isChatStarted) setIsChatStarted(true);

      // AI cevabı al
      getLokmaResponse(newMessage.text);
    }
  };

  const handleQuickButtonPress = async (buttonText) => {
    if (!hasPackage) {
      handleRequirePackage();
      return;
    }
    
    const userMessage = {
      id: generateUniqueId(),
      type: "user",
      text: buttonText,
      userName: userName ?? "Kullanıcı",
      userAvatar: userAvatarSource,
    };

    setMessages((prev) => [...prev, userMessage]);
    setIsChatStarted(true);

    // Özel modüller için kontrol
    if (buttonText === "Soru Cevap") {
      await handleChatModalToggle();
    } else if (buttonText === "Günlük egzersizler") {
      router.push("/(tabs)/exercises");
    } else {
      // Normal AI cevabı al
      getLokmaResponse(buttonText);
    }
  };

  // Lokma notification functions
  const startLokmaMode = async () => {
    try {
      setLokmaLoading(true);
      setIsLokmaMode(true);
      setCurrentStep("idle");
      
      // Gıda tiplerini yükle
      const foodTypesResponse = await getFoodTypes();
      setFoodType(foodTypesResponse?.data ?? []);
      
      // İlk soruyu başlat
      const lokmaMessage = {
        id: generateUniqueId(),
        type: "lokma_question",
        text: "Bugün gıdanı israf ettin mi?",
        hasButtons: true,
        buttons: [
          { id: "yes", text: "Evet", selected: false },
          { id: "no", text: "Hayır", selected: false },
        ],
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };
      
      setMessages((prev) => [...prev, lokmaMessage]);
    } catch (error) {
      console.error("Lokma mode loading error:", error);
      const errorMessage = {
        id: generateUniqueId(),
        type: "lokma",
        text: "Lokma bildirimi yüklenirken bir hata oluştu. Lütfen tekrar deneyin.",
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };
      setMessages((prev) => [...prev, errorMessage]);
    } finally {
      setLokmaLoading(false);
    }
  };

  const formatDateForApi = (dateObj) => {
    const pad = (n) => String(n).padStart(2, "0");
    const yyyy = dateObj.getFullYear();
    const MM = pad(dateObj.getMonth() + 1);
    const dd = pad(dateObj.getDate());
    const HH = pad(dateObj.getHours());
    const mm = pad(dateObj.getMinutes());
    const ss = pad(dateObj.getSeconds());
    return `${yyyy}-${MM}-${dd} ${HH}:${mm}:${ss}`;
  };

  const submitLokmaNotification = async ({ isWaste, meal, place, types }) => {
    try {
      const now = new Date();
      const payload = {
        isWaste,
        meal: meal ?? null,
        place: place ?? null,
        date: formatDateForApi(now),
        types: Array.isArray(types) ? types.map((n) => Number(n)) : [],
        foodTypes: Array.isArray(types) ? types.map((n) => Number(n)) : [],
      };
      const response = await saveLokmaNotification(payload);
      return true;
    } catch (e) {
      return false;
    }
  };

  // Survey mode functions
  const startSurveyMode = async () => {
    try {
      setSurveyLoading(true);
      setIsSurveyMode(true);
      
      const response = await surveys();
      if (response?.success && response?.data?.surveys?.[0]) {
        const survey = response.data.surveys[0];
        setCurrentSurvey(survey);
        setCurrentQuestionIndex(0);
        setSurveyAnswers([]);
        setCurrentAnswer(null);
        
      // İlk soruyu chat'e ekle
      const firstQuestion = survey.Questions[0];
      const lokmaMessage = {
        id: generateUniqueId(),
        type: "survey",
        text: firstQuestion?.question ?? "Anket soruları yükleniyor...",
        question: firstQuestion,
        questionIndex: 0,
        totalQuestions: survey.Questions.length,
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };
        
        setMessages((prev) => [...prev, lokmaMessage]);
      } else {
        const errorMessage = {
          id: generateUniqueId(),
          type: "lokma",
          text: "Anket bulunamadı. Lütfen daha sonra tekrar deneyin.",
          lokmaName: "Lokma'm",
          lokmaAvatar: require("@/assets/images/package-lokma.png"),
        };
        setMessages((prev) => [...prev, errorMessage]);
      }
    } catch (error) {
      console.error("Survey loading error:", error);
      const errorMessage = {
        id: generateUniqueId(),
        type: "lokma",
        text: "Anket yüklenirken bir hata oluştu. Lütfen tekrar deneyin.",
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };
      setMessages((prev) => [...prev, errorMessage]);
    } finally {
      setSurveyLoading(false);
    }
  };

  // Exercise mode functions
  const startExerciseMode = async () => {
    try {
      setExerciseLoading(true);
      setIsExerciseMode(true);
      
      const response = await checkExerciseNotification();
      if (response?.success && response?.data?.canStart) {
        const exerciseData = response.data;
        setCurrentExercise(exerciseData);
        
        // Egzersiz sorularını yükle
        const questionsResponse = await getExerciseQuestiom(exerciseData.notification?.id);
        if (questionsResponse?.data) {
          const mappedQuestions = questionsResponse.data.map((q) => ({
            id: q?.id,
            text: q?.question,
            options: (q?.options ?? []).map((o) => ({ 
              id: o?.id, 
              text: o?.option, 
              isTrue: o?.isTrue 
            })),
          }));
          
          setExerciseQuestions(mappedQuestions);
          setCurrentQuestionIdx(0);
          setSelectedAnswer(null);
          setTimeLeft(15);
          
          // İlk soruyu chat'e ekle
          const firstQuestion = mappedQuestions[0];
          const lokmaMessage = {
            id: generateUniqueId(),
            type: "exercise",
            text: firstQuestion?.text ?? "Egzersiz soruları yükleniyor...",
            question: firstQuestion,
            questionIndex: 0,
            totalQuestions: mappedQuestions.length,
            timeLeft: 15,
            lokmaName: "Lokma'm",
            lokmaAvatar: require("@/assets/images/package-lokma.png"),
          };
          
          setMessages((prev) => [...prev, lokmaMessage]);
        }
      } else {
        const reason = response?.data?.reason || "Egzersiz henüz başlatılamaz";
        const lokmaMessage = {
          id: generateUniqueId(),
          type: "lokma",
          text: reason,
          lokmaName: "Lokma'm",
          lokmaAvatar: require("@/assets/images/package-lokma.png"),
        };
        setMessages((prev) => [...prev, lokmaMessage]);
      }
    } catch (error) {
      console.error("Exercise loading error:", error);
      const errorMessage = {
        id: generateUniqueId(),
        type: "lokma",
        text: "Egzersiz yüklenirken bir hata oluştu. Lütfen tekrar deneyin.",
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };
      setMessages((prev) => [...prev, errorMessage]);
    } finally {
      setExerciseLoading(false);
    }
  };

  // Survey continue handler
  const handleSurveyContinue = async () => {
    if (!currentAnswer || !currentSurvey) return;

    // Kullanıcı cevabını ekle
    const userMessage = {
      id: generateUniqueId(),
      type: "user",
      text: currentAnswer,
      userName: userName ?? "Kullanıcı",
      userAvatar: userAvatarSource,
    };
    setMessages((prev) => [...prev, userMessage]);

    // Cevabı kaydet
    const newAnswers = [...surveyAnswers, {
      questionId: currentSurvey.Questions[currentQuestionIndex].id,
      answer: currentAnswer
    }];
    setSurveyAnswers(newAnswers);

    // Sonraki soruya geç
    if (currentQuestionIndex < currentSurvey.Questions.length - 1) {
      const nextQuestionIndex = currentQuestionIndex + 1;
      setCurrentQuestionIndex(nextQuestionIndex);
      setCurrentAnswer(null);

      const nextQuestion = currentSurvey.Questions[nextQuestionIndex];
      const lokmaMessage = {
        id: generateUniqueId(),
        type: "survey",
        text: nextQuestion?.question ?? "Sonraki soru yükleniyor...",
        question: nextQuestion,
        questionIndex: nextQuestionIndex,
        totalQuestions: currentSurvey.Questions.length,
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };
      setMessages((prev) => [...prev, lokmaMessage]);
    } else {
      // Anket tamamlandı
      try {
        const response = await submitSurvey(currentSurvey.id, newAnswers);
        if (response.success) {
          const completionMessage = {
            id: generateUniqueId(),
            type: "lokma",
            text: "Anketiniz başarıyla tamamlandı! Teşekkür ederiz. 🎉",
            lokmaName: "Lokma'm",
            lokmaAvatar: require("@/assets/images/package-lokma.png"),
          };
          setMessages((prev) => [...prev, completionMessage]);
          setIsSurveyMode(false);
          setCurrentSurvey(null);
          setCurrentQuestionIndex(0);
          setSurveyAnswers([]);
          setCurrentAnswer(null);
        } else {
          const errorMessage = {
            id: generateUniqueId(),
            type: "lokma",
            text: "Anket gönderilirken bir hata oluştu. Lütfen tekrar deneyin.",
            lokmaName: "Lokma'm",
            lokmaAvatar: require("@/assets/images/package-lokma.png"),
          };
          setMessages((prev) => [...prev, errorMessage]);
        }
      } catch (error) {
        console.error("Survey submit error:", error);
        const errorMessage = {
          id: generateUniqueId(),
          type: "lokma",
          text: "Anket gönderilirken bir hata oluştu. Lütfen tekrar deneyin.",
          lokmaName: "Lokma'm",
          lokmaAvatar: require("@/assets/images/package-lokma.png"),
        };
        setMessages((prev) => [...prev, errorMessage]);
      }
    }
  };

  // Exercise continue handler
  const handleExerciseContinue = async () => {
    if (!selectedAnswer || !currentExercise) return;

    // Kullanıcı cevabını ekle
    const userMessage = {
      id: generateUniqueId(),
      type: "user",
      text: exerciseQuestions[currentQuestionIdx]?.options?.find(opt => opt.id === selectedAnswer)?.text ?? "Cevap",
      userName: userName ?? "Kullanıcı",
      userAvatar: userAvatarSource,
    };
    setMessages((prev) => [...prev, userMessage]);

    // Sonraki soruya geç
    if (currentQuestionIdx < exerciseQuestions.length - 1) {
      const nextQuestionIdx = currentQuestionIdx + 1;
      setCurrentQuestionIdx(nextQuestionIdx);
      setSelectedAnswer(null);
      setTimeLeft(15);

      const nextQuestion = exerciseQuestions[nextQuestionIdx];
      const lokmaMessage = {
        id: generateUniqueId(),
        type: "exercise",
        text: nextQuestion?.text ?? "Sonraki soru yükleniyor...",
        question: nextQuestion,
        questionIndex: nextQuestionIdx,
        totalQuestions: exerciseQuestions.length,
        timeLeft: 15,
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };
      setMessages((prev) => [...prev, lokmaMessage]);
    } else {
      // Egzersiz tamamlandı
      const completionMessage = {
        id: generateUniqueId(),
        type: "lokma",
        text: "Günlük egzersiziniz başarıyla tamamlandı! Harika çalıştınız! 🎉",
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };
      setMessages((prev) => [...prev, completionMessage]);
      setIsExerciseMode(false);
      setCurrentExercise(null);
      setExerciseQuestions([]);
      setCurrentQuestionIdx(0);
      setSelectedAnswer(null);
      setTimeLeft(15);
    }
  };

  // Lokma button handlers
  const handleLokmaButtonPress = async (messageId, buttonId) => {
    const source = messages.find((m) => m.id === messageId);
    const selectedButton = source?.buttons?.find((b) => b.id === buttonId);
    const selectedText = selectedButton?.text ?? "";

    if (!selectedText) return;

    // Kullanıcı cevabını ekle
    const userMessage = {
      id: generateUniqueId(),
      type: "user",
      text: selectedText,
      userName: userName ?? "Kullanıcı",
      userAvatar: userAvatarSource,
    };
    setMessages((prev) => [...prev, userMessage]);

    // Lokma akışını yönet
    if (currentStep === "idle") {
      if (buttonId === "yes") {
        const mealQuestion = {
          id: generateUniqueId(),
          type: "lokma_question",
          text: "Hangi öğünde gıdanı israf ettin?",
          hasButtons: true,
          buttons: [
            { id: 1, text: "Sabah", selected: false },
            { id: 2, text: "Öğlen", selected: false },
            { id: 3, text: "Akşam", selected: false },
          ],
          lokmaName: "Lokma'm",
          lokmaAvatar: require("@/assets/images/package-lokma.png"),
        };
        setMessages((prev) => [...prev, mealQuestion]);
        setCurrentStep("meal");
      } else {
        // Hayır cevabı - bildirimi kaydet ve kapat
        await submitLokmaNotification({ isWaste: 0, meal: null, place: null, types: [] });
        const closingMessage = {
          id: generateUniqueId(),
          type: "lokma",
          text: "Harika! Gıda israfı yapmadığın için teşekkürler. Seninle her gün yaptığımız bu bilgi paylaşımı sayesinde verilerini senin için 30 günün sonunda sunacağım rapora kayıt ediyorum. 🌱",
          lokmaName: "Lokma'm",
          lokmaAvatar: require("@/assets/images/package-lokma.png"),
        };
        setMessages((prev) => [...prev, closingMessage]);
        setIsLokmaMode(false);
        setCurrentStep("idle");
      }
      return;
    }

    if (currentStep === "meal") {
      setSelectedMealId(buttonId);
      const foodsQuestion = {
        id: generateUniqueId(),
        type: "lokma_question",
        text: "Aşağıdakilerden hangi gıdaları israf ettin? (Birden fazla seçebilirsin)",
        hasCheckboxes: true,
        checkboxes: foodType.map((ft) => ({
          id: String(ft?.id),
          text: ft?.name ?? "",
          checked: false,
        })),
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };
      setMessages((prev) => [...prev, foodsQuestion]);
      setCurrentStep("foods");
      return;
    }

    if (currentStep === "location") {
      await submitLokmaNotification({
        isWaste: 1,
        meal: selectedMealId,
        place: buttonId,
        types: selectedFoodTypeIds,
      });
      const closingMessage = {
        id: generateUniqueId(),
        type: "lokma",
        text: "Teşekkürler! Bu bilgileri kaydettim. Seninle her gün yaptığımız bu bilgi paylaşımı sayesinde verilerini senin için 30 günün sonunda sunacağım rapora kayıt ediyorum. 🌱",
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };
      setMessages((prev) => [...prev, closingMessage]);
      setIsLokmaMode(false);
      setCurrentStep("idle");
      return;
    }
  };

  const handleLokmaCheckboxPress = (messageId, checkboxId) => {
    setMessages((prev) =>
      prev.map((msg) => {
        if (msg.id === messageId && msg.hasCheckboxes) {
          return {
            ...msg,
            checkboxes: msg.checkboxes.map((cb) => ({
              ...cb,
              checked: cb.id === checkboxId ? !cb.checked : cb.checked,
            })),
          };
        }
        return msg;
      })
    );
  };

  const handleLokmaContinuePress = (messageId) => {
    const currentMessage = messages.find((msg) => msg.id === messageId);
    const selectedCheckboxes = currentMessage?.checkboxes?.filter((cb) => cb.checked) || [];
    
    if (selectedCheckboxes.length > 0) {
      const selectedTexts = selectedCheckboxes.map((cb) => cb.text).join(", ");
      const ids = selectedCheckboxes
        .map((cb) => parseInt(cb.id, 10))
        .filter((n) => Number.isFinite(n));
      setSelectedFoodTypeIds(ids);
      
      const userMessage = {
        id: generateUniqueId(),
        type: "user",
        text: selectedTexts,
        userName: userName ?? "Kullanıcı",
        userAvatar: userAvatarSource,
      };
      setMessages((prev) => [...prev, userMessage]);

      const locationQuestion = {
        id: generateUniqueId(),
        type: "lokma_question",
        text: "Gıdanı nerede israf ettin?",
        hasButtons: true,
        buttons: [
          { id: 1, text: "Evde", selected: false },
          { id: 2, text: "İş yerindeki yemekhanede", selected: false },
          { id: 3, text: "Restoran veya Kafede", selected: false },
        ],
        lokmaName: "Lokma'm",
        lokmaAvatar: require("@/assets/images/package-lokma.png"),
      };
      setMessages((prev) => [...prev, locationQuestion]);
      setCurrentStep("location");
    }
  };

  const quickButtons = [
    "Gıda İsrafı Eğitimi",
    "Gıda Saklama Eğitimi",
    "Gıda İsrafı ve Bilinç Eğitimi",
    "Soru Cevap",
    "Gıda Alışverişi Eğitimi",
    "Günlük egzersizler",
  ];

  const renderMessage = ({ item }) => {
    if (item.type === "user") {
      return (
        <View style={styles.userMessageContainer}>
          <View style={styles.userMessageHeader}>
            <Image source={item.userAvatar} style={styles.userAvatar} />
            <Text style={styles.userName}>{item.userName}</Text>
          </View>
          <View style={styles.userBubble}>
            <Text style={styles.userText}>{item.text}</Text>
          </View>
        </View>
      );
    }

    if (item.type === "lokma") {
      return (
        <View style={styles.lokmaMessageContainer}>
          <View style={styles.lokmaMessageHeader}>
            <Image source={item.lokmaAvatar} style={styles.lokmaAvatar} />
            <Text style={styles.lokmaName}>{item.lokmaName}</Text>
          </View>
          <View style={styles.lokmaBubble}>
            <Text style={styles.lokmaText}>{item.text}</Text>
          </View>
        </View>
      );
    }

    if (item.type === "survey") {
      return (
        <View style={styles.lokmaMessageContainer}>
          <View style={styles.lokmaMessageHeader}>
            <Image source={item.lokmaAvatar} style={styles.lokmaAvatar} />
            <Text style={styles.lokmaName}>{item.lokmaName}</Text>
          </View>
          <View style={styles.surveyContainer}>
            <View style={styles.surveyHeader}>
              <Text style={styles.surveyTitle}>Anket Sorusu</Text>
              <Text style={styles.surveyProgress}>
                {item.questionIndex + 1}/{item.totalQuestions}
              </Text>
            </View>
            <View style={styles.surveyBubble}>
              <Text style={styles.surveyText}>{item.text}</Text>
            </View>
            {item.question?.options && (
              <View style={styles.optionsContainer}>
                {item.question.options.map((option, index) => (
                  <TouchableOpacity
                    key={index}
                    style={[
                      styles.optionButton,
                      currentAnswer === option && styles.selectedOptionButton
                    ]}
                    onPress={() => setCurrentAnswer(option)}
                  >
                    <Text style={[
                      styles.optionText,
                      currentAnswer === option && styles.selectedOptionText
                    ]}>
                      {String.fromCharCode(65 + index)}. {option}
                    </Text>
                  </TouchableOpacity>
                ))}
              </View>
            )}
            {currentAnswer && (
              <TouchableOpacity
                style={styles.continueButton}
                onPress={handleSurveyContinue}
              >
                <Text style={styles.continueButtonText}>Devam Et</Text>
              </TouchableOpacity>
            )}
          </View>
        </View>
      );
    }

    if (item.type === "exercise") {
      return (
        <View style={styles.lokmaMessageContainer}>
          <View style={styles.lokmaMessageHeader}>
            <Image source={item.lokmaAvatar} style={styles.lokmaAvatar} />
            <Text style={styles.lokmaName}>{item.lokmaName}</Text>
          </View>
          <View style={styles.exerciseContainer}>
            <View style={styles.exerciseHeader}>
              <Text style={styles.exerciseTitle}>Günlük Egzersiz</Text>
              <View style={styles.exerciseInfo}>
                <Text style={styles.exerciseProgress}>
                  {item.questionIndex + 1}/{item.totalQuestions}
                </Text>
                <View style={styles.timerContainer}>
                  <Ionicons name="time-outline" size={16} color={COLOR_SCALES.primary[80]} />
                  <Text style={styles.timerText}>{item.timeLeft}s</Text>
                </View>
              </View>
            </View>
            <View style={styles.exerciseBubble}>
              <Text style={styles.exerciseText}>{item.text}</Text>
            </View>
            {item.question?.options && (
              <View style={styles.optionsContainer}>
                {item.question.options.map((option, index) => (
                  <TouchableOpacity
                    key={option.id}
                    style={[
                      styles.optionButton,
                      selectedAnswer === option.id && styles.selectedOptionButton
                    ]}
                    onPress={() => setSelectedAnswer(option.id)}
                  >
                    <Text style={[
                      styles.optionText,
                      selectedAnswer === option.id && styles.selectedOptionText
                    ]}>
                      {String.fromCharCode(65 + index)}. {option.text}
                    </Text>
                  </TouchableOpacity>
                ))}
              </View>
            )}
            {selectedAnswer && (
              <TouchableOpacity
                style={styles.continueButton}
                onPress={handleExerciseContinue}
              >
                <Text style={styles.continueButtonText}>Cevabı Gönder</Text>
              </TouchableOpacity>
            )}
          </View>
        </View>
      );
    }

    if (item.type === "lokma_question") {
      return (
        <View style={styles.lokmaMessageContainer}>
          <View style={styles.lokmaMessageHeader}>
            <Image source={item.lokmaAvatar} style={styles.lokmaAvatar} />
            <Text style={styles.lokmaName}>{item.lokmaName}</Text>
          </View>
          <View style={styles.lokmaQuestionContainer}>
            <View style={styles.lokmaQuestionHeader}>
              <Text style={styles.lokmaQuestionTitle}>Lokma Bildirimi</Text>
            </View>
            <View style={styles.lokmaQuestionBubble}>
              <Text style={styles.lokmaQuestionText}>{item.text}</Text>
            </View>
            {item.hasButtons && (
              <View style={styles.lokmaButtonContainer}>
                {item.buttons.map((button) => (
                  <TouchableOpacity
                    key={button.id}
                    style={[
                      styles.lokmaButton,
                      button.selected && styles.selectedLokmaButton
                    ]}
                    onPress={() => handleLokmaButtonPress(item.id, button.id)}
                  >
                    <Text style={[
                      styles.lokmaButtonText,
                      button.selected && styles.selectedLokmaButtonText
                    ]}>
                      {button.text}
                    </Text>
                  </TouchableOpacity>
                ))}
              </View>
            )}
            {item.hasCheckboxes && (
              <View style={styles.lokmaCheckboxContainer}>
                <View style={styles.lokmaCheckboxList}>
                  {item.checkboxes.map((checkbox) => (
                    <TouchableOpacity
                      key={checkbox.id}
                      style={styles.lokmaCheckboxItem}
                      onPress={() => handleLokmaCheckboxPress(item.id, checkbox.id)}
                    >
                      <View style={[
                        styles.lokmaCheckbox,
                        checkbox.checked && styles.checkedLokmaCheckbox
                      ]}>
                        {checkbox.checked && (
                          <Ionicons name="checkmark" size={16} color="#FFFFFF" />
                        )}
                      </View>
                      <Text style={styles.lokmaCheckboxText}>{checkbox.text}</Text>
                    </TouchableOpacity>
                  ))}
                </View>
                <TouchableOpacity
                  style={styles.lokmaContinueButton}
                  onPress={() => handleLokmaContinuePress(item.id)}
                >
                  <Text style={styles.lokmaContinueButtonText}>
                    Devam Et ({item.checkboxes?.filter(cb => cb.checked).length || 0} seçili)
                  </Text>
                </TouchableOpacity>
              </View>
            )}
          </View>
        </View>
      );
    }

    return null;
  };

  return (
    <SafeAreaView style={styles.container}>
      <Toast
        visible={toast?.visible}
        title={toast?.title}
        message={toast?.message}
        type={toast?.type}
        duration={toast?.duration}
        onHide={hideToast}
      />
      {/* Header */}
      <View style={styles.header}>
        <View style={styles.headerContent}>
          <TouchableOpacity style={styles.backButton} onPress={handleBackPress}>
            <Image
              source={require("@/assets/images/icons/back-button.png")}
              style={styles.backButtonIcon}
              resizeMode="contain"
            />
          </TouchableOpacity>

          <TouchableOpacity style={styles.bugunButton}>
            <Text style={styles.bugunText}>Bugün</Text>
          </TouchableOpacity>

          <TouchableOpacity style={styles.bugunYapButton}>
            <Image
              source={require("@/assets/images/logo/logo-small.png")}
              style={styles.logo}
            />
          </TouchableOpacity>
        </View>
      </View>

      {/* Main Content */}
      {isPackageLoading ? (
        <View style={styles.loadingContainer}>
          <Loading size="small" message="Paket durumu kontrol ediliyor..." />
        </View>
      ) : (!hasPackage) ? (
        <ScrollView style={styles.mainContent} showsVerticalScrollIndicator={false}>
          {/* Greeting Section */}
          <View style={styles.greetingSection}>
            <Text style={styles.greetingText}>
              Merhaba!{" "}
              <Text
                style={{
                  fontSize: 24,
                  fontWeight: "700",
                  color: COLOR_SCALES.primary[80],
                }}
              >
                {userName ?? 'Kullanıcı'}
              </Text>
            </Text>
            <Text style={styles.helpText}>Sana nasıl yardımcı olabilirim?</Text>
          </View>

          {/* Lokma Character */}
          <View style={styles.characterSection}>
            <Image
              source={require("@/assets/images/lokma-right.png")}
              style={styles.lokmaCharacter}
              resizeMode="contain"
            />
          </View>

          {/* Quick Buttons */}
          <View style={styles.quickButtonsSection}>
            <View style={styles.quickButtonsGrid}>
              {quickButtons.map((buttonText, index) => (
                <TouchableOpacity
                  key={index}
                  style={[styles.quickButton, !hasPackage && { opacity: 0.6 }]}
                  onPress={() => handleQuickButtonPress(buttonText)}
                  disabled={!hasPackage}
                >
                  <Text style={styles.quickButtonText}>{buttonText}</Text>
                </TouchableOpacity>
              ))}
            </View>
          </View>
          {!hasPackage && (
            <View style={styles.lockBanner}>
              <Text style={styles.lockBannerTitle}>
                {isGuest ? "Lokma sohbeti için üye olmanız gerekiyor" : "Lokma sohbeti için aktif paket gerekli"}
              </Text>
              <Text style={styles.lockBannerDesc}>
                {isGuest
                  ? "Misafir modunda paket avantajlarına erişemezsin. Üye olarak Lokma ile sohbet etmeye başlayabilirsin."
                  : "Paket satın alarak Lokma ile sohbet etmeye başlayabilirsin."}
              </Text>
              {!isGuest && (
                <TouchableOpacity style={styles.lockBannerButton} onPress={handleRequirePackage}>
                  <Text style={styles.lockBannerButtonText}>Paketleri Gör</Text>
                </TouchableOpacity>
              )}
            </View>
          )}
        </ScrollView>
      ) : (!isChatStarted) ? (
        <>
          <ScrollView style={styles.mainContent} showsVerticalScrollIndicator={false}>
            {/* Greeting Section */}
            <View style={styles.greetingSection}>
              <Text style={styles.greetingText}>
                Merhaba!{" "}
                <Text
                  style={{
                    fontSize: 24,
                    fontWeight: "700",
                    color: COLOR_SCALES.primary[80],
                  }}
                >
                  {userName ?? 'Kullanıcı'}
                </Text>
              </Text>
              <Text style={styles.helpText}>Sana nasıl yardımcı olabilirim?</Text>
            </View>

            {/* Lokma Character */}
            <View style={styles.characterSection}>
              <Image
                source={require("@/assets/images/lokma-right.png")}
                style={styles.lokmaCharacter}
                resizeMode="contain"
              />
            </View>

            {/* Quick Buttons */}
            <View style={styles.quickButtonsSection}>
              <View style={styles.quickButtonsGrid}>
                {quickButtons.map((buttonText, index) => (
                  <TouchableOpacity
                    key={index}
                    style={[styles.quickButton, !hasPackage && { opacity: 0.6 }]}
                    onPress={() => handleQuickButtonPress(buttonText)}
                    disabled={!hasPackage}
                  >
                    <Text style={styles.quickButtonText}>{buttonText}</Text>
                  </TouchableOpacity>
                ))}
              </View>
            </View>
          </ScrollView>

          {/* Input Section (Keyboard aware) */}
          <KeyboardAvoidingView
            behavior={Platform.OS === 'ios' ? 'padding' : 'padding'}
            keyboardVerticalOffset={Platform.OS === 'ios' ? 60 : 0}
          >
            <View style={styles.inputSection} onLayout={(e) => setInputHeight(e?.nativeEvent?.layout?.height ?? 72)}>
              <View style={styles.inputContainer}>
                <TextInput
                  style={styles.textInput}
                  placeholder="Mesajınızı yazın..."
                  placeholderTextColor={COLOR_SCALES.gray[40]}
                  value={inputText}
                  onChangeText={setInputText}
                  multiline
                  editable={hasPackage && !isLoading}
                />
                <TouchableOpacity
                  style={[
                    styles.sendButton,
                    (isLoading || !inputText.trim() || !hasPackage) && { opacity: 0.6 },
                  ]}
                  onPress={handleSendMessage}
                  disabled={isLoading || !inputText.trim() || !hasPackage}
                >
                  <Image
                    source={require("@/assets/images/send.png")}
                    style={styles.sendButtonIcon}
                    resizeMode="contain"
                  />
                </TouchableOpacity>
              </View>
            </View>
          </KeyboardAvoidingView>
        </>
      ) : (
        <>
          <View style={[styles.chatContainer, { paddingBottom: 20 + Math.max(insets?.bottom ?? 0, 8) }]}>
            {/* Date Separator */}
            <View style={styles.dateSeparator}>
              <Text style={styles.dateText}>Bugün</Text>
            </View>

            {/* Messages */}
            <FlatList
              data={messages}
              renderItem={renderMessage}
              keyExtractor={(item) => item.id.toString()}
              style={styles.messagesList}
              showsVerticalScrollIndicator={false}
              ref={scrollViewRef}
              onLayout={() => scrollViewRef.current?.scrollToEnd({ animated: false })}
              onContentSizeChange={() => scrollViewRef.current?.scrollToEnd({ animated: true })}
              contentContainerStyle={{ paddingBottom: inputHeight + 24, paddingTop: 8, flexGrow: 1 }}
              keyboardShouldPersistTaps="always"
              keyboardDismissMode="on-drag"
            />
            {(isLoading || surveyLoading || exerciseLoading || lokmaLoading) && (
              <Loading 
                size="small" 
                message={
                  surveyLoading ? "Anket yükleniyor..." :
                  exerciseLoading ? "Egzersiz yükleniyor..." :
                  lokmaLoading ? "Lokma bildirimi yükleniyor..." :
                  "Lokma yazıyor..."
                } 
              />
            )}
          </View>

          {/* Input Section (Keyboard aware) */}
          <KeyboardAvoidingView
            behavior={Platform.OS === 'ios' ? 'padding' : 'padding'}
            keyboardVerticalOffset={Platform.OS === 'ios' ? 60 : 0}
          >
            <View style={styles.inputSection} onLayout={(e) => setInputHeight(e?.nativeEvent?.layout?.height ?? 72)}>
              <View style={styles.inputContainer}>
                <TextInput
                  style={styles.textInput}
                  placeholder="Mesajınızı yazın..."
                  placeholderTextColor={COLOR_SCALES.gray[40]}
                  value={inputText}
                  onChangeText={setInputText}
                  multiline
                  editable={hasPackage && !isLoading}
                />
                <TouchableOpacity
                  style={[
                    styles.sendButton,
                    (isLoading || !inputText.trim() || !hasPackage) && { opacity: 0.6 },
                  ]}
                  onPress={handleSendMessage}
                  disabled={isLoading || !inputText.trim() || !hasPackage}
                >
                  <Image
                    source={require("@/assets/images/send.png")}
                    style={styles.sendButtonIcon}
                    resizeMode="contain"
                  />
                </TouchableOpacity>
              </View>
            </View>
          </KeyboardAvoidingView>
        </>
      )}
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    ...FLEX.fill,
    backgroundColor: "#FFFFFF",
  },
  header: {
    backgroundColor: "#FFFFFF",
    paddingTop: 10,
    paddingBottom: 20,
    borderBottomWidth: 1,
    borderBottomColor: "#F0F0F0",
  },
  headerContent: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 20,
    marginTop: 40,
  },
  backButton: {
    width: 40,
    height: 40,
    alignItems: "center",
    justifyContent: "center",
  },
  backButtonIcon: {
    width: 40,
    height: 40,
  },
  headerCenter: {
    flex: 1,
    alignItems: "center",
  },
  bugunButton: {
    backgroundColor: "#F0F0F0",
    paddingHorizontal: 20,
    paddingVertical: 8,
    borderRadius: 20,
  },
  bugunText: {
    ...title["S/Medium"],
    color: "#666666",
  },
  bugunYapButton: {
    flexDirection: "row",
    alignItems: "center",
  },
  logo: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: "#FF0026",
    borderWidth: 1,
    borderColor: "#fff",
  },
  logoContainer: {
    backgroundColor: "#FF0026",
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 20,
    alignItems: "center",
  },
  logoText: {
    color: "#FFFFFF",
    fontSize: 12,
    fontWeight: "600",
    marginBottom: 2,
  },
  mainContent: {
    flex: 1,
    paddingHorizontal: 20,
  },
  greetingSection: {
    alignItems: "center",
    marginTop: 40,
    marginBottom: 30,
  },
  greetingText: {
    ...paragraph["M/Regular"],
    color: COLOR_SCALES.secondary[100],
    textAlign: "center",
    marginBottom: 8,
  },
  userName: {
    color: COLOR_SCALES.primary[60],
    fontSize: 24,
    fontWeight: "700",
  },
  helpText: {
    ...paragraph["M/Regular"],
    color: COLOR_SCALES.secondary[100],
    textAlign: "center",
  },
  characterSection: {
    alignItems: "center",
    marginBottom: 40,
  },
  lokmaCharacter: {
    width: 100,
    height: 100,
  },
  quickButtonsSection: {
    marginBottom: 40,
  },
  quickButtonsGrid: {
    flexDirection: "row",
    flexWrap: "wrap",
    justifyContent: "space-between",
    gap: 12,
  },
  quickButton: {
    backgroundColor: COLOR_SCALES.white[20],
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderRadius: 20,
    minWidth: "48%",
    alignItems: "center",
    borderWidth: 1,
    borderColor: COLOR_SCALES.gray[20],
  },
  quickButtonText: {
    ...paragraph["S/Medium"],
    color: COLOR_SCALES.gray[100],
    textAlign: "center",
    lineHeight: 18,
  },
  lockBanner: {
    marginHorizontal: 20,
    marginTop: 12,
    padding: 16,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: COLOR_SCALES.primary[60],
    backgroundColor: COLOR_SCALES.primary[10],
    alignItems: "center",
  },
  lockBannerTitle: {
    ...title["S/Bold"],
    color: COLOR_SCALES.primary[80],
    marginBottom: 6,
  },
  lockBannerDesc: {
    ...paragraph["S/Regular"],
    color: COLOR_SCALES.colorGray[80],
    textAlign: "center",
    marginBottom: 10,
  },
  lockBannerButton: {
    paddingHorizontal: 16,
    paddingVertical: 10,
    borderRadius: 20,
    borderWidth: 2,
    borderColor: COLOR_SCALES.primary[80],
    backgroundColor: COLOR_SCALES.white.white,
  },
  lockBannerButtonText: {
    ...title["S/Medium"],
    color: COLOR_SCALES.primary[80],
  },
  inputSection: {
    paddingHorizontal: 20,
    paddingVertical: 16,
    backgroundColor: "#FFFFFF",
    borderTopWidth: 1,
    borderTopColor: COLOR_SCALES.gray[20],
  },
  inputContainer: {
    flexDirection: "row",
    alignItems: "flex-end",
    backgroundColor: "#FFFFFF",
    borderRadius: 32,
    borderWidth: 1,
    borderColor: COLOR_SCALES.primary[100],
    paddingHorizontal: 16,
    paddingBottom: 6,
    paddingTop: 2,
  },
  textInput: {
    flex: 1,
    paddingVertical: 12,
    paddingHorizontal: 8,
    maxHeight: 100,
    fontSize: 14,
    color: COLOR_SCALES.gray[90],
  },
  sendButton: {
    backgroundColor: "#B4001A",
    width: 36,
    height: 36,
    borderRadius: 18,
    alignItems: "center",
    justifyContent: "center",
    marginLeft: 8,
  },
  sendButtonIcon: {
    width: 40,
    height: 40,
  },
  // Chat Styles
  chatContainer: {
    flex: 1,
    backgroundColor: "#FFFFFF",
  },
  loadingContainer: {
    flex: 1,
    backgroundColor: "#FFFFFF",
    alignItems: "center",
    justifyContent: "center",
    paddingHorizontal: 20,
  },
  dateSeparator: {
    alignItems: "center",
    marginVertical: 16,
  },
  dateText: {
    backgroundColor: COLOR_SCALES.gray[20],
    paddingHorizontal: 16,
    paddingVertical: 6,
    borderRadius: 16,
    fontSize: 12,
    color: COLOR_SCALES.gray[60],
  },
  messagesList: {
    flex: 1,
    paddingHorizontal: 16,
  },
  userMessageContainer: {
    alignItems: "flex-end",
    marginBottom: 16,
  },
  userMessageHeader: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 4,
  },
  userAvatar: {
    width: 24,
    height: 24,
    borderRadius: 12,
    marginRight: 8,
  },
  userName: {
    fontSize: 12,
    color: COLOR_SCALES.secondary[100],
    fontWeight: "700",
  },
  userBubble: {
    backgroundColor: COLOR_SCALES.gray[20],
    borderRadius: 16,
    paddingHorizontal: 16,
    paddingVertical: 12,
    maxWidth: "90%",
  },
  userText: {
    color: COLOR_SCALES.gray[90],
    fontSize: 15,
    lineHeight: 22,
    flexShrink: 1,
    flexWrap: "wrap",
  },
  lokmaMessageContainer: {
    alignItems: "flex-start",
    marginBottom: 16,
  },
  lokmaMessageHeader: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 4,
  },
  lokmaAvatar: {
    width: 24,
    height: 24,
    borderRadius: 12,
    marginRight: 8,
  },
  lokmaName: {
    fontSize: 14,
    color: COLOR_SCALES.secondary[100],
    fontWeight: "700",
  },
  lokmaBubble: {
    backgroundColor: COLOR_SCALES.primary[80],
    borderRadius: 16,
    paddingHorizontal: 16,
    paddingVertical: 12,
    maxWidth: "90%",
  },
  lokmaText: {
    color: "#FFFFFF",
    fontSize: 16,
    lineHeight: 24,
    includeFontPadding: false,
    textAlignVertical: "center",
    flexShrink: 1,
    flexWrap: "wrap",
  },
  // Survey styles
  surveyContainer: {
    backgroundColor: "#FFFFFF",
    borderRadius: 16,
    padding: 16,
    marginTop: 8,
    borderWidth: 1,
    borderColor: COLOR_SCALES.primary[60],
  },
  surveyHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 12,
  },
  surveyTitle: {
    ...title["S/Bold"],
    color: COLOR_SCALES.primary[80],
  },
  surveyProgress: {
    ...paragraph["S/Medium"],
    color: COLOR_SCALES.gray[70],
  },
  surveyBubble: {
    backgroundColor: COLOR_SCALES.primary[10],
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
  },
  surveyText: {
    ...paragraph["M/Regular"],
    color: COLOR_SCALES.gray[90],
    lineHeight: 22,
  },
  // Exercise styles
  exerciseContainer: {
    backgroundColor: "#FFFFFF",
    borderRadius: 16,
    padding: 16,
    marginTop: 8,
    borderWidth: 1,
    borderColor: COLOR_SCALES.primary[60],
  },
  exerciseHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 12,
  },
  exerciseTitle: {
    ...title["S/Bold"],
    color: COLOR_SCALES.primary[80],
  },
  exerciseInfo: {
    flexDirection: "row",
    alignItems: "center",
    gap: 12,
  },
  exerciseProgress: {
    ...paragraph["S/Medium"],
    color: COLOR_SCALES.gray[70],
  },
  timerContainer: {
    flexDirection: "row",
    alignItems: "center",
    gap: 4,
  },
  timerText: {
    ...paragraph["S/Medium"],
    color: COLOR_SCALES.primary[80],
  },
  exerciseBubble: {
    backgroundColor: COLOR_SCALES.primary[10],
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
  },
  exerciseText: {
    ...paragraph["M/Regular"],
    color: COLOR_SCALES.gray[90],
    lineHeight: 22,
  },
  // Common option styles
  optionsContainer: {
    marginBottom: 16,
  },
  optionButton: {
    backgroundColor: COLOR_SCALES.white[20],
    borderRadius: 12,
    padding: 12,
    marginBottom: 8,
    borderWidth: 1,
    borderColor: COLOR_SCALES.gray[30],
  },
  selectedOptionButton: {
    backgroundColor: COLOR_SCALES.primary[10],
    borderColor: COLOR_SCALES.primary[60],
    borderWidth: 2,
  },
  optionText: {
    ...paragraph["M/Regular"],
    color: COLOR_SCALES.gray[90],
  },
  selectedOptionText: {
    color: COLOR_SCALES.primary[80],
    fontWeight: "600",
  },
  continueButton: {
    backgroundColor: COLOR_SCALES.primary[80],
    borderRadius: 12,
    padding: 12,
    alignItems: "center",
  },
  continueButtonText: {
    ...title["S/Bold"],
    color: "#FFFFFF",
  },
  // Lokma question styles
  lokmaQuestionContainer: {
    backgroundColor: "#FFFFFF",
    borderRadius: 16,
    padding: 16,
    marginTop: 8,
    borderWidth: 1,
    borderColor: COLOR_SCALES.primary[60],
  },
  lokmaQuestionHeader: {
    marginBottom: 12,
  },
  lokmaQuestionTitle: {
    ...title["S/Bold"],
    color: COLOR_SCALES.primary[80],
  },
  lokmaQuestionBubble: {
    backgroundColor: COLOR_SCALES.primary[10],
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
  },
  lokmaQuestionText: {
    ...paragraph["M/Regular"],
    color: COLOR_SCALES.gray[90],
    lineHeight: 22,
  },
  lokmaButtonContainer: {
    flexDirection: "row",
    flexWrap: "wrap",
    gap: 8,
    marginBottom: 16,
  },
  lokmaButton: {
    backgroundColor: COLOR_SCALES.white[20],
    paddingVertical: 8,
    paddingHorizontal: 16,
    borderRadius: 20,
    borderWidth: 1,
    borderColor: COLOR_SCALES.gray[30],
    alignItems: "center",
  },
  selectedLokmaButton: {
    backgroundColor: COLOR_SCALES.primary[10],
    borderColor: COLOR_SCALES.primary[60],
    borderWidth: 2,
  },
  lokmaButtonText: {
    ...paragraph["M/Regular"],
    color: COLOR_SCALES.gray[90],
  },
  selectedLokmaButtonText: {
    color: COLOR_SCALES.primary[80],
    fontWeight: "600",
  },
  lokmaCheckboxContainer: {
    backgroundColor: "#FFFFFF",
    borderWidth: 1,
    borderColor: COLOR_SCALES.primary[60],
    borderRadius: 8,
    padding: 12,
  },
  lokmaCheckboxList: {
    marginBottom: 12,
  },
  lokmaCheckboxItem: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 8,
  },
  lokmaCheckbox: {
    width: 20,
    height: 20,
    borderRadius: 4,
    alignItems: "center",
    justifyContent: "center",
    marginRight: 12,
    backgroundColor: "#FFFFFF",
    borderWidth: 1,
    borderColor: COLOR_SCALES.primary[60],
  },
  checkedLokmaCheckbox: {
    backgroundColor: COLOR_SCALES.primary[80],
  },
  lokmaCheckboxText: {
    ...paragraph["M/Regular"],
    color: COLOR_SCALES.gray[90],
  },
  lokmaContinueButton: {
    backgroundColor: COLOR_SCALES.primary[80],
    paddingVertical: 8,
    paddingHorizontal: 20,
    borderRadius: 24,
    borderWidth: 2,
    borderColor: COLOR_SCALES.primary[100],
    alignItems: "center",
    shadowColor: "#DB0020",
    shadowOffset: {
      width: 2,
      height: 2,
    },
    shadowOpacity: 1,
    shadowRadius: 0,
    elevation: 4,
  },
  lokmaContinueButtonText: {
    ...title["S/Bold"],
    color: "#FFFFFF",
  },
}); 