/**
 * 发帖页 CreatePostScreen（响应式适配）
 * 胡萝卜BBS - 发布新帖子
 * 参考微博发帖界面设计
 * 表单在宽屏下居中显示
 * 图片选择器在宽屏下显示更大的预览
 * 投票编辑器在宽屏下优化布局
 */

import React, { useState, useCallback, useMemo } from 'react';
import {
  View,
  ScrollView,
  StyleSheet,
  TouchableOpacity,
  TextInput,
  Alert,
  KeyboardAvoidingView,
  Platform,
  Animated,
  Image,
  useWindowDimensions,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter, useLocalSearchParams, useNavigation } from 'expo-router';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
import {
  spacing,
  fontSizes,
  borderRadius,
  shadows,
  useAppColors,
  type AppColors,
} from '../../theme';
import { Text, ResponsiveContainer } from '../../components/common';
import { channelService, postService, showPrompt, voteService } from '../../services';
import { ApiError } from '../../services/api';
import { uploadService } from '../../services/uploadService';
import VoteEditor from '../../components/business/VoteEditor';
import { useResponsive, useResponsiveValue } from '../../hooks';
import * as hrefs from '../../navigation/hrefs';

// Props 接口
interface CreatePostScreenProps {
  onClose?: () => void;
}

const MAX_TITLE_LENGTH = 100;
const MAX_CONTENT_LENGTH = 2000;
type ChannelOption = {
  id: string;
  name: string;
};

// 表情面板高度
const EMOJI_PANEL_HEIGHT = 280;

// 常用表情列表
const EMOJIS = [
  '😀', '😃', '😄', '😁', '😆', '😅', '🤣', '😂',
  '🙂', '🙃', '😉', '😊', '😇', '🥰', '😍', '🤩',
  '😘', '😗', '😚', '😙', '🥲', '😋', '😛', '😜',
  '🤪', '😝', '🤑', '🤗', '🤭', '🤫', '🤔', '🤐',
  '🤨', '😐', '😑', '😶', '😏', '😒', '🙄',
  '😬', '🤥', '😌', '😔', '😪', '🤤', '😴', '😷',
  '🤒', '🤕', '🤢', '🤮', '🤧', '🥵', '🥶', '🥴',
  '😵', '🤯', '🤠', '🥳', '🥸', '😎', '🤓',
  '🧐', '😕', '😟', '🙁', '☹️', '😮', '😯', '😲',
  '😳', '🥺', '😦', '😧', '😨', '😰', '😥', '😢',
  '😭', '😱', '😖', '😣', '😞', '😓', '😩', '😫',
  '🥱', '😤', '😡', '😠', '🤬', '😈', '👿', '💀',
  '👋', '🤚', '🖐️', '✋', '🖖', '👌', '🤌', '🤏',
  '✌️', '🤞', '🤟', '🤘', '🤙', '👈', '👉', '👆',
  '👍', '👎', '✊', '👊', '🤛', '🤜', '👏', '🙌',
  '👐', '🤲', '🤝', '🙏', '✍️', '💪', '🦾', '🦵',
  '❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍',
  '🤎', '💔', '🩹', '💕', '💞', '💓', '💗', '💖',
  '💘', '💝', '🎉', '🎊', '🎁', '🎈', '✨', '🔥',
  '💯', '💢', '💥', '💫', '💦', '💨', '🕳️',
];

// 动画值
const AnimatedTouchable = Animated.createAnimatedComponent(TouchableOpacity);

const getPublishErrorMessage = (error: unknown): string => {
  if (error instanceof ApiError && error.message?.trim()) {
    return error.message.trim();
  }
  return '发布失败，请重试';
};

