import React, { useState, useEffect, useCallback } from 'react';
import {
  View,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Image,
  TextInput,
  ActivityIndicator,
  RefreshControl,
  FlatList,
  Dimensions,
} from 'react-native';

const { width: SCREEN_WIDTH } = Dimensions.get('window');
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { router, useLocalSearchParams } from 'expo-router';
import Text from '@/components/common/Text';
import Button from '@/components/common/Button';
import Empty from '@/components/common/Empty';
import Toast from '@/components/common/Toast';
import useToast from '@/hooks/useToast';
import QrModuleHeader from '@/components/qr-module/QrModuleHeader';
import QrTaskImageGrid from '@/components/qr-module/QrTaskImageGrid';
import { COLOR_SCALES } from '@/theme/colors';
import { paragraph, title } from '@/theme/typography';
import {
  QR_MODULE_STEPS,
  QR_MODULE_INFO,
  QR_MODULE_INTRO_SECTIONS,
  QR_MODULE_REQUIREMENTS,
  QR_MODULE_MOTIVATION,
  QR_PLACEHOLDER_IMAGE,
  SUCCESS_MESSAGE,
} from '@/data/qrModule';
import { scanQr, submitQrTask, getHeroes, reactToHero, getLeaderboard, getQrTasks, getDefaultQr, getQrContents, getQrProperties } from '@/services/qr';

const STEP_LABELS = {
  [QR_MODULE_STEPS.INTRO]: 'Modül',
  [QR_MODULE_STEPS.SCAN]: 'QR Tara',
  [QR_MODULE_STEPS.TASK_SELECT]: 'Seçim',
  [QR_MODULE_STEPS.TASK]: 'Görev',
  [QR_MODULE_STEPS.SUCCESS]: 'Başarı',
  [QR_MODULE_STEPS.LEADERBOARD]: 'Sıralama',
  [QR_MODULE_STEPS.HEROES]: 'Kahramanlar',
};

const FLOW_STEPS = [
  QR_MODULE_STEPS.INTRO,
  QR_MODULE_STEPS.SCAN,
  QR_MODULE_STEPS.TASK_SELECT,
  QR_MODULE_STEPS.TASK,
  QR_MODULE_STEPS.SUCCESS,
];

