/**
 * 自动记账管理页（plan.md「3.x 自动记账统一管理」+「3.6 无障碍服务」）。
 *
 * 功能：
 * - 显示 5 个通道（通知/短信/截图/OCR/手动）的检测统计
 * - 展示检测到的事件列表
 * - "处理全部" → BillPipeline → 草稿
 * - 逐条确认/拒绝草稿 → 写入 main.bean
 * - 截图监控开关（调原生 ScreenshotMonitor 模块）
 * - 无障碍服务控制：
 *   - 服务状态（已连接/未启用）
 *   - 打开系统无障碍设置
 *   - 记住当前页面（标记应自动 OCR 的支付页面）
 *   - 手动触发 OCR
 *   - 已记住页面列表（可删除）
 *   - 支付 App 白名单展示
 */
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { ActivityIndicator, Alert, AppState, Linking, NativeModules, PermissionsAndroid, Platform, Pressable, ScrollView, StyleSheet, Text, View, Switch } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { useTheme } from '../../theme';
import { useT } from '../../i18n';
import { useRouter } from 'expo-router';
import { useSettingsStore } from '../../store/settingsStore';
import { Card } from '../../components/ui/Card';
import { Button } from '../../components/ui/Button';
import { ScreenHeader } from '../../components/layout/ScreenHeader';
import {
  getAccessibilityBridge,
  getPackageLabel,
  type PageSignature,
} from '../../services/automation/accessibilityBridge';
import { ensureOcrModels, downloadOcrModels } from '../../services/ocr/modelDownloader';
import { logger } from '../../utils/logger';