export const CreatePostScreen: React.FC<CreatePostScreenProps> = (props) => {
  const colors = useAppColors();
  const styles = useMemo(() => createCreatePostStyles(colors), [colors]);
  const { onClose } = props;
  const router = useRouter();
  const navigation = useNavigation();
  const { mode, postId: postIdParam } = useLocalSearchParams<{ mode?: string; postId?: string }>();
  const isEditMode = mode === 'edit' && !!postIdParam;
  const editPostID = postIdParam || '';
  
  // 响应式布局
  const { isWideScreen, width } = useResponsive();
  const { height: windowHeight } = useWindowDimensions();
  
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [images, setImages] = useState<{ uri: string; uploading?: boolean }[]>([]);
  const [channelOptions, setChannelOptions] = useState<ChannelOption[]>([]);
  const [selectedChannelId, setSelectedChannelId] = useState<string | null>(null);
  const [showChannelPicker, setShowChannelPicker] = useState(false);
  const [showEmojiPanel, setShowEmojiPanel] = useState(false);
  const [posting, setPosting] = useState(false);
  const [loadingPost, setLoadingPost] = useState(false);
  
  // 投票相关状态
  const [isVotePost, setIsVotePost] = useState(false);
  const [voteOptions, setVoteOptions] = useState<string[]>(['', '']); // 默认2个选项

  // 内容输入框引用
  const contentInputRef = React.useRef<TextInput>(null);
  const [selection, setSelection] = useState({ start: 0, end: 0 });

  // 动画值
  const fadeAnim = React.useRef(new Animated.Value(0)).current;
  const slideAnim = React.useRef(new Animated.Value(20)).current;

  // 响应式图片网格配置
  const imagesPerRow = useResponsiveValue({ xs: 3, sm: 3, md: 4, lg: 5, xl: 6 });
  const imageGap = 4;
  const availableWidth = isWideScreen 
    ? Math.min(width, 800) - spacing.lg * 2 
    : width - spacing.lg * 2;
  const imageSize = Math.floor((availableWidth - imageGap * (imagesPerRow - 1)) / imagesPerRow);
  const contentInputMinHeight = Math.max(
    isWideScreen ? 460 : 320,
    Math.floor(windowHeight * (isWideScreen ? 0.56 : 0.5))
  );
  const contentSectionMinHeight = Math.floor(windowHeight * (isWideScreen ? 0.68 : 0.62));

  React.useEffect(() => {
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 250,
        useNativeDriver: true,
      }),
      Animated.timing(slideAnim, {
        toValue: 0,
        duration: 250,
        useNativeDriver: true,
      }),
    ]).start();
  }, []);

  React.useEffect(() => {
    const loadChannels = async () => {
      const list = await channelService.list();
      setChannelOptions(list.map(item => ({ id: item.id, name: item.name })));
    };
    loadChannels();
  }, []);

  React.useLayoutEffect(() => {
    navigation.setOptions({
      headerShown: false,
    });
  }, [navigation]);

  React.useEffect(() => {
    if (!isEditMode || !editPostID) {
      return;
    }

    const loadPostForEdit = async () => {
      setLoadingPost(true);
      try {
        const existingPost = await postService.getPost(editPostID);
        if (!existingPost) {
          Alert.alert('提示', '帖子不存在或已被删除');
          router.back();
          return;
        }
        setTitle(existingPost.title || '');
        setContent(existingPost.content || '');
        setImages((existingPost.images || []).map((img) => ({ uri: img.url, uploading: false })));
      } catch (error) {
        console.error('加载待编辑帖子失败:', error);
        Alert.alert('错误', '加载帖子失败，请稍后重试');
        router.back();
      } finally {
        setLoadingPost(false);
      }
    };

    loadPostForEdit();
  }, [isEditMode, editPostID, router]);

  // 选择图片
  const handlePickImage = async () => {
    const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();

    if (!permissionResult.granted) {
      Alert.alert('权限不足', '需要访问相册权限来选择图片');
      return;
    }

    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: 'images',
      allowsMultipleSelection: true,
      selectionLimit: 0,
      quality: 1,
    });

    if (!result.canceled && result.assets) {
      const newImages = result.assets.map(asset => ({ uri: asset.uri, uploading: true }));
      setImages(prev => [...prev, ...newImages]);

      // 上传图片
      for (let i = 0; i < newImages.length; i++) {
        const asset = result.assets[i];
        const uploadResult = await uploadService.uploadImage({
          uri: asset.uri,
          type: asset.mimeType || 'image/jpeg',
        });

        if (uploadResult) {
          setImages(prev => {
            const updated = [...prev];
            const index = prev.findIndex(img => img.uri === asset.uri);
            if (index !== -1) {
              updated[index] = { uri: uploadResult.url, uploading: false };
            }
            return updated;
          });
        } else {
          Alert.alert('上传失败', '图片上传失败，请重试');
          setImages(prev => prev.filter(img => img.uri !== asset.uri));
        }
      }
    }
  };

  // 拍照
  const handleTakePhoto = async () => {
    const permissionResult = await ImagePicker.requestCameraPermissionsAsync();

    if (!permissionResult.granted) {
      Alert.alert('权限不足', '需要访问相机权限来拍照');
      return;
    }

    const result = await ImagePicker.launchCameraAsync({
      allowsEditing: true,
      quality: 0.8,
    });

    if (!result.canceled && result.assets[0]) {
      const asset = result.assets[0];
      setImages(prev => [...prev, { uri: asset.uri, uploading: true }]);

      // 上传图片
      const uploadResult = await uploadService.uploadImage({
        uri: asset.uri,
        type: asset.mimeType || 'image/jpeg',
      });

      if (uploadResult) {
        setImages(prev => {
          const updated = [...prev];
          const index = prev.findIndex(img => img.uri === asset.uri);
          if (index !== -1) {
            updated[index] = { uri: uploadResult.url, uploading: false };
          }
          return updated;
        });
      } else {
        Alert.alert('上传失败', '图片上传失败，请重试');
        setImages(prev => prev.filter(img => img.uri !== asset.uri));
      }
    }
  };

  // 删除图片
  const handleRemoveImage = (index: number) => {
    setImages(images.filter((_, i) => i !== index));
  };

   // 选择频道（单选，可再次点击取消）
  const handleSelectChannel = useCallback((channelId: string) => {
    setSelectedChannelId(prev => (prev === channelId ? null : channelId));
    setShowChannelPicker(false);
  }, []);

  // 插入表情
  const handleInsertEmoji = (emoji: string) => {
    const newContent = content.slice(0, selection.start) + emoji + content.slice(selection.end);
    setContent(newContent);
    const newPosition = selection.start + emoji.length;
    setSelection({ start: newPosition, end: newPosition });
  };

  // 关闭所有面板
  const closeAllPanels = () => {
    setShowEmojiPanel(false);
    setShowChannelPicker(false);
  };

  // 切换表情面板
  const handleToggleEmojiPanel = () => {
    closeAllPanels();
    setShowEmojiPanel(!showEmojiPanel);
  };

  // 切换频道选择
  const handleToggleChannelPicker = () => {
    closeAllPanels();
    setShowChannelPicker(!showChannelPicker);
  };

  // 切换投票模式
  const handleToggleVote = () => {
    closeAllPanels();
    setIsVotePost(!isVotePost);
  };

  // 添加投票选项
  const handleAddVoteOption = () => {
    if (voteOptions.length < 10) {
      setVoteOptions([...voteOptions, '']);
    }
  };

  // 删除投票选项
  const handleRemoveVoteOption = (index: number) => {
    if (voteOptions.length > 2) {
      setVoteOptions(voteOptions.filter((_, i) => i !== index));
    }
  };

  // 更新投票选项
  const handleUpdateVoteOption = (index: number, value: string) => {
    const newOptions = [...voteOptions];
    newOptions[index] = value;
    setVoteOptions(newOptions);
  };

  // 发布帖子
  const handlePost = async () => {
    // 防止重复点击
    if (posting) return;

    if (!title.trim()) {
      Alert.alert('错误', '请输入帖子标题');
      return;
    }

    if (!content.trim()) {
      Alert.alert('错误', '请输入帖子内容');
      return;
    }

    // 检查是否有图片正在上传
    const uploadingImages = images.filter(img => img.uploading);
    if (uploadingImages.length > 0) {
      Alert.alert('请稍候', '图片正在上传中，请稍后再试');
      return;
    }

    setPosting(true);

    try {
      const imageUrls = images.map(img => img.uri);
      
      if (isVotePost) {
        // 验证投票选项
        const validOptions = voteOptions.filter(opt => opt.trim() !== '');
        if (validOptions.length < 2) {
          Alert.alert('错误', '投票选项至少需要2个');
          setPosting(false);
          return;
        }
        
        // 创建投票帖子
        await voteService.createVotePost({
          title: title.trim(),
          content: content.trim(),
          images: imageUrls,
          channel_id: selectedChannelId || undefined,
          vote_options: validOptions,
        });
        showPrompt({
          type: 'info',
          title: '审核中',
          message: '投票帖已提交，内容审核中，稍后展示',
          duration: 2600,
        });
        router.replace(hrefs.hrefHome());
      } else {
        if (isEditMode && editPostID) {
          const updated = await postService.updatePost(editPostID, {
            title: title.trim(),
            content: content.trim(),
            images: imageUrls,
          });
          if (!updated) {
            throw new Error('更新帖子失败');
          }
          showPrompt({
            type: 'success',
            title: '修改成功',
            message: '帖子内容已更新',
            duration: 2200,
          });
          router.replace(hrefs.hrefHome());
        } else {
          // 创建普通帖子
          await postService.createPost({
            title: title.trim(),
            content: content.trim(),
            images: imageUrls,
            channel_id: selectedChannelId || undefined,
          });
          showPrompt({
            type: 'info',
            title: '审核中',
            message: '帖子已提交，内容审核中，稍后展示',
            duration: 2600,
          });
          router.replace(hrefs.hrefHome());
        }
      }
    } catch (error) {
      console.error('发布帖子失败:', error);
      Alert.alert('错误', getPublishErrorMessage(error));
    } finally {
      setPosting(false);
    }
  };

  // 渲染图片网格
  const renderImageGrid = () => {
    if (images.length === 0) return null;

    return (
      <View style={styles.imageGrid}>
        {images.map((img, index) => (
          <Animated.View
            key={`${img.uri}-${index}`}
            style={[
              styles.imageGridItem,
              { 
                width: imageSize, 
                height: imageSize,
                opacity: fadeAnim, 
                transform: [{ scale: fadeAnim }] 
              }
            ]}
          >
            <Image source={{ uri: img.uri }} style={styles.gridImage} resizeMode="cover" />
            {img.uploading && (
              <View style={styles.uploadingOverlay}>
                <MaterialCommunityIcons name="loading" size={20} color={colors.text.inverse} />
              </View>
            )}
            <TouchableOpacity
              style={styles.removeImageButton}
              onPress={() => handleRemoveImage(index)}
              disabled={img.uploading}
              hitSlop={{ top: 10, right: 10, bottom: 10, left: 10 }}
            >
              <View style={styles.removeImageButtonInner}>
                <MaterialCommunityIcons name="close" size={12} color={colors.text.inverse} />
              </View>
            </TouchableOpacity>
          </Animated.View>
        ))}
        {/* 添加图片按钮 */}
        <TouchableOpacity 
          style={[
            styles.addImageGridButton, 
            { width: imageSize, height: imageSize }
          ]} 
          onPress={handlePickImage}
        >
          <MaterialCommunityIcons name="plus" size={32} color={colors.text.hint} />
        </TouchableOpacity>
      </View>
    );
  };

  // 渲染频道（单选）
  const renderChannelPicker = () => {
    if (!showChannelPicker) return null;

    return (
      <View style={styles.tagsSection}>
        <View style={styles.tagsContainer}>
          {channelOptions.map((channel) => {
            const isSelected = selectedChannelId === channel.id;
            return (
              <TouchableOpacity
                key={channel.id}
                style={[styles.tag, isSelected && styles.channelSelected]}
                onPress={() => handleSelectChannel(channel.id)}
              >
                <Text
                  variant="caption"
                  color={isSelected ? colors.primary.contrast : colors.text.secondary}
                  style={styles.tagText}
                >
                  {channel.name}
                </Text>
              </TouchableOpacity>
            );
          })}
        </View>
        {channelOptions.length === 0 && (
          <Text variant="caption" color={colors.text.hint}>暂无可用频道</Text>
        )}
      </View>
    );
  };

  const selectedChannelName = React.useMemo(() => {
    if (!selectedChannelId) return '';
    return channelOptions.find(c => c.id === selectedChannelId)?.name || '';
  }, [selectedChannelId, channelOptions]);

  const renderChannelEntryRow = () => (
    <TouchableOpacity
      style={styles.channelEntryRow}
      onPress={handleToggleChannelPicker}
      activeOpacity={0.8}
    >
      <Text variant="body" color={colors.text.secondary} style={styles.channelEntryLabel}>
        发表至：
      </Text>
      <View style={styles.channelEntryValueWrap}>
        <Text
          variant="body"
          color={selectedChannelName ? colors.text.primary : colors.text.hint}
          style={styles.channelEntryValue}
        >
          {selectedChannelName || '选择频道'}
        </Text>
        <MaterialCommunityIcons name="chevron-right" size={18} color={colors.text.hint} />
      </View>
    </TouchableOpacity>
  );

  // 渲染投票编辑器
  const renderVoteEditor = () => {
    if (!isVotePost) return null;

    return (
      <View style={isWideScreen && styles.voteEditorWide}>
        <View style={styles.voteEditorHeaderRow}>
          <Text variant="caption" color={colors.text.secondary}>
            已插入投票
          </Text>
          <TouchableOpacity onPress={() => setIsVotePost(false)} activeOpacity={0.7}>
            <Text variant="caption" color={colors.primary.main}>移除投票</Text>
          </TouchableOpacity>
        </View>
        <VoteEditor
          options={voteOptions}
          onAddOption={handleAddVoteOption}
          onRemoveOption={handleRemoveVoteOption}
          onUpdateOption={handleUpdateVoteOption}
          maxOptions={10}
          minOptions={2}
          maxLength={50}
        />
      </View>
    );
  };

  // 渲染内容输入区
  const renderContentSection = () => (
    <View
      style={[
        styles.contentSection,
        contentSectionMinHeight ? { minHeight: contentSectionMinHeight } : null,
      ]}
    >
      {/* 标题输入 */}
      <TextInput
        style={[
          styles.titleInput,
          isWideScreen && styles.titleInputWide,
        ]}
        value={title}
        onChangeText={setTitle}
        placeholder="请输入标题（必填）"
        placeholderTextColor={colors.text.hint}
        maxLength={MAX_TITLE_LENGTH}
      />

      {/* 正文输入 */}
      <TextInput
        ref={contentInputRef}
        style={[
          styles.contentInput,
          isWideScreen && styles.contentInputWide,
          { minHeight: contentInputMinHeight },
        ]}
        value={content}
        onChangeText={setContent}
        placeholder="分享新鲜事..."
        placeholderTextColor={colors.text.hint}
        multiline
        textAlignVertical="top"
        maxLength={MAX_CONTENT_LENGTH}
        onSelectionChange={(e) => setSelection(e.nativeEvent.selection)}
      />

      {/* 作为正文容器的子模块，追加在文本后面 */}
      {renderImageGrid()}
      {renderVoteEditor()}
    </View>
  );

  // 渲染表情面板
  const renderEmojiPanel = () => {
    if (!showEmojiPanel) return null;

    return (
      <View style={[
        styles.emojiPanel,
        isWideScreen && styles.emojiPanelWide,
      ]}>
        <ScrollView
          showsVerticalScrollIndicator={false}
          contentContainerStyle={styles.emojiGrid}
        >
          {EMOJIS.map((emoji, index) => (
            <TouchableOpacity
              key={index}
              style={styles.emojiItem}
              onPress={() => handleInsertEmoji(emoji)}
            >
              <Text style={styles.emojiText}>{emoji}</Text>
            </TouchableOpacity>
          ))}
        </ScrollView>
      </View>
    );
  };

  // 渲染底部工具栏
  const renderToolbar = () => (
    <View style={styles.toolbar}>
      {/* 左侧功能按钮组 */}
      <View style={styles.toolbarLeft}>
        <TouchableOpacity
          style={styles.toolbarButton}
          onPress={handlePickImage}
          disabled={posting}
        >
          <View style={styles.toolbarButtonInner}>
            <MaterialCommunityIcons
              name="image-outline"
              size={24}
              color={colors.text.secondary}
            />
          </View>
        </TouchableOpacity>

        <TouchableOpacity
          style={styles.toolbarButton}
          onPress={handleTakePhoto}
          disabled={posting}
        >
          <View style={styles.toolbarButtonInner}>
            <MaterialCommunityIcons
              name="camera-outline"
              size={24}
              color={colors.text.secondary}
            />
          </View>
        </TouchableOpacity>

        <TouchableOpacity
          style={styles.toolbarButton}
          onPress={handleToggleEmojiPanel}
          disabled={posting}
        >
          <View style={styles.toolbarButtonInner}>
            <MaterialCommunityIcons
              name={showEmojiPanel ? "emoticon-happy" : "emoticon-happy-outline"}
              size={24}
              color={showEmojiPanel ? colors.primary.main : colors.text.secondary}
            />
          </View>
        </TouchableOpacity>

        {/* 投票按钮 */}
        <TouchableOpacity
          style={styles.toolbarButton}
          onPress={handleToggleVote}
          disabled={posting}
        >
          <View style={styles.toolbarButtonInner}>
            <MaterialCommunityIcons
              name={isVotePost ? "vote" : "vote-outline"}
              size={24}
              color={isVotePost ? colors.primary.main : colors.text.secondary}
            />
          </View>
        </TouchableOpacity>
      </View>
    </View>
  );

  const renderTopActionBar = () => (
    <View style={styles.topActionBar}>
      <TouchableOpacity
        onPress={() => (onClose ? onClose() : router.back())}
        style={styles.topActionButton}
        activeOpacity={0.7}
      >
        <Text variant="body" color={colors.text.secondary}>取消</Text>
      </TouchableOpacity>

      <View style={styles.topActionCenter}>
        <Text variant="body" color={colors.text.primary} style={styles.topActionTitle}>
          {isEditMode ? '编辑帖子' : '发布帖子'}
        </Text>
        <Text variant="caption" color={colors.text.hint} style={styles.topActionCount}>
          {content.length}/{MAX_CONTENT_LENGTH}
        </Text>
      </View>

      <TouchableOpacity
        onPress={handlePost}
        disabled={!content.trim() || posting}
        style={[
          styles.topActionButton,
          styles.topActionButtonRight,
          (!content.trim() || posting) && styles.topActionButtonDisabled,
        ]}
        activeOpacity={0.8}
      >
        <Text
          variant="body"
          color={!content.trim() || posting ? colors.text.hint : colors.primary.main}
          style={styles.topActionPublishText}
        >
          {posting ? '发布中' : '发布'}
        </Text>
      </TouchableOpacity>
    </View>
  );

  // 渲染主内容
  const renderMainContent = () => (
    <>
      {renderTopActionBar()}

      <ScrollView
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
        keyboardShouldPersistTaps="handled"
      >
        {/* 内容输入区 */}
        {renderContentSection()}
      </ScrollView>

      {renderChannelEntryRow()}

      {/* 频道选择面板 */}
      {renderChannelPicker()}

      {/* 表情面板 - 位于底部工具栏上方 */}
      {renderEmojiPanel()}

      {/* 底部工具栏 - 重新设计 */}
      {renderToolbar()}
    </>
  );

  return (
    <SafeAreaView style={styles.container} edges={['top', 'bottom']}>
      <KeyboardAvoidingView
        style={styles.flex}
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        keyboardVerticalOffset={Platform.OS === 'ios' ? 90 : 0}
      >
        {isWideScreen ? (
          <ResponsiveContainer maxWidth={800}>
            {loadingPost ? (
              <View style={styles.loadingContainer}>
                <MaterialCommunityIcons name="loading" size={28} color={colors.primary.main} />
                <Text variant="body" color={colors.text.secondary} style={styles.loadingText}>加载帖子中...</Text>
              </View>
            ) : (
              renderMainContent()
            )}
          </ResponsiveContainer>
        ) : (
          loadingPost ? (
            <View style={styles.loadingContainer}>
              <MaterialCommunityIcons name="loading" size={28} color={colors.primary.main} />
              <Text variant="body" color={colors.text.secondary} style={styles.loadingText}>加载帖子中...</Text>
            </View>
          ) : (
            renderMainContent()
          )
        )}
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
};