const QrModuleScreen = () => {
  const insets = useSafeAreaInsets();
  const { toast, showToast, hideToast } = useToast();
  const params = useLocalSearchParams();

  const [step, setStep] = useState(QR_MODULE_STEPS.INTRO);
  const [activeInfoIndex, setActiveInfoIndex] = useState(0);

  // QR & görev state
  const [qrData, setQrData] = useState(null); // { qrId, companyId, time, tasks, scannedAt }
  const [selectedTask, setSelectedTask] = useState(null);
  const [uploadedImages, setUploadedImages] = useState([]);
  const [description, setDescription] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [earnedPoints, setEarnedPoints] = useState(0);

  // Backend'den varsayılan QR'ı yükle (cache yok — uygulama silinse de kalır)
  useEffect(() => {
    const loadDefaultQr = async () => {
      try {
        const res = await getDefaultQr();
        if (res?.success && res?.data?.qrId) {
          setQrData(res.data);
        }
      } catch (e) {
        console.log('getDefaultQr error:', e?.message);
      }
    };
    loadDefaultQr();
  }, []);

  // API'den taze görev durumlarını çek
  const refreshQrData = useCallback(async (showRefreshing = false) => {
    try {
      const qrId = qrData?.qrId;
      if (!qrId) return;
      if (showRefreshing) setIsRefreshing(true);
      const res = await getQrTasks(qrId);
      if (res.success) {
        setQrData((prev) => ({ ...prev, tasks: res.data.tasks }));
      }
    } catch (e) {
      console.log('refreshQrData error:', e?.message);
    } finally {
      if (showRefreshing) setIsRefreshing(false);
    }
  }, [qrData?.qrId]);

  // Kahramanlar & sıralama
  const [heroes, setHeroes] = useState([]);
  const [leaderboard, setLeaderboard] = useState([]);
  const [heroesLoading, setHeroesLoading] = useState(false);
  const [leaderboardLoading, setLeaderboardLoading] = useState(false);
  const [searchName, setSearchName] = useState('');
  const [isRefreshing, setIsRefreshing] = useState(false);

  // Dinamik içerikler
  const [introSections, setIntroSections] = useState(QR_MODULE_INTRO_SECTIONS);
  const [requirements, setRequirements] = useState(QR_MODULE_REQUIREMENTS);

  const scrollBottomPad = 20 + Math.max(insets.bottom, 8);

  // Dinamik intro ve requirements yükle
  useEffect(() => {
    getQrContents().then(res => {
      if (res?.success && res.data?.length) {
        setIntroSections(res.data.map((item, i) => ({
          id: String(item.id ?? i),
          highlight: item.title,
          description: item.description,
        })));
      }
    }).catch(() => {});

    getQrProperties().then(res => {
      if (res?.success && res.data?.length) {
        setRequirements(res.data.map(item => item.title));
      }
    }).catch(() => {});
  }, []);

  const notify = ({ type = 'info', title: t = '', message = '' }) =>
    showToast({ type, title: t, message, duration: 2800 });

  // QR scanner sayfasından dönen qrCode parametresini yakala
  useEffect(() => {
    if (params?.qrCode) {
      handleQrScanned(params.qrCode);
    }
  }, [params?.qrCode]);

  const handleQrScanned = async (qrCode) => {
    try {
      const res = await scanQr(qrCode);
      if (res.success) {
        setQrData(res.data);
        setStep(QR_MODULE_STEPS.TASK_SELECT);
        notify({ type: 'success', title: 'QR Okundu', message: `${res.data.tasks.length} görev yüklendi!` });
      } else {
        notify({ type: 'error', title: 'Hata', message: res.message });
      }
    } catch (e) {
      notify({ type: 'error', title: 'Hata', message: e?.message || 'QR işlenemedi' });
    }
  };

  const loadHeroes = useCallback(async () => {
    setHeroesLoading(true);
    try {
      const res = await getHeroes(qrData?.companyId);
      if (res.success) setHeroes(res.data);
    } catch (e) {
      notify({ type: 'error', title: 'Hata', message: 'Kahramanlar yüklenemedi' });
    } finally {
      setHeroesLoading(false);
    }
  }, [qrData?.companyId]);

  const loadLeaderboard = useCallback(async () => {
    if (!qrData?.companyId) return;
    setLeaderboardLoading(true);
    try {
      const res = await getLeaderboard(qrData.companyId);
      if (res.success) setLeaderboard(res.data);
    } catch (e) {
      notify({ type: 'error', title: 'Hata', message: 'Sıralama yüklenemedi' });
    } finally {
      setLeaderboardLoading(false);
    }
  }, [qrData?.companyId]);

  useEffect(() => {
    if (step === QR_MODULE_STEPS.HEROES) loadHeroes();
    if (step === QR_MODULE_STEPS.LEADERBOARD) loadLeaderboard();
    if (step === QR_MODULE_STEPS.TASK_SELECT && qrData?.qrId) refreshQrData();
  }, [step, qrData?.qrId]);

  const handleBack = () => {
    const backMap = {
      [QR_MODULE_STEPS.SCAN]: QR_MODULE_STEPS.INTRO,
      [QR_MODULE_STEPS.TASK_SELECT]: QR_MODULE_STEPS.SCAN,
      [QR_MODULE_STEPS.TASK]: QR_MODULE_STEPS.TASK_SELECT,
      [QR_MODULE_STEPS.SUCCESS]: QR_MODULE_STEPS.INTRO,
      [QR_MODULE_STEPS.LEADERBOARD]: QR_MODULE_STEPS.INTRO,
      [QR_MODULE_STEPS.HEROES]: QR_MODULE_STEPS.INTRO,
    };
    if (step === QR_MODULE_STEPS.INTRO) { router.back(); return; }
    if (step === QR_MODULE_STEPS.SUCCESS) { setUploadedImages([]); setDescription(''); }
    setStep(backMap[step] ?? QR_MODULE_STEPS.INTRO);
  };

  const handleSelectTask = (task) => {
    setSelectedTask(task);
    setUploadedImages([]);
    setDescription('');
    setStep(QR_MODULE_STEPS.TASK);
  };

  const handleSubmitTask = async () => {
    if (!uploadedImages?.length) {
      notify({ type: 'warning', title: 'Görsel Gerekli', message: 'En az bir fotoğraf yüklemelisiniz.' });
      return;
    }
    setIsSubmitting(true);
    try {
      const res = await submitQrTask({
        qrId: qrData.qrId,
        taskId: selectedTask.id,
        description,
        images: uploadedImages,
      });
      if (res.success) {
        setEarnedPoints(selectedTask?.points ?? 100);
        // Görev listesini local güncelle — status: 0 (bekliyor)
        setQrData((prev) => {
          if (!prev) return prev;
          return {
            ...prev,
            tasks: prev.tasks.map((t) =>
              t.id === selectedTask.id ? { ...t, submissionStatus: 0 } : t
            ),
          };
        });
        setStep(QR_MODULE_STEPS.SUCCESS);
        notify({ type: 'success', title: SUCCESS_MESSAGE, message: 'Admin onayından sonra puan yansıyacak.' });
      } else {
        notify({ type: 'error', title: 'Hata', message: res.message });
      }
    } catch (e) {
      console.error("submitQrTask error:", JSON.stringify(e), e?.message, e?.stack);
      notify({ type: 'error', title: 'Hata', message: e?.message || 'Görev gönderilemedi' });
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleReact = async (heroId, type) => {
    try {
      const res = await reactToHero(heroId, type);
      if (res.success) {
        notify({ type: 'success', title: type === 'heart' ? 'Kutlandı!' : 'İlham Alındı!', message: res.message });
        // Listeyi güncelle
        setHeroes((prev) =>
          prev.map((h) =>
            h.id === heroId
              ? { ...h, hearts: h.hearts + (type === 'heart' ? 1 : 0), leaves: h.leaves + (type === 'leaf' ? 1 : 0) }
              : h
          )
        );
      }
    } catch (e) {
      notify({ type: 'error', title: 'Hata', message: e?.message || 'İşlem başarısız' });
    }
  };

  // ─── RENDER'LAR ────────────────────────────────────────────────────────────

  const renderStepIndicator = () => {
    if ([QR_MODULE_STEPS.LEADERBOARD, QR_MODULE_STEPS.HEROES].includes(step)) return null;
    const currentIndex = FLOW_STEPS.indexOf(step);
    return (
      <View style={styles.stepBar}>
        {FLOW_STEPS.map((s, index) => {
          const isCompleted = index < currentIndex;
          const isCurrent = index === currentIndex;
          return (
            <View key={s} style={styles.stepItem}>
              <View style={[styles.stepDot, isCompleted && styles.stepDotActive, isCurrent && styles.stepDotCurrent]}>
                {isCompleted
                  ? <Ionicons name="checkmark" size={10} color="#fff" />
                  : <Text style={[styles.stepDotText, isCurrent && styles.stepDotTextCurrent]}>{index + 1}</Text>}
              </View>
              {index < FLOW_STEPS.length - 1 && (
                <View style={[styles.stepLine, isCompleted && styles.stepLineActive]} />
              )}
            </View>
          );
        })}
        <Text style={styles.stepLabel}>{STEP_LABELS[step] ?? ''}</Text>
      </View>
    );
  };

  const renderIntro = () => {
    const isUnlocked = !!qrData;
    const doneCount = (qrData?.tasks ?? []).filter((t) => t.submissionStatus !== null).length;
    const approvedCount = (qrData?.tasks ?? []).filter((t) => t.submissionStatus === 1).length;
    const totalCount = qrData?.tasks?.length ?? 0;

    return (
    <ScrollView
      style={styles.scroll}
      contentContainerStyle={[styles.scrollContent, { paddingBottom: scrollBottomPad }]}
      showsVerticalScrollIndicator={false}
      refreshControl={
        isUnlocked ? (
          <RefreshControl
            refreshing={isRefreshing}
            onRefresh={() => refreshQrData(true)}
            colors={[COLOR_SCALES.primary[50]]}
            tintColor={COLOR_SCALES.primary[50]}
          />
        ) : undefined
      }
    >

      {/* Tanıtım kartı — yatay kaydırmalı */}
      <View style={{ marginBottom: 16 }}>
        <FlatList
          data={introSections}
          keyExtractor={(item) => item.id}
          horizontal
          pagingEnabled
          showsHorizontalScrollIndicator={false}
          onMomentumScrollEnd={(e) => {
            const index = Math.round(e.nativeEvent.contentOffset.x / (SCREEN_WIDTH - 32));
            setActiveInfoIndex(index);
          }}
          renderItem={({ item }) => (
            <View style={[styles.introCard, { width: SCREEN_WIDTH - 32, marginBottom: 0 }]}>
              <View style={styles.introAccent} />
              <Text style={styles.introHighlight}>{item.highlight}</Text>
              <Text style={styles.introDescription}>{item.description}</Text>
            </View>
          )}
        />
        <View style={[styles.infoDots, { marginTop: 8 }]}>
          {introSections?.map((s, i) => (
            <View key={s.id} style={[styles.dot, activeInfoIndex === i && styles.dotActive]} />
          ))}
        </View>
      </View>

      {/* Motivasyon */}
      <View style={styles.motivationCard}>
        <Text style={styles.motivationHeadline}>{QR_MODULE_MOTIVATION.headline}</Text>
        <Text style={styles.motivationSubline}>{QR_MODULE_MOTIVATION.subline}</Text>
      </View>

      {/* İstatistikler — QR yoksa statik, varsa dinamik */}
      {isUnlocked ? (
        <View style={styles.statsRow}>
          <View style={styles.statCard}>
            <Ionicons name="list" size={20} color={COLOR_SCALES.primary[50]} />
            <Text style={styles.statValue}>{totalCount}</Text>
            <Text style={styles.statLabel}>Toplam Görev</Text>
          </View>
          <View style={styles.statCard}>
            <Ionicons name="time-outline" size={20} color="#FFA500" />
            <Text style={styles.statValue}>{doneCount - approvedCount}</Text>
            <Text style={styles.statLabel}>Bekliyor</Text>
          </View>
          <View style={styles.statCard}>
            <Ionicons name="checkmark-circle" size={20} color="#2E7D32" />
            <Text style={styles.statValue}>{approvedCount}</Text>
            <Text style={styles.statLabel}>Onaylanan</Text>
          </View>
        </View>
      ) : (
        <View style={styles.statsRow}>
          <View style={styles.statCard}>
            <Ionicons name="list" size={20} color={COLOR_SCALES.primary[50]} />
            <Text style={styles.statValue}>{QR_MODULE_INFO.initialTasks}</Text>
            <Text style={styles.statLabel}>Görev</Text>
          </View>
          <View style={styles.statCard}>
            <Ionicons name="images-outline" size={20} color={COLOR_SCALES.primary[50]} />
            <Text style={styles.statValue}>{QR_MODULE_INFO.maxImagesPerTask}</Text>
            <Text style={styles.statLabel}>Görsel / Görev</Text>
          </View>
          <View style={styles.statCard}>
            <Ionicons name="star" size={20} color={COLOR_SCALES.primary[50]} />
            <Text style={styles.statValue}>{QR_MODULE_INFO.pointsPerTask}</Text>
            <Text style={styles.statLabel}>Puan / Görev</Text>
          </View>
        </View>
      )}

      {/* QR önizleme / aktif durum */}
      {isUnlocked ? (
        <View style={styles.unlockedBanner}>
          <Ionicons name="qr-code" size={28} color={COLOR_SCALES.primary[60]} />
          <View style={{ flex: 1 }}>
            <Text style={styles.unlockedTitle}>Modül Aktif</Text>
            <Text style={styles.unlockedSub}>{totalCount} görev · {qrData?.time ?? 6} ay geçerli</Text>
          </View>
          <View style={styles.unlockedBadge}>
            <Text style={styles.unlockedBadgeText}>✓ Aktif</Text>
          </View>
        </View>
      ) : (
        <View style={styles.qrPreviewCard}>
          <View style={styles.qrImageWrap}>
            <Image source={{ uri: QR_PLACEHOLDER_IMAGE }} style={styles.qrImage} resizeMode="contain" />
          </View>
          <View style={styles.qrPreviewText}>
            <Text style={styles.qrPreviewTitle}>QR ile Yolculuğa Başla</Text>
            <Text style={styles.qrPreviewDesc}>Kutuyu satın alan veya kurumsal QR ile erişen kullanıcılar görevlere ücretsiz başlayabilir.</Text>
          </View>
        </View>
      )}

      {/* Ana butonlar */}
      <View style={styles.actionRow}>
        {isUnlocked ? (
          <Button
            label="Görevlere Git →"
            onPress={() => setStep(QR_MODULE_STEPS.TASK_SELECT)}
            style={styles.flexButton}
          />
        ) : (
       <Button
  label="QR Kod"
  onPress={() => router.push({ pathname: '/qr-scanner', params: { mode: 'qr-module' } })}
  style={[
    styles.flexButton,
    {
      height: 56,
      paddingVertical: 14,
    },
  ]}
/>
        )}
      {isUnlocked ? (
          <>
            {!qrData?.isCorporate && (
              <TouchableOpacity
                style={styles.secondaryBtn}
                onPress={() => setStep(QR_MODULE_STEPS.HEROES)}
                activeOpacity={0.8}
              >
                <Ionicons name="trophy-outline" size={16} color={COLOR_SCALES.primary[60]} />
                <Text style={styles.secondaryBtnText}>Kahramanlar</Text>
              </TouchableOpacity>
            )}
            {qrData?.isCorporate && (
              <TouchableOpacity
                style={styles.secondaryBtn}
                onPress={() => setStep(QR_MODULE_STEPS.LEADERBOARD)}
                activeOpacity={0.8}
              >
                <Ionicons name="podium-outline" size={16} color={COLOR_SCALES.primary[60]} />
                <Text style={styles.secondaryBtnText}>Kurum Sıralaması</Text>
              </TouchableOpacity>
            )}
          </>
        ) : (
          <>
            <TouchableOpacity style={[styles.secondaryBtn, styles.secondaryBtnDisabled]} activeOpacity={1}>
              <Ionicons name="trophy-outline" size={16} color={COLOR_SCALES.colorGray[30]} />
              <Text style={styles.secondaryBtnTextDisabled}>Kahramanlar</Text>
              <Ionicons name="lock-closed" size={12} color={COLOR_SCALES.colorGray[30]} />
            </TouchableOpacity>
          </>
        )}
      </View>

      {/* Başka QR okut — mevcut varsayılanı değiştirmek için */}
      {isUnlocked && (
        <TouchableOpacity
          style={styles.rescanBtn}
          onPress={() => router.push({ pathname: '/qr-scanner', params: { mode: 'qr-module' } })}
          activeOpacity={0.8}
        >
          <Ionicons name="scan-outline" size={18} color={COLOR_SCALES.primary[60]} />
          <Text style={styles.rescanBtnText}>Başka QR Okut</Text>
        </TouchableOpacity>
      )}

      {/* Özellikler */}
      <View style={styles.requirementsCard}>
        <View style={styles.requirementsHeader}>
          <Ionicons name="shield-checkmark" size={20} color={COLOR_SCALES.primary[60]} />
          <Text style={styles.requirementsTitle}>Modül Özellikleri</Text>
        </View>
        {requirements?.map((item, i) => (
          <View key={i} style={styles.requirementRow}>
            <Ionicons name="checkmark-circle" size={18} color={COLOR_SCALES.primary[50]} />
            <Text style={styles.requirementText}>{item}</Text>
          </View>
        ))}
      </View>
    </ScrollView>
  );
  };

  const renderTaskSelect = () => (
    <ScrollView
      style={styles.scroll}
      contentContainerStyle={[styles.scrollContent, { paddingBottom: scrollBottomPad }]}
      showsVerticalScrollIndicator={false}
      refreshControl={
        <RefreshControl
          refreshing={isRefreshing}
          onRefresh={() => refreshQrData(true)}
          colors={[COLOR_SCALES.primary[50]]}
          tintColor={COLOR_SCALES.primary[50]}
        />
      }
    >
      <Image source={require('@/assets/images/badem.png')} style={styles.selectMascot} resizeMode="contain" />
      <Text style={styles.motivationHeadline}>{QR_MODULE_MOTIVATION.headline}</Text>
      <Text style={styles.motivationSubline}>{QR_MODULE_MOTIVATION.subline}</Text>

      <View style={styles.qrInfoBadge}>
        <Ionicons name="qr-code" size={16} color={COLOR_SCALES.primary[60]} />
        <Text style={styles.qrInfoText}>{qrData?.tasks?.length ?? 0} görev · {qrData?.time ?? 6} ay süre</Text>
      </View>

      <Text style={styles.sectionTitle}>Görevler</Text>
      <View style={styles.tasksGrid}>
        {(qrData?.tasks ?? []).map((task) => {
          const imageUri = task.image || null;
          console.log('task:', task.id, 'image raw:', JSON.stringify(task.image));
          const isSubmitted = task.submissionStatus !== null;
          const isApproved = task.submissionStatus === 1;
          return (
            <TouchableOpacity
              key={task.id}
              style={[styles.taskCard, selectedTask?.id === task.id && styles.taskCardActive, isSubmitted && styles.taskCardDone]}
              onPress={() => !isApproved && handleSelectTask(task)}
              activeOpacity={0.85}
              disabled={isApproved}
            >
              {imageUri ? (
                <Image source={{ uri: task.image }} style={styles.taskCardImage} resizeMode="cover" onError={() => console.log('Image load failed:', task.image)} />
              ) : (
                <View style={[styles.taskCardImage, { backgroundColor: COLOR_SCALES.primary[10], alignItems: 'center', justifyContent: 'center' }]}>
                  <Ionicons name="leaf-outline" size={32} color={COLOR_SCALES.primary[50]} />
                </View>
              )}
              <View style={styles.taskCardBody}>
                <Text style={styles.taskCardTitle} numberOfLines={3}>{task.title}</Text>
                <View style={styles.taskCardFooter}>
                  <Text style={styles.taskPoints}>{task.points ?? 100} puan</Text>
                  {isApproved && <Ionicons name="checkmark-circle" size={16} color="#2E7D32" />}
                  {task.submissionStatus === 0 && <Ionicons name="time-outline" size={16} color="#FFA500" />}
                </View>
              </View>
            </TouchableOpacity>
          );
        })}
      </View>
    </ScrollView>
  );

  const renderTask = () => {
    const status = selectedTask?.submissionStatus;
    const BASE_URL = 'https://api.bugunyap.com:1910';

    // Gönderilmiş ama reddedilmemiş → detay görünümü
    if (status === 0 || status === 1) {
      const images = selectedTask?.submissionImages ?? [];
      const desc = selectedTask?.submissionDescription;
      const statusColor = status === 1 ? '#2E7D32' : '#FFA500';
      const statusLabel = status === 1 ? '✓ Onaylandı' : '⏳ Onay Bekliyor';

      return (
        <ScrollView style={styles.scroll} contentContainerStyle={[styles.scrollContent, { paddingBottom: scrollBottomPad }]} showsVerticalScrollIndicator={false}>
          <View style={styles.taskHeaderRow}>
            {selectedTask?.image
              ? <Image source={{ uri: selectedTask.image }} style={styles.taskIcon} resizeMode="cover" />
              : <View style={[styles.taskIcon, { backgroundColor: COLOR_SCALES.primary[20], alignItems: 'center', justifyContent: 'center' }]}><Ionicons name="leaf-outline" size={24} color={COLOR_SCALES.primary[60]} /></View>
            }
            <Text style={styles.taskTitle}>{selectedTask?.title ?? ''}</Text>
          </View>

          {/* Durum badge */}
          <View style={[styles.statusBanner, { backgroundColor: statusColor + '18', borderColor: statusColor }]}>
            <Text style={[styles.statusBannerText, { color: statusColor }]}>{statusLabel}</Text>
            {status === 1 && <Text style={[styles.statusBannerPts, { color: statusColor }]}>{selectedTask?.earnedPoints ?? 0} puan kazandın</Text>}
          </View>

          {/* Açıklama */}
          {desc ? (
            <View style={styles.submissionDescBox}>
              <Text style={styles.submissionDescLabel}>Açıklaman</Text>
              <Text style={styles.submissionDescText}>{desc}</Text>
            </View>
          ) : null}

          {/* Görseller */}
          {images.length > 0 && (
            <View style={styles.submissionImagesBox}>
              <Text style={styles.submissionDescLabel}>Yüklediğin Görseller</Text>
              <View style={styles.submissionImagesGrid}>
                {images.map((img, i) => (
                  <Image
                    key={i}
                    source={{ uri: img.startsWith('http') ? img : `${BASE_URL}${img}` }}
                    style={styles.submissionThumb}
                    resizeMode="cover"
                  />
                ))}
              </View>
            </View>
          )}
        </ScrollView>
      );
    }

    // Reddedildi veya hiç gönderilmemiş → form
    return (
    <ScrollView style={styles.scroll} contentContainerStyle={[styles.scrollContent, { paddingBottom: scrollBottomPad }]} showsVerticalScrollIndicator={false}>
      <View style={styles.taskHeaderRow}>
        {selectedTask?.image
          ? <Image source={{ uri: selectedTask.image }} style={styles.taskIcon} resizeMode="cover" />
          : <View style={[styles.taskIcon, { backgroundColor: COLOR_SCALES.primary[20], alignItems: 'center', justifyContent: 'center' }]}><Ionicons name="leaf-outline" size={24} color={COLOR_SCALES.primary[60]} /></View>
        }
        <Text style={styles.taskTitle}>{selectedTask?.title ?? ''}</Text>
      </View>

      {/* Reddedildi uyarısı */}
      {status === 2 && (
        <View style={[styles.statusBanner, { backgroundColor: '#FFF0F0', borderColor: COLOR_SCALES.helper.red }]}>
          <Text style={[styles.statusBannerText, { color: COLOR_SCALES.helper.red }]}>✗ Reddedildi — Yeniden gönderebilirsin</Text>
        </View>
      )}

      <Text style={styles.taskDescription}>{selectedTask?.description ?? ''}</Text>

      <View style={styles.inputGroup}>
        <Text style={styles.inputLabel}>Açıklama (opsiyonel)</Text>
        <View style={[styles.inputWrap, { minHeight: 80, alignItems: 'flex-start', paddingVertical: 10 }]}>
          <TextInput
            style={[styles.input, { textAlignVertical: 'top' }]}
            placeholder="Ne yaptığınızı kısaca anlatın..."
            placeholderTextColor={COLOR_SCALES.colorGray[40]}
            value={description}
            onChangeText={setDescription}
            multiline
            numberOfLines={3}
          />
        </View>
      </View>

      <QrTaskImageGrid
        images={uploadedImages}
        onChange={setUploadedImages}
        onShowToast={notify}
        showBinArea={false}
      />

      <Button
        label={isSubmitting ? 'Gönderiliyor...' : 'Görevi Tamamla'}
        onPress={handleSubmitTask}
        disabled={!uploadedImages?.length || isSubmitting}
        style={styles.submitButton}
      />
    </ScrollView>
    );
  };

  const renderSuccess = () => (
    <ScrollView style={styles.scroll} contentContainerStyle={[styles.successContainer, { paddingBottom: scrollBottomPad }]} showsVerticalScrollIndicator={false}>
      <View style={styles.successCard}>
        <View style={styles.successIconRing}>
          <Image source={require('@/assets/images/badem.png')} style={styles.mascot} resizeMode="contain" />
        </View>
        <Text style={styles.successMessage}>{SUCCESS_MESSAGE}</Text>
        <View style={styles.pointsBadge}>
          <Ionicons name="star" size={20} color="#fff" />
          <Text style={styles.pointsValue}>{earnedPoints}</Text>
          <Text style={styles.pointsLabel}>puan (onay bekliyor)</Text>
        </View>
        {uploadedImages?.length > 0 && (
          <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.successImages}>
            {uploadedImages.map((uri, i) => (
              <Image key={i} source={{ uri }} style={styles.successThumb} resizeMode="cover" />
            ))}
          </ScrollView>
        )}
        <Text style={styles.successNote}>Görselleriniz onaylandıktan sonra puanlarınız hesabınıza yansıyacaktır.</Text>
      </View>
      <Button label="Yeni Göreve Başla" onPress={() => { setUploadedImages([]); setDescription(''); setStep(QR_MODULE_STEPS.TASK_SELECT); }} style={styles.successButton} />
      <Button label="Ana Sayfaya Dön" variant="secondary" onPress={() => { setUploadedImages([]); setDescription(''); setStep(QR_MODULE_STEPS.INTRO); }} style={styles.successButton} />
    </ScrollView>
  );

  const renderHeroes = () => (
    <ScrollView style={styles.scroll} contentContainerStyle={[styles.scrollContent, { paddingBottom: scrollBottomPad }]} showsVerticalScrollIndicator={false}>
      <View style={styles.heroesHeader}>
        <Image source={require('@/assets/images/badem.png')} style={styles.heroesMascot} resizeMode="contain" />
        <View>
          <Text style={styles.heroesTitle}>Gıda Kahramanları</Text>
          <Text style={styles.heroesSubtitle}>Birlikte fark yaratıyoruz</Text>
        </View>
      </View>

      {heroesLoading
        ? <ActivityIndicator color={COLOR_SCALES.primary[50]} style={{ marginTop: 40 }} />
        : heroes.length === 0
          ? <Empty title="Henüz kahraman yok" description="İlk görevi tamamlayan sen ol!" fullscreen={false} icon={<Ionicons name="trophy-outline" size={48} color={COLOR_SCALES.colorGray[40]} />} />
          : heroes.map((hero) => (
            <View key={hero.id} style={styles.heroCard}>
             {hero.profileImage ? (
  <Image
    source={{
      uri:
        hero.profileImage === "default.png"
          ? "https://api.bugunyap.com:1910/uploads/profile/default.png"
          : `https://panel.bugunyap.com/uploads/profile/${hero.profileImage}`,
    }}
    style={styles.heroAvatar}
    resizeMode="cover"
  />
) : (
  <View
    style={[
      styles.heroAvatar,
      {
        backgroundColor: COLOR_SCALES.primary[20],
        alignItems: "center",
        justifyContent: "center",
      },
    ]}
  >
    <Ionicons
      name="person"
      size={22}
      color={COLOR_SCALES.primary[60]}
    />
  </View>
)}
              <View style={styles.heroInfo}>
                <Text style={styles.heroName}>{hero.name || 'Kullanıcı'}</Text>
                <View style={styles.heroStats}>
                  <Ionicons name="heart" size={14} color={COLOR_SCALES.primary[50]} />
                  <Text style={styles.heroStatText}>{hero.hearts}</Text>
                  <Ionicons name="leaf" size={14} color="#2E7D32" style={{ marginLeft: 6 }} />
                  <Text style={styles.heroStatText}>{hero.leaves}</Text>
                </View>
              </View>
              <View style={styles.heroRight}>
                <View style={styles.heroPoints}>
                  <Ionicons name="trophy" size={14} color={COLOR_SCALES.primary[60]} />
                  <Text style={styles.heroPointsText}>{hero.points}</Text>
                </View>
                <View style={styles.heroActions}>
                  <TouchableOpacity style={styles.celebrateBtn} onPress={() => handleReact(hero.id, 'heart')} activeOpacity={0.8}>
                    <Ionicons name="heart" size={12} color="#fff" />
                    <Text style={styles.heroBtnText}>Kutla</Text>
                  </TouchableOpacity>
                  <TouchableOpacity style={styles.inspiredBtn} onPress={() => handleReact(hero.id, 'leaf')} activeOpacity={0.8}>
                    <Ionicons name="leaf" size={12} color="#fff" />
                    <Text style={styles.heroBtnText}>İlham Aldım</Text>
                  </TouchableOpacity>
                </View>
              </View>
            </View>
          ))
      }
    </ScrollView>
  );

  const renderLeaderboard = () => {
    const filtered = searchName?.trim()
      ? leaderboard.filter((item) => item?.name?.toLowerCase().includes(searchName.trim().toLowerCase()))
      : leaderboard;

    return (
      <ScrollView style={styles.scroll} contentContainerStyle={[styles.scrollContent, { paddingBottom: scrollBottomPad }]} showsVerticalScrollIndicator={false}>
        <View style={styles.leaderboardHeader}>
          <Ionicons name="trophy" size={28} color={COLOR_SCALES.primary[50]} />
          <Text style={styles.leaderboardTitle}>Kurum Sıralaması</Text>
        </View>

        <View style={styles.inputGroup}>
          <View style={styles.inputWrap}>
            <Ionicons name="search-outline" size={18} color={COLOR_SCALES.colorGray[50]} style={styles.inputIcon} />
            <TextInput
              style={styles.input}
              placeholder="İsim ara..."
              placeholderTextColor={COLOR_SCALES.colorGray[40]}
              value={searchName}
              onChangeText={setSearchName}
            />
          </View>
        </View>

        {leaderboardLoading
          ? <ActivityIndicator color={COLOR_SCALES.primary[50]} style={{ marginTop: 40 }} />
          : filtered.length === 0
            ? <Empty title="Sıralama Bulunamadı" description="Henüz onaylı görev yok." fullscreen={false} icon={<Ionicons name="trophy-outline" size={48} color={COLOR_SCALES.colorGray[40]} />} />
            : filtered.map((item, i) => (
              <View key={item.id} style={[styles.heroCard, i < 3 && styles.leaderboardRowTop]}>
                {/* Sıra + Avatar */}
                <View style={[styles.rankBadge, i === 0 && styles.rankGold, i === 1 && styles.rankSilver, i === 2 && styles.rankBronze, { marginRight: 8 }]}>
                  <Text style={styles.rankText}>{i + 1}</Text>
                </View>
               {item.profileImage ? (
  <Image
    source={{
      uri:
        item.profileImage === "default.png"
          ? "https://api.bugunyap.com:1910/uploads/profile/default.png"
          : item.profileImage,
    }}
    style={styles.heroAvatar}
    resizeMode="cover"
  />
) : (
  <View
    style={[
      styles.heroAvatar,
      {
        backgroundColor: COLOR_SCALES.primary[20],
        alignItems: "center",
        justifyContent: "center",
      },
    ]}
  >
    <Ionicons
      name="person"
      size={20}
      color={COLOR_SCALES.primary[60]}
    />
  </View>
)}
                {/* Bilgi */}
                <View style={styles.heroInfo}>
                  <Text style={styles.heroName}>{item.name || 'Kullanıcı'}</Text>
                  <View style={styles.heroStats}>
                    <Ionicons name="heart" size={13} color={COLOR_SCALES.primary[50]} />
                    <Text style={styles.heroStatText}>{item.hearts ?? 0}</Text>
                    <Ionicons name="leaf" size={13} color="#2E7D32" style={{ marginLeft: 6 }} />
                    <Text style={styles.heroStatText}>{item.leaves ?? 0}</Text>
                  </View>
                </View>
                {/* Sağ: puan + butonlar */}
                <View style={styles.heroRight}>
                  <View style={styles.heroPoints}>
                    <Ionicons name="trophy" size={13} color={COLOR_SCALES.primary[60]} />
                    <Text style={styles.heroPointsText}>{item.points}</Text>
                  </View>
                  <View style={styles.heroActions}>
                    <TouchableOpacity style={styles.celebrateBtn} onPress={() => handleReact(item.id, 'heart')} activeOpacity={0.8}>
                      <Ionicons name="heart" size={11} color="#fff" />
                      <Text style={styles.heroBtnText}>Kutla</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.inspiredBtn} onPress={() => handleReact(item.id, 'leaf')} activeOpacity={0.8}>
                      <Ionicons name="leaf" size={11} color="#fff" />
                      <Text style={styles.heroBtnText}>İlham Aldım</Text>
                    </TouchableOpacity>
                  </View>
                </View>
              </View>
            ))
        }
      </ScrollView>
    );
  };

  const renderContent = () => {
    switch (step) {
      case QR_MODULE_STEPS.TASK_SELECT: return renderTaskSelect();
      case QR_MODULE_STEPS.TASK: return renderTask();
      case QR_MODULE_STEPS.SUCCESS: return renderSuccess();
      case QR_MODULE_STEPS.LEADERBOARD: return renderLeaderboard();
      case QR_MODULE_STEPS.HEROES: return renderHeroes();
      default: return renderIntro();
    }
  };

  const headerTitle =
    step === QR_MODULE_STEPS.HEROES ? 'Gıda Kahramanları' :
    step === QR_MODULE_STEPS.TASK_SELECT ? 'Seçimini Yap' :
    QR_MODULE_INFO.title;

  return (
    <View style={styles.container}>
      <SafeAreaView style={styles.safeTop} edges={['top', 'left', 'right']}>
        <QrModuleHeader onBack={handleBack} showBadge={step === QR_MODULE_STEPS.INTRO} title={headerTitle} />
        {renderStepIndicator()}
        <View style={styles.content}>{renderContent()}</View>
      </SafeAreaView>
      <Toast visible={toast?.visible} title={toast?.title} message={toast?.message} type={toast?.type} duration={toast?.duration} onHide={hideToast} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: COLOR_SCALES.white.white },
  safeTop: { flex: 1 },
  content: { flex: 1 },
  scroll: { flex: 1 },
  scrollContent: { padding: 16 },
  stepBar: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 20, paddingVertical: 10, backgroundColor: COLOR_SCALES.primary[10], borderBottomWidth: 1, borderBottomColor: COLOR_SCALES.primary[20] },
  stepItem: { flexDirection: 'row', alignItems: 'center' },
  stepDot: { width: 22, height: 22, borderRadius: 11, backgroundColor: COLOR_SCALES.colorGray[30], alignItems: 'center', justifyContent: 'center' },
  stepDotActive: { backgroundColor: COLOR_SCALES.primary[50] },
  stepDotCurrent: { backgroundColor: COLOR_SCALES.primary[70], transform: [{ scale: 1.1 }] },
  stepDotText: { ...paragraph['XS/Bold'], color: COLOR_SCALES.colorGray[60], fontSize: 10 },
  stepDotTextCurrent: { color: '#fff' },
  stepLine: { width: 18, height: 2, backgroundColor: COLOR_SCALES.colorGray[30], marginHorizontal: 2 },
  stepLineActive: { backgroundColor: COLOR_SCALES.primary[40] },
  stepLabel: { ...paragraph['XS/Medium'], color: COLOR_SCALES.primary[70], marginLeft: 10 },

  // Intro
  introCard: { backgroundColor: '#fff', borderRadius: 16, padding: 16, marginBottom: 16, borderWidth: 1, borderColor: COLOR_SCALES.colorGray[20], overflow: 'hidden', shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.06, shadowRadius: 8, elevation: 2 },
  introAccent: { position: 'absolute', left: 0, top: 0, bottom: 0, width: 4, backgroundColor: COLOR_SCALES.primary[60] },
  introHighlight: { ...title['M/Bold'], color: COLOR_SCALES.primary[70], marginBottom: 8, paddingLeft: 8 },
  introDescription: { ...paragraph['S/Regular'], color: COLOR_SCALES.colorGray[80], lineHeight: 22, paddingLeft: 8 },
  infoDots: { flexDirection: 'row', justifyContent: 'center', gap: 6, marginTop: 16 },
  dot: { width: 8, height: 8, borderRadius: 4, backgroundColor: COLOR_SCALES.colorGray[30] },
  dotActive: { backgroundColor: COLOR_SCALES.primary[50], width: 20 },
  motivationCard: { backgroundColor: COLOR_SCALES.primary[10], borderRadius: 14, padding: 14, marginBottom: 16, borderLeftWidth: 4, borderLeftColor: COLOR_SCALES.primary[50] },
  motivationHeadline: { ...paragraph['M/Bold'], color: COLOR_SCALES.primary[80], marginBottom: 4 },
  motivationSubline: { ...paragraph['S/Regular'], color: COLOR_SCALES.colorGray[70], lineHeight: 20 },
  statsRow: { flexDirection: 'row', gap: 10, marginBottom: 16 },
  statCard: { flex: 1, backgroundColor: COLOR_SCALES.primary[10], borderRadius: 14, padding: 12, alignItems: 'center', borderWidth: 1, borderColor: COLOR_SCALES.primary[20] },
  statValue: { ...title['L/Bold'], color: COLOR_SCALES.primary[70], marginTop: 4 },
  statLabel: { ...paragraph['XS/Regular'], color: COLOR_SCALES.colorGray[70], textAlign: 'center', marginTop: 2 },
  qrPreviewCard: { flexDirection: 'row', backgroundColor: COLOR_SCALES.colorGray[10], borderRadius: 14, padding: 14, marginBottom: 16, alignItems: 'center', gap: 12, borderWidth: 1, borderColor: COLOR_SCALES.colorGray[20] },
  qrImageWrap: { backgroundColor: '#fff', borderRadius: 10, padding: 6 },
  qrImage: { width: 72, height: 72 },
  qrPreviewText: { flex: 1 },
  qrPreviewTitle: { ...paragraph['M/Bold'], color: COLOR_SCALES.colorGray[90], marginBottom: 4 },
  qrPreviewDesc: { ...paragraph['XS/Regular'], color: COLOR_SCALES.colorGray[60], lineHeight: 18 },
  actionRow: { flexDirection: 'row', gap: 10, marginBottom: 12, alignItems: 'stretch' },
  flexButton: { flex: 1},
  fullButton: { marginBottom: 16 },

  // Unlocked banner
  unlockedBanner: { flexDirection: 'row', alignItems: 'center', gap: 12, backgroundColor: '#E8F5E9', borderRadius: 14, padding: 14, marginBottom: 16, borderWidth: 1, borderColor: '#A5D6A7' },
  unlockedTitle: { ...paragraph['M/Bold'], color: '#2E7D32' },
  unlockedSub: { ...paragraph['XS/Regular'], color: '#4CAF50', marginTop: 2 },
  unlockedBadge: { backgroundColor: '#2E7D32', paddingHorizontal: 10, paddingVertical: 4, borderRadius: 20 },
  unlockedBadgeText: { ...paragraph['XS/Bold'], color: '#fff' },

  rescanBtn: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 8,
    borderWidth: 1.5,
    borderColor: COLOR_SCALES.primary[40],
    borderRadius: 12,
    paddingVertical: 12,
    marginBottom: 16,
    backgroundColor: '#fff',
  },
  rescanBtnText: { ...paragraph['S/Medium'], color: COLOR_SCALES.primary[60] },

  // Secondary button (Kahramanlar)
  secondaryBtn: { flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 6, borderWidth: 1.5, borderColor: COLOR_SCALES.primary[40], borderRadius: 12, paddingVertical: 12, paddingHorizontal: 10, backgroundColor: '#fff' },
  secondaryBtnDisabled: { borderColor: COLOR_SCALES.colorGray[20], backgroundColor: COLOR_SCALES.colorGray[10] },
  secondaryBtnText: { ...paragraph['S/Medium'], color: COLOR_SCALES.primary[60] },
  secondaryBtnTextDisabled: { color: COLOR_SCALES.colorGray[30] },

  // Leaderboard button
  leaderboardBtn: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 8, borderWidth: 1.5, borderColor: COLOR_SCALES.primary[40], borderRadius: 12, paddingVertical: 12, marginBottom: 16, backgroundColor: '#fff' },
  leaderboardBtnDisabled: { borderColor: COLOR_SCALES.colorGray[20], backgroundColor: COLOR_SCALES.colorGray[10] },
  leaderboardBtnText: { ...paragraph['S/Medium'], color: COLOR_SCALES.primary[60] },
  leaderboardBtnTextDisabled: { color: COLOR_SCALES.colorGray[30] },
  requirementsCard: { backgroundColor: COLOR_SCALES.colorGray[10], borderRadius: 14, padding: 14, marginBottom: 16, borderWidth: 1, borderColor: COLOR_SCALES.colorGray[20] },
  requirementsHeader: { flexDirection: 'row', alignItems: 'center', gap: 8, marginBottom: 10 },
  requirementsTitle: { ...paragraph['M/Bold'], color: COLOR_SCALES.colorGray[90] },
  requirementRow: { flexDirection: 'row', alignItems: 'flex-start', gap: 8, marginBottom: 8 },
  requirementText: { ...paragraph['XS/Regular'], color: COLOR_SCALES.colorGray[70], flex: 1, lineHeight: 18 },

  // Task select
  selectMascot: { width: 72, height: 72, alignSelf: 'center', marginBottom: 12 },
  qrInfoBadge: { flexDirection: 'row', alignItems: 'center', gap: 8, alignSelf: 'center', backgroundColor: COLOR_SCALES.primary[10], paddingHorizontal: 14, paddingVertical: 8, borderRadius: 20, marginVertical: 14 },
  qrInfoText: { ...paragraph['XS/Medium'], color: COLOR_SCALES.primary[70] },
  sectionTitle: { ...paragraph['M/Bold'], color: COLOR_SCALES.colorGray[90], marginBottom: 12 },
  tasksGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: 12 },
  taskCard: { width: '47%', borderRadius: 14, overflow: 'hidden', backgroundColor: '#fff', borderWidth: 1, borderColor: COLOR_SCALES.colorGray[20] },
  taskCardActive: { borderColor: COLOR_SCALES.primary[50], borderWidth: 2 },
  taskCardDone: { opacity: 0.7 },
  taskCardImage: { width: '100%', height: 90 },
  taskCardBody: { padding: 10 },
  taskCardTitle: { ...paragraph['XS/Medium'], color: COLOR_SCALES.colorGray[80], lineHeight: 16, marginBottom: 8 },
  taskCardFooter: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
  taskPoints: { ...paragraph['XS/Bold'], color: COLOR_SCALES.primary[60] },

  // Task
  taskHeaderRow: { flexDirection: 'row', alignItems: 'center', gap: 12, marginBottom: 12 },
  taskIcon: { width: 48, height: 48, borderRadius: 24, borderWidth: 2, borderColor: COLOR_SCALES.primary[30] },
  taskTitle: { ...paragraph['M/Bold'], color: COLOR_SCALES.colorGray[90], flex: 1, lineHeight: 22 },
  taskDescription: { ...paragraph['S/Regular'], color: COLOR_SCALES.colorGray[80], lineHeight: 22, marginBottom: 12 },
  inputGroup: { marginBottom: 16 },
  inputLabel: { ...paragraph['S/Medium'], color: COLOR_SCALES.colorGray[80], marginBottom: 6 },
  inputWrap: { flexDirection: 'row', alignItems: 'center', borderWidth: 1, borderColor: COLOR_SCALES.colorGray[20], borderRadius: 12, backgroundColor: '#fff', paddingHorizontal: 12 },
  inputIcon: { marginRight: 8 },
  input: { flex: 1, paddingVertical: 12, ...paragraph['S/Regular'], color: COLOR_SCALES.colorGray[90] },
  submitButton: { marginTop: 20 },

  // Submission detay
  statusBanner: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', borderWidth: 1, borderRadius: 12, padding: 12, marginBottom: 16 },
  statusBannerText: { fontWeight: '700', fontSize: 14 },
  statusBannerPts: { fontSize: 13, fontWeight: '600' },
  submissionDescBox: { backgroundColor: COLOR_SCALES.colorGray[10], borderRadius: 12, padding: 12, marginBottom: 16 },
  submissionDescLabel: { ...paragraph['XS/Medium'], color: COLOR_SCALES.colorGray[60], marginBottom: 6 },
  submissionDescText: { ...paragraph['S/Regular'], color: COLOR_SCALES.colorGray[90], lineHeight: 20 },
  submissionImagesBox: { marginBottom: 16 },
  submissionImagesGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: 8, marginTop: 6 },
  submissionThumb: { width: '47%', aspectRatio: 1, borderRadius: 12 },

  // Success
  successContainer: { padding: 20, alignItems: 'center' },
  successCard: { backgroundColor: COLOR_SCALES.primary[10], borderRadius: 24, padding: 24, alignItems: 'center', width: '100%', marginBottom: 20, borderWidth: 1, borderColor: COLOR_SCALES.primary[20] },
  successIconRing: { width: 120, height: 120, borderRadius: 60, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', marginBottom: 12, borderWidth: 3, borderColor: COLOR_SCALES.primary[30] },
  mascot: { width: 80, height: 80 },
  successMessage: { ...title['M/Bold'], color: COLOR_SCALES.primary[80], textAlign: 'center', marginBottom: 12, lineHeight: 28 },
  pointsBadge: { flexDirection: 'row', alignItems: 'center', gap: 6, backgroundColor: COLOR_SCALES.primary[70], borderRadius: 40, paddingHorizontal: 24, paddingVertical: 12, marginBottom: 16 },
  pointsValue: { ...title['XL/Bold'], color: '#fff' },
  pointsLabel: { ...paragraph['S/Medium'], color: '#fff' },
  successImages: { marginBottom: 12, maxHeight: 80 },
  successThumb: { width: 72, height: 72, borderRadius: 10, marginRight: 8, borderWidth: 2, borderColor: COLOR_SCALES.primary[30] },
  successNote: { ...paragraph['XS/Regular'], color: COLOR_SCALES.colorGray[60], textAlign: 'center', lineHeight: 18 },
  successButton: { width: '100%', marginBottom: 8 },

  // Heroes
  heroesHeader: { flexDirection: 'row', alignItems: 'center', gap: 12, marginBottom: 14 },
  heroesMascot: { width: 48, height: 48 },
  heroesTitle: { ...title['M/Bold'], color: COLOR_SCALES.colorGray[90] },
  heroesSubtitle: { ...paragraph['S/Regular'], color: COLOR_SCALES.colorGray[60] },
  heroCard: { flexDirection: 'row', backgroundColor: COLOR_SCALES.colorGray[10], borderRadius: 14, padding: 12, marginBottom: 10, alignItems: 'center', borderWidth: 1, borderColor: COLOR_SCALES.colorGray[20] },
  heroAvatar: { width: 48, height: 48, borderRadius: 24, marginRight: 10 },
  heroInfo: { flex: 1 },
  heroName: { ...paragraph['S/Bold'], color: COLOR_SCALES.colorGray[90] },
  heroStats: { flexDirection: 'row', alignItems: 'center', marginTop: 4 },
  heroStatText: { ...paragraph['XS/Medium'], color: COLOR_SCALES.colorGray[70], marginLeft: 3, marginRight: 4 },
  heroRight: { alignItems: 'flex-end' },
  heroPoints: { flexDirection: 'row', alignItems: 'center', gap: 4, marginBottom: 8 },
  heroPointsText: { ...paragraph['S/Bold'], color: COLOR_SCALES.primary[60] },
  heroActions: { gap: 6 },
  celebrateBtn: { flexDirection: 'row', alignItems: 'center', gap: 4, backgroundColor: COLOR_SCALES.primary[50], paddingHorizontal: 10, paddingVertical: 6, borderRadius: 16 },
  inspiredBtn: { flexDirection: 'row', alignItems: 'center', gap: 4, backgroundColor: '#2E7D32', paddingHorizontal: 10, paddingVertical: 6, borderRadius: 16 },
  heroBtnText: { ...paragraph['XS/Bold'], color: '#fff', fontSize: 10 },

  // Leaderboard
  leaderboardHeader: { flexDirection: 'row', alignItems: 'center', gap: 10, marginBottom: 16 },
  leaderboardTitle: { ...title['M/Bold'], color: COLOR_SCALES.colorGray[90] },
  leaderboardRow: { flexDirection: 'row', alignItems: 'center', backgroundColor: COLOR_SCALES.colorGray[10], borderRadius: 14, padding: 12, marginBottom: 8, borderWidth: 1, borderColor: COLOR_SCALES.colorGray[20] },
  leaderboardRowTop: { backgroundColor: COLOR_SCALES.primary[10], borderColor: COLOR_SCALES.primary[20] },
  rankBadge: { width: 32, height: 32, borderRadius: 16, backgroundColor: COLOR_SCALES.primary[50], alignItems: 'center', justifyContent: 'center', marginRight: 12 },
  rankGold: { backgroundColor: '#D4A017' },
  rankSilver: { backgroundColor: '#A8A8A8' },
  rankBronze: { backgroundColor: '#CD7F32' },
  rankText: { ...paragraph['S/Bold'], color: '#fff' },
  leaderboardInfo: { flex: 1 },
  leaderboardName: { ...paragraph['S/Bold'], color: COLOR_SCALES.colorGray[90] },
  leaderboardPoints: { ...paragraph['S/Bold'], color: COLOR_SCALES.primary[60] },
});

export default QrModuleScreen;
