/**
 * react-native-system-navigation-bar HarmonyOS Example
 *
 * 覆盖模块公开 API(与源仓 src/index.tsx default 导出一致):
 *   - navigationHide() / navigationShow()
 *   - leanBack(enabled?) / immersive() / stickyImmersive(enabled?) / lowProfile(enabled?)
 *   - setBarMode(style?, bar?) / setNavigationColor(color, style?, bar?)
 *   - setNavigationBarDividerColor(color) / setNavigationBarContrastEnforced(enabled?)
 *   - fullScreen(enabled?) / getBarColor(bar?) / setFitsSystemWindows(enabled?)
 *
 * 每个方法提供可触达按钮(testID 前缀 test-{method}-btn)与结果展示区
 * (testID 前缀 result-{method}),供设备测试(Hypium)定位与验证。
 *
 * HarmonyOS 平台限制(见 ohos/README.md):
 *   - 沉浸模式三态(leanBack/immersive/stickyImmersive)统一映射为隐藏双栏+全屏布局。
 *   - lowProfile / setNavigationBarDividerColor / setNavigationBarContrastEnforced
 *     为 no-op(鸿蒙无对应能力),仍 resolve 'true'。
 *   - 导航栏图标明暗(setBarMode bar='navigation'、setNavigationColor 的 style 对导航栏)
 *     不生效,仅 status/both 作用状态栏图标。
 *   - 导航栏颜色通过窗口背景色近似呈现。
 */

import React, { useState } from 'react';
import {
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
  ViewStyle,
} from 'react-native';
import SystemNavigationBar, { GetBarColorType } from 'react-native-system-navigation-bar';

const PRESET_COLORS = ['#80b3ff', '#ff7f50', '#000000', '#ffffff', 'translucent'];

/** 每个方向是否放弃 SafeAreaView 避让(true = 内容延伸进该侧系统栏区域)。 */
type Immersion = { top: boolean; bottom: boolean };

type ResultKey =
  | 'navigationHide'
  | 'navigationShow'
  | 'leanBack'
  | 'immersive'
  | 'stickyImmersive'
  | 'lowProfile'
  | 'setBarMode'
  | 'setNavigationColor'
  | 'setNavigationBarDividerColor'
  | 'setNavigationBarContrastEnforced'
  | 'fullScreen'
  | 'getBarColor'
  | 'setFitsSystemWindows';

function ResultBox({ testID, text }: { testID: string; text: string }): JSX.Element {
  return (
    <View style={styles.resultBox} testID={`${testID}-box`}>
      <Text style={styles.resultLabel}>Result:</Text>
      <Text style={styles.resultText} testID={testID}>
        {text}
      </Text>
    </View>
  );
}

function ActionButton({
  testID,
  label,
  onPress,
}: {
  testID: string;
  label: string;
  onPress: () => void;
}): JSX.Element {
  return (
    <TouchableOpacity
      style={styles.button}
      testID={testID}
      accessibilityLabel={testID}
      onPress={onPress}>
      <Text style={styles.buttonText}>{label}</Text>
    </TouchableOpacity>
  );
}

function Card({
  title,
  children,
}: {
  title: string;
  children: React.ReactNode;
}): JSX.Element {
  return (
    <View style={styles.card}>
      <Text style={styles.cardTitle}>{title}</Text>
      {children}
    </View>
  );
}