export default function AutomationScreen() {
  const { theme } = useTheme();
  const t = useT();
  const router = useRouter();

  const floatingBallEnabled = useSettingsStore(s => s.floatingBallEnabled);
  const setFloatingBallEnabled = useSettingsStore(s => s.setFloatingBallEnabled);

  // 自动记账层级
  const layer1RuleEnabled = useSettingsStore(s => s.layer1RuleEnabled);
  const setLayer1RuleEnabled = useSettingsStore(s => s.setLayer1RuleEnabled);
  const layer2OcrEnabled = useSettingsStore(s => s.layer2OcrEnabled);
  const setLayer2OcrEnabled = useSettingsStore(s => s.setLayer2OcrEnabled);
  const layer3AiEnabled = useSettingsStore(s => s.layer3AiEnabled);
  const setLayer3AiEnabled = useSettingsStore(s => s.setLayer3AiEnabled);
  const ocrModelVersion = useSettingsStore(s => s.ocrModelVersion);
  const aiEnabled = useSettingsStore(s => s.aiEnabled);
  const aiApiKey = useSettingsStore(s => s.aiApiKey) || '';
  const dedupEnabled = useSettingsStore(s => s.dedupEnabled);
  const setDedupEnabled = useSettingsStore(s => s.setDedupEnabled);
  const transferRecognitionEnabled = useSettingsStore(s => s.transferRecognitionEnabled);
  const setTransferRecognitionEnabled = useSettingsStore(s => s.setTransferRecognitionEnabled);

  // 无障碍服务状态
  const [serviceRunning, setServiceRunning] = useState(false);
  const [pageSignatures, setPageSignatures] = useState<PageSignature[]>([]);
  const [paymentPackages, setPaymentPackages] = useState<{ package: string; label: string }[]>([]);
  const [screenshotActive, setScreenshotActive] = useState(false);
  const [topApp, setTopApp] = useState<{ package: string; activity: string } | null>(null);

  // 权限状态
  const [notifEnabled, setNotifEnabled] = useState<boolean | null>(null);
  const [smsGranted, setSmsGranted] = useState<boolean | null>(null);
  const [storageGranted, setStorageGranted] = useState<boolean | null>(null);
  const [overlayGranted, setOverlayGranted] = useState<boolean | null>(null);

  // OCR 模型安装/下载状态
  const [modelStatus, setModelStatus] = useState<'idle' | 'installing' | 'verifying' | 'done' | 'error'>('idle');
  const [modelProgress, setModelProgress] = useState(0);

  const handleInstallModel = async () => {
    setModelStatus('installing');
    try {
      await ensureOcrModels((p) => setModelProgress(p));
      setModelStatus('done');
    } catch (e) {
      setModelStatus('error');
      Alert.alert(t('common.error'), String(e));
    }
  };

  const handleRedownloadModel = async () => {
    setModelStatus('installing');
    setModelProgress(0);
    try {
      await downloadOcrModels(undefined, (p) => setModelProgress(p));
      setModelStatus('done');
    } catch (e) {
      setModelStatus('error');
      Alert.alert(t('automation.ocrModelDownloadFail'), String(e));
    }
  };

  const handleL2Toggle = (val: boolean) => {
    if (val && !ocrModelVersion) {
      Alert.alert(t('automation.ocrModelTitle'), t('automation.ocrModelNotInstalled'), [
        { text: t('common.cancel'), onPress: () => setLayer2OcrEnabled(false) },
        { text: t('automation.ocrModelInstall'), onPress: handleInstallModel },
      ]);
      return;
    }
    setLayer2OcrEnabled(val);
  };

  const scrollRef = useRef<ScrollView>(null);

  const handleL3Toggle = (val: boolean) => {
    if (val && (!aiEnabled || !aiApiKey)) {
      Alert.alert(t('automation.layer3Ai'), t('automation.layer3AiDisabled'), [
        { text: t('common.cancel'), style: 'cancel' },
        { text: t('common.confirm'), onPress: () => router.push('/settings/ai') },
      ]);
      return;
    }
    setLayer3AiEnabled(val);
  };

  // 刷新无障碍状态
  const refreshAccessibilityState = useCallback(async () => {
    const bridge = getAccessibilityBridge();
    if (!bridge) return;
    try {
      const [running, sigs, pkgs, top] = await Promise.all([
        bridge.isServiceRunning().catch(() => false),
        bridge.getPageSignatures().catch(() => [] as PageSignature[]),
        bridge.getPaymentPackages().catch(() => [] as string[]),
        bridge.getTopApp().catch(() => ({ package: '', activity: '' })),
      ]);
      setServiceRunning(running);
      setPageSignatures(sigs);
      setPaymentPackages(pkgs.map(pkg => ({ package: pkg, label: getPackageLabel(pkg) })));
      setTopApp(top && top.package ? top : null);
    } catch (e) {
      logger.debug('automation', '[刷新无障碍状态] 失败', e);
    }
  }, []);

  useEffect(() => {
    refreshAccessibilityState();

    const subscription = AppState.addEventListener('change', (nextAppState) => {
      if (nextAppState === 'active') {
        refreshAccessibilityState();
      }
    });

    return () => {
      subscription.remove();
    };
  }, [refreshAccessibilityState]);

  // 检查权限状态（挂载 + 从系统设置返回前台时重新检查）
  useEffect(() => {
    if (Platform.OS !== 'android') return;

    const checkPermissions = () => {
      const bridge = getAccessibilityBridge();
      if (bridge && typeof bridge.isNotificationListenerEnabled === 'function') {
        bridge.isNotificationListenerEnabled().then(setNotifEnabled).catch(() => setNotifEnabled(false));
      }
      if (bridge && typeof bridge.canDrawOverlays === 'function') {
        bridge.canDrawOverlays().then(setOverlayGranted).catch(() => setOverlayGranted(false));
      }
      const smsPerm = 'android.permission.RECEIVE_SMS';
      PermissionsAndroid.check(smsPerm).then(async (granted) => {
        if (granted) { setSmsGranted(true); return; }
        try {
          const result = await PermissionsAndroid.request(smsPerm);
          setSmsGranted(result === PermissionsAndroid.RESULTS.GRANTED);
        } catch { setSmsGranted(false); }
      }).catch(() => setSmsGranted(false));
      const storagePerm = Number(Platform.Version) >= 33 ? 'android.permission.READ_MEDIA_IMAGES' : 'android.permission.READ_EXTERNAL_STORAGE';
      PermissionsAndroid.check(storagePerm).then(g => setStorageGranted(g as boolean)).catch(() => setStorageGranted(false));
    };

    checkPermissions();

    const sub = AppState.addEventListener('change', (state) => {
      if (state === 'active') checkPermissions();
    });
    return () => sub.remove();
  }, []);

  const handleOpenNotificationSettings = () => {
    if (Platform.OS !== 'android') return;
    Linking.sendIntent('android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS').catch((e) => { logger.debug('automation', '[打开通知设置] 失败', e); });
  };

  const handleRequestSms = async () => {
    const result = await PermissionsAndroid.request('android.permission.RECEIVE_SMS');
    setSmsGranted(result === PermissionsAndroid.RESULTS.GRANTED);
  };

  const handleOpenOverlaySettings = () => {
    Linking.sendIntent('android.settings.action.MANAGE_OVERLAY_PERMISSION').catch((e) => { logger.debug('automation', '[打开悬浮窗设置] 失败', e); });
  };

  const handleRequestStorage = async () => {
    const perm = Number(Platform.Version) >= 33 ? 'android.permission.READ_MEDIA_IMAGES' : 'android.permission.READ_EXTERNAL_STORAGE';
    const result = await PermissionsAndroid.request(perm);
    setStorageGranted(result === PermissionsAndroid.RESULTS.GRANTED);
  };

  const handleScreenshotToggle = () => {
    if (Platform.OS !== 'android') {
      Alert.alert('Android only');
      return;
    }
    const module = (NativeModules as { ScreenshotMonitor?: { start: () => void; stop: () => void } }).ScreenshotMonitor;
    if (!module) {
      Alert.alert(t('automation.screenshotUnavailable'));
      return;
    }
    if (screenshotActive) {
      module.stop();
      setScreenshotActive(false);
    } else {
      module.start();
      setScreenshotActive(true);
    }
  };

  const handleOpenAccessibilitySettings = () => {
    if (Platform.OS !== 'android') return;
    // 打开系统无障碍设置页面 (Intent Action)
    Linking.sendIntent('android.settings.ACCESSIBILITY_SETTINGS').catch(() => {
      Alert.alert(t('automation.openSettingsFail'));
    });
  };

  const handleRememberPage = async () => {
    const bridge = getAccessibilityBridge();
    if (!bridge) {
      Alert.alert(t('automation.bridgeUnavailable'));
      return;
    }
    Alert.alert(
      '准备记录目标页面',
      '点击“开始”后，请在 8 秒内切换到支付宝/微信的账单详情页，系统将在倒计时结束后自动记录该页面的签名。',
      [
        { text: t('common.cancel'), style: 'cancel' },
        {
          text: '开始 (8s 倒计时)',
          onPress: () => {
            setTimeout(async () => {
              try {
                const result = await bridge.rememberCurrentPage();
                Alert.alert(
                  t('automation.rememberPageSuccess'),
                  t('automation.rememberPageDesc', { pkg: getPackageLabel(result.package), activity: result.activity }),
                );
                refreshAccessibilityState();
              } catch (e) {
                Alert.alert(t('automation.rememberPageFail'), String((e as Error)?.message ?? e));
              }
            }, 8000);
          },
        },
      ],
    );
  };

  const handleManualOcr = async () => {
    const bridge = getAccessibilityBridge();
    if (!bridge) {
      Alert.alert(t('automation.bridgeUnavailable'));
      return;
    }
    Alert.alert(
      '准备手动识别',
      '点击“开始”后，请在 8 秒内切换到你想识别的账单详情页，系统将在 8 秒后自动截图并识别该页面。',
      [
        { text: t('common.cancel'), style: 'cancel' },
        {
          text: '开始 (8s 倒计时)',
          onPress: () => {
            setTimeout(async () => {
              try {
                await bridge.triggerManualOcr();
              } catch (e) {
                Alert.alert(t('automation.manualOcrFail'), String((e as Error)?.message ?? e));
              }
            }, 8000);
          },
        },
      ],
    );
  };

  const handleRemoveSignature = async (sig: string) => {
    const bridge = getAccessibilityBridge();
    if (!bridge) return;
    try {
      await bridge.removePageSignature(sig);
      refreshAccessibilityState();
    } catch (e) {
      logger.warn('automation', `[删除页面签名] 失败: ${sig}`, e);
    }
  };

  const handleClearSignatures = () => {
    Alert.alert(
      t('automation.clearPagesTitle'),
      t('automation.clearPagesConfirm'),
      [
        { text: t('common.cancel'), style: 'cancel' },
        {
          text: t('common.confirm'),
          style: 'destructive',
          onPress: async () => {
            const bridge = getAccessibilityBridge();
            if (!bridge) return;
            try {
              await bridge.clearPageSignatures();
              refreshAccessibilityState();
            } catch (e) {
              logger.warn('automation', '[清空页面签名] 失败', e);
            }
          },
        },
      ],
    );
  };

  return (
    <SafeAreaView style={[styles.page, { backgroundColor: theme.colors.bgPrimary }]} edges={['top', 'bottom']}>
      <ScreenHeader title={t('automation.title')} />

      <ScrollView ref={scrollRef} contentContainerStyle={styles.content}>
          <View style={{ gap: 12, marginBottom: 12 }}>

            {/* 无障碍服务状态与控制 */}
            {Platform.OS === 'android' && (
              <Card title={t('automation.accessibilityTitle')}>
                {/* 服务状态 */}
                <View style={[styles.statusRow, { marginBottom: 8 }]}>
                  <View style={[styles.statusDot, { backgroundColor: serviceRunning ? theme.colors.success : theme.colors.fgSecondary }]} />
                  <Text style={[theme.typography.body, { color: theme.colors.fgPrimary }]}>
                    {serviceRunning ? t('automation.serviceRunning') : t('automation.serviceStopped')}
                  </Text>
                </View>
                {topApp && (
                  <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, marginBottom: 8 }]}>
                    {t('automation.currentApp')}: {getPackageLabel(topApp.package)}
                  </Text>
                )}

                {/* 悬浮球开关 */}
                <View style={[styles.switchRow, { marginBottom: 8 }]}>
                  <Text style={[theme.typography.body, { color: theme.colors.fgPrimary, flex: 1 }]}>
                    {t('automation.floatingBall')}
                  </Text>
                  <Switch
                    value={floatingBallEnabled}
                    onValueChange={async (val) => {
                      setFloatingBallEnabled(val);
                      const bridge = getAccessibilityBridge();
                      if (bridge) {
                        try { await bridge.setFloatingBallEnabled(val); } catch (e) { logger.debug('automation', '[悬浮球] 同步开关失败', e); }
                      }
                    }}
                    trackColor={{ false: theme.colors.bgTertiary, true: theme.colors.accent }}
                    thumbColor={theme.colors.fgInverse}
                  />
                </View>

                {/* 操作按钮 */}
                <View style={{ gap: 8 }}>
                  {!serviceRunning && (
                    <Button label={t('automation.openSettings')} onPress={handleOpenAccessibilitySettings} variant="secondary" />
                  )}
                  <View style={{ flexDirection: 'row', gap: 8 }}>
                    <View style={{ flex: 1 }}>
                      <Button
                        label={t('automation.rememberPage')}
                        onPress={handleRememberPage}
                        variant="secondary"
                      />
                    </View>
                    <View style={{ flex: 1 }}>
                      <Button
                        label={t('automation.manualOcr')}
                        onPress={handleManualOcr}
                      />
                    </View>
                  </View>
                </View>

                {/* 支付 App 白名单 */}
                <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, marginTop: 12, marginBottom: 4 }]}>
                  {t('automation.whitelistTitle')}
                </Text>
                <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 4 }}>
                  {paymentPackages.length === 0 ? (
                    <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>
                      {t('automation.whitelistEmpty')}
                    </Text>
                  ) : (
                    paymentPackages.map(pkg => (
                      <View key={pkg.package} style={[styles.chip, { backgroundColor: theme.colors.divider }]}>
                        <Text style={[theme.typography.caption, { color: theme.colors.fgPrimary }]}>
                          {pkg.label}
                        </Text>
                      </View>
                    ))
                  )}
                </View>

                {/* 已记住的页面 */}
                {pageSignatures.length > 0 && (
                  <View style={{ marginTop: 12 }}>
                    <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                      <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>
                        {t('automation.rememberedPages', { count: pageSignatures.length })}
                      </Text>
                      <Pressable onPress={handleClearSignatures}>
                        <Text style={[theme.typography.caption, { color: theme.colors.accent }]}>
                          {t('automation.clearAll')}
                        </Text>
                      </Pressable>
                    </View>
                    {pageSignatures.map(sig => (
                      <View key={sig.signature} style={styles.sigRow}>
                        <Text style={[theme.typography.bodySmall, { color: theme.colors.fgPrimary, flex: 1 }]}>
                          {getPackageLabel(sig.package)} · {sig.activity.split('.').pop() || sig.activity}
                        </Text>
                        <Pressable onPress={() => handleRemoveSignature(sig.signature)}>
                          <Ionicons name="close-circle" size={18} color={theme.colors.fgSecondary} />
                        </Pressable>
                      </View>
                    ))}
                  </View>
                )}

                {/* 截图监控开关 */}
                <View style={{ marginTop: 12 }}>
                  <Button
                    label={screenshotActive ? t('automation.screenshotStop') : t('automation.screenshotStart')}
                    onPress={handleScreenshotToggle}
                    variant={screenshotActive ? 'primary' : 'secondary'}
                  />
                </View>
              </Card>
            )}

            {/* --- Card A: 自动记账层级 --- */}
            <Card title={t('automation.autoBookkeeping')}>
              {/* L1 规则匹配 */}
              <View style={[styles.layerRow, { marginBottom: 8 }]}>
                <Ionicons name="flash-outline" size={20} color={layer1RuleEnabled ? theme.colors.accent : theme.colors.fgSecondary} />
                <View style={{ flex: 1, marginLeft: 10 }}>
                  <Text style={[theme.typography.body, { color: theme.colors.fgPrimary }]}>
                    {t('automation.layer1Rule')}
                  </Text>
                  <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>
                    {t('automation.layer1RuleDesc')}
                  </Text>
                </View>
                <Switch
                  value={layer1RuleEnabled}
                  onValueChange={setLayer1RuleEnabled}
                  trackColor={{ false: theme.colors.bgTertiary, true: theme.colors.accent }}
                  thumbColor={theme.colors.fgInverse}
                />
              </View>

              {/* L2 OCR 识别 */}
              <View style={[styles.layerRow, { marginBottom: 8 }]}>
                <Ionicons name="scan-outline" size={20} color={layer2OcrEnabled ? theme.colors.accent : theme.colors.fgSecondary} />
                <View style={{ flex: 1, marginLeft: 10 }}>
                  <Text style={[theme.typography.body, { color: theme.colors.fgPrimary }]}>
                    {t('automation.layer2Ocr')}
                  </Text>
                  <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>
                    {t('automation.layer2OcrDesc')}
                  </Text>
                </View>
                <Switch
                  value={layer2OcrEnabled}
                  onValueChange={handleL2Toggle}
                  trackColor={{ false: theme.colors.bgTertiary, true: theme.colors.accent }}
                  thumbColor={theme.colors.fgInverse}
                />
              </View>

              {/* L3 AI 视觉 */}
              <View style={styles.layerRow}>
                <Ionicons name="sparkles-outline" size={20} color={layer3AiEnabled ? theme.colors.accent : theme.colors.fgSecondary} />
                <View style={{ flex: 1, marginLeft: 10 }}>
                  <Text style={[theme.typography.body, { color: theme.colors.fgPrimary }]}>
                    {t('automation.layer3Ai')}
                  </Text>
                  <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary }]}>
                    {t('automation.layer3AiDesc')}
                  </Text>
                </View>
                <Switch
                  value={layer3AiEnabled}
                  onValueChange={handleL3Toggle}
                  trackColor={{ false: theme.colors.bgTertiary, true: theme.colors.accent }}
                  thumbColor={theme.colors.fgInverse}
                />
              </View>
            </Card>

            {/* --- Card B: OCR 模型 --- */}
            <Card title={t('automation.ocrModelTitle')}>
              {/* 状态行 */}
              <View style={styles.layerRow}>
                <Ionicons
                  name="hardware-chip-outline"
                  size={20}
                  color={ocrModelVersion ? theme.colors.success : theme.colors.fgSecondary}
                />
                <Text style={[theme.typography.body, { flex: 1, marginLeft: 10, color: ocrModelVersion ? theme.colors.success : theme.colors.fgSecondary }]}>
                  {ocrModelVersion
                    ? t('automation.ocrModelInstalled', { version: ocrModelVersion })
                    : t('automation.ocrModelNotInstalled')}
                </Text>
              </View>

              {/* 下载进度条 */}
              {modelStatus === 'installing' && (
                <View style={{ marginTop: 8 }}>
                  <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
                    <ActivityIndicator size="small" color={theme.colors.accent} />
                    <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, flex: 1 }]}>
                      {modelProgress > 0
                        ? t('automation.ocrModelDownloading', { progress: String(modelProgress) })
                        : t('automation.ocrModelCopying')}
                    </Text>
                  </View>
                  {modelProgress > 0 && (
                    <View style={[styles.progressBar, { backgroundColor: theme.colors.progressBg, marginTop: 6 }]}>
                      <View style={[styles.progressFill, { backgroundColor: theme.colors.accent, width: `${modelProgress}%` }]} />
                    </View>
                  )}
                </View>
              )}

              {/* 操作按钮行 */}
              {modelStatus !== 'installing' && (
                <View style={[styles.layerRow, { marginTop: 8 }]}>
                  {!ocrModelVersion || modelStatus === 'error' ? (
                    <Button label={t('automation.ocrModelDownload')} onPress={handleInstallModel} variant="secondary" />
                  ) : (
                    <Button label={t('automation.ocrModelRedownload')} onPress={handleRedownloadModel} variant="secondary" />
                  )}
                </View>
              )}
            </Card>

            {/* --- Card C: 管道设置 --- */}
            <Card title={t('settings.algorithmConfig')}>
              <View style={[styles.switchRow, { marginBottom: 8 }]}>
                <Text style={[theme.typography.body, { color: theme.colors.fgPrimary, flex: 1 }]}>
                  {t('settings.dedupLabel')}
                </Text>
                <Switch
                  value={dedupEnabled}
                  onValueChange={setDedupEnabled}
                  trackColor={{ false: theme.colors.bgTertiary, true: theme.colors.accent }}
                  thumbColor={theme.colors.fgInverse}
                />
              </View>
              <View style={styles.switchRow}>
                <Text style={[theme.typography.body, { color: theme.colors.fgPrimary, flex: 1 }]}>
                  {t('settings.transferLabel')}
                </Text>
                <Switch
                  value={transferRecognitionEnabled}
                  onValueChange={setTransferRecognitionEnabled}
                  trackColor={{ false: theme.colors.bgTertiary, true: theme.colors.accent }}
                  thumbColor={theme.colors.fgInverse}
                />
              </View>
            </Card>

            {/* 其他权限 */}
            {Platform.OS === 'android' && (
              <Card title={t('automation.otherPermissions')}>
                {/* 通知监听 */}
                <View style={styles.permRow}>
                  <Ionicons name="notifications-outline" size={20} color={notifEnabled ? theme.colors.success : theme.colors.fgSecondary} />
                  <Text style={{ flex: 1, marginLeft: 8, color: theme.colors.fgPrimary }}>{t('automation.notificationTitle')}</Text>
                  <Text style={{ color: notifEnabled ? theme.colors.success : theme.colors.fgSecondary, marginRight: 8 }}>
                    {notifEnabled ? t('automation.notificationEnabled') : t('automation.notificationDisabled')}
                  </Text>
                  {!notifEnabled && <Button label={t('automation.notificationOpenSettings')} onPress={handleOpenNotificationSettings} variant="secondary" />}
                </View>

                {/* 短信 */}
                <View style={[styles.permRow, { marginTop: 8 }]}>
                  <Ionicons name="chatbubble-outline" size={20} color={smsGranted ? theme.colors.success : theme.colors.fgSecondary} />
                  <Text style={{ flex: 1, marginLeft: 8, color: theme.colors.fgPrimary }}>{t('automation.smsPermissionTitle')}</Text>
                  <Text style={{ color: smsGranted ? theme.colors.success : theme.colors.fgSecondary, marginRight: 8 }}>
                    {t('automation.smsPermGranted')}
                  </Text>
                  {!smsGranted && <Button label={t('automation.smsPermRequest')} onPress={handleRequestSms} variant="secondary" />}
                </View>

                {/* 存储 */}
                <View style={[styles.permRow, { marginTop: 8 }]}>
                  <Ionicons name="images-outline" size={20} color={storageGranted ? theme.colors.success : theme.colors.fgSecondary} />
                  <Text style={{ flex: 1, marginLeft: 8, color: theme.colors.fgPrimary }}>{t('automation.storagePermTitle')}</Text>
                  <Text style={{ color: storageGranted ? theme.colors.success : theme.colors.fgSecondary, marginRight: 8 }}>
                    {t('automation.storagePermGranted')}
                  </Text>
                  {!storageGranted && <Button label={t('automation.storagePermRequest')} onPress={handleRequestStorage} variant="secondary" />}
                </View>

                {/* 悬浮窗 */}
                <View style={[styles.permRow, { marginTop: 8 }]}>
                  <Ionicons name="tablet-landscape-outline" size={20} color={overlayGranted ? theme.colors.success : theme.colors.fgSecondary} />
                  <Text style={{ flex: 1, marginLeft: 8, color: theme.colors.fgPrimary }}>{t('automation.overlayPermTitle')}</Text>
                  <Text style={{ color: overlayGranted ? theme.colors.success : theme.colors.fgSecondary, marginRight: 8 }}>
                    {overlayGranted ? t('automation.overlayPermGranted') : t('automation.overlayPermNotGranted')}
                  </Text>
                  {!overlayGranted && <Button label={t('automation.overlayPermOpenSettings')} onPress={handleOpenOverlaySettings} variant="secondary" />}
                </View>
              </Card>
            )}

          </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  page: { flex: 1 },
  content: { padding: 16, paddingBottom: 64 },
  statusRow: { flexDirection: 'row', alignItems: 'center', gap: 8 },
  statusDot: { width: 8, height: 8, borderRadius: 4 },
  switchRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
  layerRow: { flexDirection: 'row', alignItems: 'center' },
  chip: { paddingHorizontal: 8, paddingVertical: 4, borderRadius: 4 },
  progressBar: { height: 4, borderRadius: 2, overflow: 'hidden' },
  progressFill: { height: '100%', borderRadius: 2 },
  sigRow: { flexDirection: 'row', alignItems: 'center', gap: 8, paddingVertical: 4 },
  permRow: { flexDirection: 'row', alignItems: 'center' },
});