function createCreatePostStyles(colors: AppColors) {
  return StyleSheet.create({
  flex: {
    flex: 1,
  },
  container: {
    flex: 1,
    backgroundColor: colors.background.paper,
  },
  scrollContent: {
    flexGrow: 1,
    paddingBottom: spacing.xl,
  },
  topActionBar: {
    height: 52,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: spacing.lg,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: colors.divider,
    backgroundColor: colors.background.paper,
  },
  topActionButton: {
    minWidth: 44,
    height: 36,
    justifyContent: 'center',
  },
  topActionButtonRight: {
    alignItems: 'flex-end',
  },
  topActionButtonDisabled: {
    opacity: 0.7,
  },
  topActionTitle: {
    fontSize: fontSizes.lg,
    fontWeight: '600',
  },
  topActionCenter: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  topActionCount: {
    marginTop: 2,
    fontSize: fontSizes.xs,
  },
  topActionPublishText: {
    fontWeight: '600',
  },
  // 内容输入区
  contentSection: {
    flexGrow: 1,
    paddingHorizontal: spacing.lg,
    paddingTop: spacing.md,
  },
  titleInput: {
    fontSize: fontSizes.lg,
    fontWeight: '600',
    color: colors.text.primary,
    paddingVertical: spacing.sm,
    marginBottom: spacing.sm,
  },
  titleInputWide: {
    fontSize: fontSizes.xl,
  },
  contentInput: {
    flexGrow: 1,
    fontSize: fontSizes.md,
    color: colors.text.primary,
    lineHeight: 22,
    paddingVertical: spacing.sm,
  },
  contentInputWide: {
    fontSize: fontSizes.lg,
    lineHeight: 26,
  },
  // 图片网格
  imageGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    paddingHorizontal: 0,
    paddingTop: spacing.md,
    gap: 4,
  },
  imageGridItem: {
    borderRadius: borderRadius.md,
    overflow: 'hidden',
    backgroundColor: colors.background.disabled,
  },
  gridImage: {
    width: '100%',
    height: '100%',
  },
  uploadingOverlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  removeImageButton: {
    position: 'absolute',
    top: 4,
    right: 4,
    zIndex: 10,
  },
  removeImageButtonInner: {
    width: 20,
    height: 20,
    borderRadius: borderRadius.full,
    backgroundColor: 'rgba(0, 0, 0, 0.6)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  addImageGridButton: {
    borderRadius: borderRadius.md,
    borderWidth: 1,
    borderColor: colors.divider,
    borderStyle: 'dashed',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: colors.background.default,
  },
  // 标签
  tagsSection: {
    paddingHorizontal: spacing.lg,
    paddingTop: spacing.md,
    paddingBottom: spacing.sm,
    borderTopWidth: StyleSheet.hairlineWidth,
    borderTopColor: colors.divider,
    backgroundColor: colors.background.paper,
  },
  tagsContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: spacing.sm,
  },
  tag: {
    backgroundColor: colors.background.default,
    borderRadius: borderRadius.full,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.xs,
    borderWidth: 1,
    borderColor: colors.divider,
  },
  channelSelected: {
    backgroundColor: colors.primary.main,
    borderColor: colors.primary.main,
  },
  tagText: {
    fontWeight: '500',
  },
  // 投票编辑器宽屏样式
  voteEditorWide: {
    maxWidth: 600,
    alignSelf: 'center',
    width: '100%',
  },
  voteEditorHeaderRow: {
    marginHorizontal: spacing.lg,
    marginTop: spacing.md,
    marginBottom: -spacing.sm,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  // 底部工具栏
  channelEntryRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: spacing.lg,
    paddingVertical: spacing.sm,
    borderTopWidth: StyleSheet.hairlineWidth,
    borderTopColor: colors.divider,
    backgroundColor: colors.background.paper,
  },
  channelEntryLabel: {
    fontSize: fontSizes.md,
  },
  channelEntryValueWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.xs,
  },
  channelEntryValue: {
    fontSize: fontSizes.md,
  },
  toolbar: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: spacing.lg,
    paddingVertical: spacing.sm,
    backgroundColor: colors.background.paper,
    borderTopWidth: StyleSheet.hairlineWidth,
    borderTopColor: colors.divider,
  },
  toolbarLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.xs,
  },
  toolbarButton: {
    position: 'relative',
  },
  toolbarButtonInner: {
    width: 40,
    height: 40,
    borderRadius: borderRadius.full,
    justifyContent: 'center',
    alignItems: 'center',
  },
  // 表情面板
  emojiPanel: {
    height: EMOJI_PANEL_HEIGHT,
    backgroundColor: colors.background.paper,
    borderTopWidth: StyleSheet.hairlineWidth,
    borderTopColor: colors.divider,
  },
  emojiPanelWide: {
    height: 320,
  },
  emojiGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    padding: spacing.md,
    justifyContent: 'flex-start',
  },
  emojiItem: {
    width: '12.5%',
    aspectRatio: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  emojiText: {
    fontSize: 24,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    gap: spacing.md,
  },
  loadingText: {
    fontSize: fontSizes.md,
  },
  });
}

export default CreatePostScreen;