function App(): JSX.Element {
  const [results, setResults] = useState<Record<ResultKey, string>>(
    {} as Record<ResultKey, string>,
  );
  const [color, setColor] = useState('#80b3ff');
  const [navColorBar, setNavColorBar] = useState<'navigation' | 'status' | 'both'>('both');
  const [immersion, setImmersion] = useState<Immersion>({ top: false, bottom: false });
  const [barModeStyle, setBarModeStyle] = useState<'light' | 'dark'>('dark');
  const [barModeBar, setBarModeBar] = useState<'navigation' | 'status' | 'both'>('status');

  const run = async (
    key: ResultKey,
    fn: () => Promise<string | GetBarColorType>,
  ): Promise<void> => {
    setResults(prev => ({ ...prev, [key]: '运行中...' }));
    try {
      const res = await fn();
      const text = typeof res === 'string' ? res : JSON.stringify(res);
      setResults(prev => ({ ...prev, [key]: `成功: ${text}` }));
    } catch (e) {
      const message =
        e !== null && typeof e === 'object' && 'message' in e
          ? String((e as { message: unknown }).message)
          : String(e);
      setResults(prev => ({ ...prev, [key]: `失败: ${message}` }));
    }
  };

  const showResult = (key: ResultKey): JSX.Element | null => {
    const text = results[key];
    if (text === undefined) {
      return null;
    }
    return <ResultBox testID={`result-${key}`} text={text} />;
  };

  // transparent / translucent 的可见效果是「内容铺进系统栏区域」。鸿蒙原生只把窗口切成
  // 沉浸式布局,是否真的延伸取决于宿主放不放弃 SafeAreaView 的避让,所以要在这里放弃。
  // 纯色相反:导航区靠避让带露出窗口背景,避让必须加回来,否则内容会把颜色盖掉。
  const applyImmersion = (
    value: string,
    bar: 'navigation' | 'status' | 'both',
  ): void => {
    const extend = value === 'transparent' || value === 'translucent';
    setImmersion(prev => ({
      top: bar === 'navigation' ? prev.top : extend,
      bottom: bar === 'status' ? prev.bottom : extend,
    }));
  };

  return (
    <SafeAreaView style={safeAreaStyle(immersion)}>
      <ScrollView style={styles.scroll} contentContainerStyle={styles.container}>
        <Text style={styles.title} testID="app-title" accessibilityLabel="app-title">
          System Navigation Bar
        </Text>
        <Text style={styles.subtitle}>
          react-native-system-navigation-bar · HarmonyOS
        </Text>

        <Card title="navigationHide() — 隐藏底部导航栏">
          <ActionButton
            testID="test-navigationHide-btn"
            label="隐藏导航栏"
            onPress={() => run('navigationHide', () => SystemNavigationBar.navigationHide())}
          />
          {showResult('navigationHide')}
        </Card>

        <Card title="navigationShow() — 显示底部导航栏">
          <ActionButton
            testID="test-navigationShow-btn"
            label="显示导航栏"
            onPress={() => run('navigationShow', () => SystemNavigationBar.navigationShow())}
          />
          {showResult('navigationShow')}
        </Card>

        <Card title="leanBack(enabled?) — Lean Back 沉浸">
          <ActionButton
            testID="test-leanBack-btn"
            label="启用 LeanBack(隐藏系统栏)"
            onPress={() => run('leanBack', () => SystemNavigationBar.leanBack(true))}
          />
          <ActionButton
            testID="test-leanBack-false-btn"
            label="退出 LeanBack(恢复系统栏)"
            onPress={() => run('leanBack', () => SystemNavigationBar.leanBack(false))}
          />
          {showResult('leanBack')}
        </Card>

        <Card title="immersive() — Immersive 沉浸">
          <ActionButton
            testID="test-immersive-btn"
            label="进入 Immersive(隐藏系统栏)"
            onPress={() => run('immersive', () => SystemNavigationBar.immersive())}
          />
          {showResult('immersive')}
        </Card>

        <Card title="stickyImmersive(enabled?) — Sticky Immersive 沉浸">
          <ActionButton
            testID="test-stickyImmersive-btn"
            label="启用 StickyImmersive"
            onPress={() =>
              run('stickyImmersive', () => SystemNavigationBar.stickyImmersive(true))
            }
          />
          <ActionButton
            testID="test-stickyImmersive-false-btn"
            label="退出 StickyImmersive"
            onPress={() =>
              run('stickyImmersive', () => SystemNavigationBar.stickyImmersive(false))
            }
          />
          {showResult('stickyImmersive')}
        </Card>

        <Card title="lowProfile(enabled?) — 弱化系统栏图标(鸿蒙无能力,no-op)">
          <ActionButton
            testID="test-lowProfile-btn"
            label="启用 LowProfile(no-op)"
            onPress={() => run('lowProfile', () => SystemNavigationBar.lowProfile(true))}
          />
          <ActionButton
            testID="test-lowProfile-false-btn"
            label="退出 LowProfile(no-op)"
            onPress={() => run('lowProfile', () => SystemNavigationBar.lowProfile(false))}
          />
          {showResult('lowProfile')}
        </Card>

        <Card title="setBarMode(style?, bar?) — 系统栏图标明暗">
          <View style={styles.paramRow}>
            <Text style={styles.label}>样式:</Text>
            {(['light', 'dark'] as const).map(style => (
              <TouchableOpacity
                key={style}
                style={[styles.chip, barModeStyle === style && styles.chipActive]}
                testID={`chip-setBarMode-style-${style}`}
                onPress={() => setBarModeStyle(style)}>
                <Text style={styles.chipText}>{style === 'light' ? 'light 浅' : 'dark 深'}</Text>
              </TouchableOpacity>
            ))}
          </View>
          <View style={styles.paramRow}>
            <Text style={styles.label}>作用域:</Text>
            {(['navigation', 'status', 'both'] as const).map(bar => (
              <TouchableOpacity
                key={bar}
                style={[styles.chip, barModeBar === bar && styles.chipActive]}
                testID={`chip-setBarMode-bar-${bar}`}
                onPress={() => setBarModeBar(bar)}>
                <Text style={styles.chipText}>{bar}</Text>
              </TouchableOpacity>
            ))}
          </View>
          <ActionButton
            testID="test-setBarMode-btn"
            label={`应用 setBarMode(${barModeStyle}, ${barModeBar})`}
            onPress={() =>
              run('setBarMode', () => SystemNavigationBar.setBarMode(barModeStyle, barModeBar))
            }
          />
          {showResult('setBarMode')}
        </Card>

        <Card title="setNavigationColor(color, style?, bar?) — 设置系统栏颜色">
          <Text style={styles.label}>颜色色值(HEX / translucent)</Text>
          <TextInput
            style={styles.input}
            value={color}
            onChangeText={setColor}
            placeholder="#80b3ff"
            placeholderTextColor="#999"
            autoCapitalize="none"
            autoCorrect={false}
            testID="input-setNavigationColor-color"
            accessibilityLabel="input-setNavigationColor-color"
          />
          <View style={styles.paramRow}>
            {PRESET_COLORS.map(preset => (
              <TouchableOpacity
                key={preset}
                style={styles.chip}
                testID={`preset-${preset.replace('#', '')}`}
                onPress={() => setColor(preset)}>
                <Text style={styles.chipText}>{preset}</Text>
              </TouchableOpacity>
            ))}
          </View>
          <View style={styles.paramRow}>
            <Text style={styles.label}>作用域:</Text>
            {(['navigation', 'status', 'both'] as const).map(bar => (
              <TouchableOpacity
                key={bar}
                style={[styles.chip, navColorBar === bar && styles.chipActive]}
                testID={`chip-setNavigationColor-bar-${bar}`}
                onPress={() => setNavColorBar(bar)}>
                <Text style={styles.chipText}>{bar}</Text>
              </TouchableOpacity>
            ))}
          </View>
          <ActionButton
            testID="test-setNavigationColor-btn"
            label={`应用 setNavigationColor(${color}, dark, ${navColorBar})`}
            onPress={() =>
              run('setNavigationColor', async () => {
                const res = await SystemNavigationBar.setNavigationColor(
                  color,
                  'dark',
                  navColorBar,
                );
                applyImmersion(color, navColorBar);
                return res;
              })
            }
          />
          {showResult('setNavigationColor')}
        </Card>

        <Card title="setNavigationBarDividerColor(color) — 导航栏分隔线颜色(鸿蒙无能力,no-op)">
          <ActionButton
            testID="test-setNavigationBarDividerColor-btn"
            label="设置分隔线颜色 #888888(no-op)"
            onPress={() =>
              run('setNavigationBarDividerColor', () =>
                SystemNavigationBar.setNavigationBarDividerColor('#888888'),
              )
            }
          />
          {showResult('setNavigationBarDividerColor')}
        </Card>

        <Card title="setNavigationBarContrastEnforced(enabled?) — 对比度强制(鸿蒙无能力,no-op)">
          <ActionButton
            testID="test-setNavigationBarContrastEnforced-btn"
            label="启用对比度强制(no-op)"
            onPress={() =>
              run('setNavigationBarContrastEnforced', () =>
                SystemNavigationBar.setNavigationBarContrastEnforced(true),
              )
            }
          />
          <ActionButton
            testID="test-setNavigationBarContrastEnforced-false-btn"
            label="关闭对比度强制(no-op)"
            onPress={() =>
              run('setNavigationBarContrastEnforced', () =>
                SystemNavigationBar.setNavigationBarContrastEnforced(false),
              )
            }
          />
          {showResult('setNavigationBarContrastEnforced')}
        </Card>

        <Card title="fullScreen(enabled?) — 全屏模式">
          <ActionButton
            testID="test-fullScreen-btn"
            label="进入全屏"
            onPress={() => run('fullScreen', () => SystemNavigationBar.fullScreen(true))}
          />
          <ActionButton
            testID="test-fullScreen-false-btn"
            label="退出全屏"
            onPress={() => run('fullScreen', () => SystemNavigationBar.fullScreen(false))}
          />
          {showResult('fullScreen')}
        </Card>

        <Card title="getBarColor(bar?) — 查询系统栏颜色">
          {(['navigation', 'status', 'both'] as const).map(bar => (
            <ActionButton
              key={bar}
              testID={`test-getBarColor-${bar}-btn`}
              label={`查询 ${bar} 颜色`}
              onPress={() => run('getBarColor', () => SystemNavigationBar.getBarColor(bar))}
            />
          ))}
          {showResult('getBarColor')}
        </Card>

        <Card title="setFitsSystemWindows(enabled?) — 内容避让系统窗口">
          <ActionButton
            testID="test-setFitsSystemWindows-btn"
            label="启用内容避让系统栏"
            onPress={() =>
              run('setFitsSystemWindows', () => SystemNavigationBar.setFitsSystemWindows(true))
            }
          />
          <ActionButton
            testID="test-setFitsSystemWindows-false-btn"
            label="关闭内容避让(延伸系统栏区域)"
            onPress={() =>
              run('setFitsSystemWindows', () => SystemNavigationBar.setFitsSystemWindows(false))
            }
          />
          {showResult('setFitsSystemWindows')}
        </Card>

        <Text style={styles.note}>
          注:HarmonyOS 上沉浸三态(leanBack/immersive/stickyImmersive)行为一致(隐藏系统栏+全屏布局),
          lowProfile/分隔线/对比度强制为 no-op;导航栏图标明暗仅状态栏生效;导航栏颜色通过窗口背景色近似呈现。
        </Text>
      </ScrollView>
    </SafeAreaView>
  );
}

// 返回字面量 style,勿用 StyleSheet 编号:RNOH SafeAreaView 读的是 style.paddingTop /
// paddingBottom 是否为 0,编号对象上读不到这两个字段,避让不会被关掉。
// 只给「要放弃」的一侧写 0,另一侧不写——写了会被当成显式 0,把该留的避让也关掉。
// 同样不能设背景色:SafeAreaView 的背景会连避让 padding 一起刷满,
// 底部那条避让带就是导航区,会把 setNavigationColor 染上的窗口背景盖掉。
function safeAreaStyle({ top, bottom }: Immersion): ViewStyle {
  if (top && bottom) {
    return { flex: 1, paddingTop: 0, paddingBottom: 0 };
  }
  if (top) {
    return { flex: 1, paddingTop: 0 };
  }
  if (bottom) {
    return { flex: 1, paddingBottom: 0 };
  }
  return { flex: 1 };
}

const styles = StyleSheet.create({
  scroll: {
    flex: 1,
    backgroundColor: '#F3F3F3',
  },
  container: {
    padding: 16,
    paddingBottom: 48,
  },
  title: {
    fontSize: 24,
    fontWeight: '700',
    color: '#222',
    marginBottom: 4,
  },
  subtitle: {
    fontSize: 14,
    color: '#666',
    marginBottom: 16,
  },
  card: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 14,
    marginBottom: 14,
  },
  cardTitle: {
    fontSize: 15,
    fontWeight: '600',
    color: '#333',
    marginBottom: 10,
  },
  button: {
    backgroundColor: '#0a84ff',
    borderRadius: 6,
    paddingVertical: 10,
    paddingHorizontal: 14,
    marginBottom: 8,
    alignItems: 'center',
  },
  buttonText: {
    color: '#fff',
    fontSize: 14,
    fontWeight: '600',
  },
  label: {
    fontSize: 13,
    color: '#555',
    marginBottom: 4,
  },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 6,
    paddingHorizontal: 10,
    paddingVertical: 8,
    marginBottom: 8,
    fontSize: 14,
    color: '#222',
    backgroundColor: '#fff',
  },
  paramRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    alignItems: 'center',
    marginBottom: 8,
  },
  chip: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 14,
    paddingHorizontal: 10,
    paddingVertical: 4,
    marginRight: 6,
    marginBottom: 4,
  },
  chipActive: {
    borderColor: '#0a84ff',
    backgroundColor: '#e8f1ff',
  },
  chipText: {
    fontSize: 12,
    color: '#333',
  },
  resultBox: {
    backgroundColor: '#f6f6f6',
    borderRadius: 6,
    padding: 10,
    marginTop: 4,
  },
  resultLabel: {
    fontSize: 12,
    fontWeight: '700',
    color: '#444',
    marginBottom: 2,
  },
  resultText: {
    fontSize: 13,
    color: '#222',
  },
  note: {
    fontSize: 12,
    color: '#888',
    lineHeight: 18,
    marginTop: 4,
  },
});

export default App;