import React, { useState, useEffect, useContext, useRef } from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  FlatList,
  Modal,
  ScrollView,
  ActivityIndicator,
  Alert,
  StyleSheet,
  RefreshControl,
  SafeAreaView,
  StatusBar,
  Image,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { AuthContext } from "../context/AuthContext";
import { useTheme } from "../context/ThemeContext";
import {
  loginWebmail,
  getFolders,
  getMessages,
  getMessageDetail,
  sendEmail,
  deleteMessage,
} from "../api/webmail";
import { showNewMailNotification } from "../services/NotificationService";

export default function WebmailScreen() {
  const { colors } = useTheme();
  const {
    accounts,
    activeAccount,
    addWebmailAccount,
    switchWebmailAccount,
    removeWebmailAccount,
  } = useContext(AuthContext);

  // Login form state
  const [loginEmail, setLoginEmail] = useState("");
  const [loginPass, setLoginPass] = useState("");
  const [isLoggingIn, setIsLoggingIn] = useState(false);

  // Account Switcher modal
  const [isAccountModal, setIsAccountModal] = useState(false);
  const [isAddingNewAccount, setIsAddingNewAccount] = useState(false);

  // Mail state
  const [folders, setFolders] = useState([]);
  const [currentFolder, setCurrentFolder] = useState("INBOX");
  const [messages, setMessages] = useState([]);
  const [isLoadingMessages, setIsLoadingMessages] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);

  // Tracking last known message ID for notifications
  const lastMessageUidRef = useRef({});

  // Message Detail modal
  const [selectedMessage, setSelectedMessage] = useState(null);
  const [isLoadingDetail, setIsLoadingDetail] = useState(false);

  // Compose modal
  const [isComposeVisible, setIsComposeVisible] = useState(false);
  const [composeTo, setComposeTo] = useState("");
  const [composeSubject, setComposeSubject] = useState("");
  const [composeBody, setComposeBody] = useState("");
  const [isSending, setIsSending] = useState(false);

  useEffect(() => {
    if (activeAccount) {
      loadFoldersAndMessages();
    }
  }, [activeAccount]);

  // Periodic silent background notification poller
  useEffect(() => {
    if (!activeAccount) return;

    const interval = setInterval(async () => {
      try {
        const mRes = await getMessages(activeAccount.email, activeAccount.password, "INBOX", 1);
        if (mRes.success && mRes.messages && mRes.messages.length > 0) {
          const newest = mRes.messages[0];
          const lastUid = lastMessageUidRef.current[activeAccount.email];

          if (lastUid && newest.uid && newest.uid !== lastUid && !newest.is_seen) {
            showNewMailNotification(
              newest.from_name || newest.from || "Pengirim",
              newest.subject || "(Tanpa Subjek)",
              activeAccount.email
            );
            if (currentFolder === "INBOX") {
              setMessages(mRes.messages);
            }
          }
          if (newest.uid) {
            lastMessageUidRef.current[activeAccount.email] = newest.uid;
          }
        }
      } catch (err) {}
    }, 15000);

    return () => clearInterval(interval);
  }, [activeAccount, currentFolder]);

  const handleLogin = async () => {
    if (!loginEmail || !loginPass) {
      Alert.alert("Perhatian", "Silakan masukkan email dan kata sandi.");
      return;
    }
    setIsLoggingIn(true);
    try {
      const res = await loginWebmail(loginEmail.trim(), loginPass);
      if (res.success) {
        await addWebmailAccount(loginEmail.trim(), loginPass);
        setLoginEmail("");
        setLoginPass("");
        setIsAddingNewAccount(false);
        setIsAccountModal(false);
      } else {
        Alert.alert("Gagal Masuk", res.error || "Email atau kata sandi salah.");
      }
    } catch (e) {
      Alert.alert("Kesalahan", e.message || "Gagal menghubungi server.");
    } finally {
      setIsLoggingIn(false);
    }
  };

  const loadFoldersAndMessages = async () => {
    if (!activeAccount) return;
    try {
      const fRes = await getFolders(activeAccount.email, activeAccount.password);
      if (fRes.success && fRes.folders) {
        setFolders(fRes.folders);
      }
      fetchMessages(currentFolder);
    } catch (e) {
      console.log("Error loading folders:", e);
    }
  };

  const fetchMessages = async (folder) => {
    if (!activeAccount) return;
    setIsLoadingMessages(true);
    try {
      const mRes = await getMessages(activeAccount.email, activeAccount.password, folder);
      if (mRes.success && mRes.messages) {
        setMessages(mRes.messages);
        if (mRes.messages.length > 0 && mRes.messages[0].uid) {
          lastMessageUidRef.current[activeAccount.email] = mRes.messages[0].uid;
        }
      }
    } catch (e) {
      console.log("Error fetching messages:", e);
    } finally {
      setIsLoadingMessages(false);
      setIsRefreshing(false);
    }
  };

  const handleRefresh = () => {
    setIsRefreshing(true);
    loadFoldersAndMessages();
  };

  const handleSelectFolder = (folderId) => {
    setCurrentFolder(folderId);
    fetchMessages(folderId);
  };

  const handleOpenMessage = async (item) => {
    setSelectedMessage({ ...item, body: "Memuat isi surat..." });
    setIsLoadingDetail(true);
    try {
      const res = await getMessageDetail(
        activeAccount.email,
        activeAccount.password,
        currentFolder,
        item.uid || item.id
      );
      if (res.success && res.message) {
        setSelectedMessage(res.message);
      }
    } catch (e) {
      Alert.alert("Kesalahan", "Gagal memuat detail surat.");
    } finally {
      setIsLoadingDetail(false);
    }
  };

  const handleDeleteCurrentMessage = async () => {
    if (!selectedMessage || !activeAccount) return;
    Alert.alert("Hapus Pesan", "Yakin ingin menghapus email ini?", [
      { text: "Batal", style: "cancel" },
      {
        text: "Hapus",
        style: "destructive",
        onPress: async () => {
          try {
            await deleteMessage(
              activeAccount.email,
              activeAccount.password,
              currentFolder,
              selectedMessage.uid || selectedMessage.id
            );
            setSelectedMessage(null);
            fetchMessages(currentFolder);
          } catch (e) {
            Alert.alert("Gagal", "Gagal menghapus pesan.");
          }
        },
      },
    ]);
  };

  const handleSendCompose = async () => {
    if (!composeTo || !composeSubject || !composeBody) {
      Alert.alert("Perhatian", "Penerima, subjek, dan pesan wajib diisi.");
      return;
    }
    setIsSending(true);
    try {
      const res = await sendEmail(
        activeAccount.email,
        activeAccount.password,
        composeTo.trim(),
        composeSubject,
        composeBody
      );
      if (res.success) {
        Alert.alert("Terkirim", "Email berhasil dikirim!");
        setIsComposeVisible(false);
        setComposeTo("");
        setComposeSubject("");
        setComposeBody("");
        fetchMessages(currentFolder);
      } else {
        Alert.alert("Gagal Mengirim", res.error || "Terjadi kesalahan.");
      }
    } catch (e) {
      Alert.alert("Kesalahan", e.message || "Gagal mengirim email.");
    } finally {
      setIsSending(false);
    }
  };

  // 1. Unauthenticated Login Screen
  if (!activeAccount) {
    return (
      <SafeAreaView style={[styles.container, { backgroundColor: colors.bg }]}>
        <StatusBar barStyle="light-content" />
        <ScrollView contentContainerStyle={styles.authScroll}>
          <View style={styles.authHeader}>
            <Image
              source={require("../assets/logo.png")}
              style={styles.logoImage}
              resizeMode="contain"
            />
            <Text style={[styles.title, { color: colors.text }]}>Ruang.Email Webmail</Text>
            <Text style={[styles.subtitle, { color: colors.textMuted }]}>
              Mendukung multi-akun & multi-domain tanpa batas
            </Text>
          </View>

          <View style={[styles.authCard, { backgroundColor: colors.card, borderColor: colors.cardBorder }]}>
            <Text style={[styles.label, { color: colors.textMuted }]}>Alamat Email</Text>
            <TextInput
              style={[styles.input, { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
              placeholder="nama@domainanda.com"
              placeholderTextColor={colors.textDim}
              value={loginEmail}
              onChangeText={setLoginEmail}
              autoCapitalize="none"
              keyboardType="email-address"
            />

            <Text style={[styles.label, { color: colors.textMuted, marginTop: 14 }]}>Kata Sandi</Text>
            <TextInput
              style={[styles.input, { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
              placeholder="••••••••"
              placeholderTextColor={colors.textDim}
              value={loginPass}
              onChangeText={setLoginPass}
              secureTextEntry
            />

            <TouchableOpacity
              style={[styles.primaryButton, { backgroundColor: colors.primary }]}
              onPress={handleLogin}
              disabled={isLoggingIn}
            >
              {isLoggingIn ? (
                <ActivityIndicator color="#fff" />
              ) : (
                <Text style={styles.buttonText}>Buka Kotak Surat</Text>
              )}
            </TouchableOpacity>
          </View>
        </ScrollView>
      </SafeAreaView>
    );
  }

  // 2. Authenticated Native Webmail App
  return (
    <SafeAreaView style={[styles.container, { backgroundColor: colors.bg }]}>
      <StatusBar barStyle="light-content" />

      {/* App Header with Interactive Multi-Account Dropdown */}
      <View style={[styles.topBar, { borderBottomColor: colors.cardBorder }]}>
        <TouchableOpacity
          style={styles.accountSelectorBtn}
          onPress={() => setIsAccountModal(true)}
          activeOpacity={0.7}
        >
          <View style={[styles.avatar, { backgroundColor: colors.primary }]}>
            <Text style={styles.avatarText}>
              {activeAccount.email.charAt(0).toUpperCase()}
            </Text>
          </View>
          <View>
            <View style={{ flexDirection: "row", alignItems: "center", gap: 4 }}>
              <Text style={[styles.userName, { color: colors.text }]}>{activeAccount.email}</Text>
              <Ionicons name="chevron-down" size={14} color={colors.textMuted} />
            </View>
            <Text style={[styles.userStatus, { color: colors.primary }]}>
              ● @{activeAccount.domain} • {accounts.length} Akun Terhubung
            </Text>
          </View>
        </TouchableOpacity>

        <View style={styles.topActions}>
          <TouchableOpacity onPress={handleRefresh} style={styles.iconBtn}>
            <Ionicons name="refresh" size={20} color={colors.textMuted} />
          </TouchableOpacity>
          <TouchableOpacity onPress={() => setIsAccountModal(true)} style={styles.iconBtn}>
            <Ionicons name="people-outline" size={22} color={colors.primary} />
          </TouchableOpacity>
        </View>
      </View>

      {/* Folders Chips */}
      <View style={styles.folderRow}>
        <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.folderScroll}>
          {folders.map((f) => {
            const isActive = f.id === currentFolder;
            return (
              <TouchableOpacity
                key={f.id}
                onPress={() => handleSelectFolder(f.id)}
                style={[
                  styles.folderChip,
                  {
                    backgroundColor: isActive ? colors.primaryLight : colors.card,
                    borderColor: isActive ? colors.primary : colors.cardBorder,
                  },
                ]}
              >
                <Text
                  style={[
                    styles.folderChipText,
                    { color: isActive ? colors.primary : colors.textMuted },
                  ]}
                >
                  {f.name}
                </Text>
                {f.unseen > 0 && (
                  <View style={[styles.badge, { backgroundColor: colors.primary }]}>
                    <Text style={styles.badgeText}>{f.unseen}</Text>
                  </View>
                )}
              </TouchableOpacity>
            );
          })}
        </ScrollView>
      </View>

      {/* Message List */}
      {isLoadingMessages && !isRefreshing ? (
        <View style={styles.centerContainer}>
          <ActivityIndicator size="large" color={colors.primary} />
          <Text style={[styles.loadingText, { color: colors.textMuted }]}>Memuat surat...</Text>
        </View>
      ) : messages.length === 0 ? (
        <View style={styles.centerContainer}>
          <Ionicons name="file-tray-outline" size={54} color={colors.textDim} />
          <Text style={[styles.emptyText, { color: colors.textMuted }]}>Kotak Surat Kosong</Text>
          <Text style={[styles.emptySubText, { color: colors.textDim }]}>
            Tidak ada pesan di folder {currentFolder}
          </Text>
        </View>
      ) : (
        <FlatList
          data={messages}
          keyExtractor={(item, idx) => item.uid ? String(item.uid) : String(idx)}
          refreshControl={
            <RefreshControl refreshing={isRefreshing} onRefresh={handleRefresh} tintColor={colors.primary} />
          }
          renderItem={({ item }) => {
            const isUnread = !item.is_seen;
            const fromStr = item.from_name || item.from || "Pengirim";
            return (
              <TouchableOpacity
                onPress={() => handleOpenMessage(item)}
                style={[
                  styles.mailItem,
                  {
                    backgroundColor: isUnread ? colors.subCard : colors.card,
                    borderColor: colors.cardBorder,
                  },
                ]}
              >
                <View style={[styles.mailAvatar, { backgroundColor: isUnread ? colors.primary : colors.cardBorder }]}>
                  <Text style={styles.mailAvatarText}>
                    {fromStr.charAt(0).toUpperCase()}
                  </Text>
                </View>

                <View style={styles.mailBody}>
                  <View style={styles.mailHeaderRow}>
                    <Text
                      numberOfLines={1}
                      style={[
                        styles.mailFrom,
                        { color: colors.text, fontWeight: isUnread ? "bold" : "600" },
                      ]}
                    >
                      {fromStr}
                    </Text>
                    <Text style={[styles.mailTime, { color: colors.textDim }]}>
                      {item.date_human || item.date || ""}
                    </Text>
                  </View>

                  <Text
                    numberOfLines={1}
                    style={[
                      styles.mailSubject,
                      { color: isUnread ? colors.text : colors.textMuted, fontWeight: isUnread ? "700" : "500" },
                    ]}
                  >
                    {item.subject || "(Tanpa Subjek)"}
                  </Text>

                  <Text numberOfLines={2} style={[styles.mailSnippet, { color: colors.textDim }]}>
                    {item.snippet || item.body_preview || ""}
                  </Text>
                </View>

                {isUnread && <View style={[styles.unreadDot, { backgroundColor: colors.primary }]} />}
              </TouchableOpacity>
            );
          }}
        />
      )}

      {/* Floating Compose Button */}
      <TouchableOpacity
        style={[styles.fab, { backgroundColor: colors.primary }]}
        onPress={() => setIsComposeVisible(true)}
      >
        <Ionicons name="create-outline" size={24} color="#fff" />
        <Text style={styles.fabText}>Tulis Pesan</Text>
      </TouchableOpacity>

      {/* Multi-Account Switcher Modal */}
      <Modal visible={isAccountModal} animationType="slide" presentationStyle="pageSheet">
        <SafeAreaView style={[styles.modalContainer, { backgroundColor: colors.bg }]}>
          <View style={[styles.modalHeader, { borderBottomColor: colors.cardBorder }]}>
            <TouchableOpacity onPress={() => setIsAccountModal(false)} style={styles.iconBtn}>
              <Ionicons name="close" size={24} color={colors.text} />
            </TouchableOpacity>
            <Text style={[styles.modalTitle, { color: colors.text }]}>Kelola Akun Email</Text>
            <View style={{ width: 24 }} />
          </View>

          <ScrollView style={{ padding: 16 }}>
            <Text style={[styles.sectionHeading, { color: colors.textMuted }]}>
              AKUN TERHUBUNG ({accounts.length})
            </Text>

            {accounts.map((acc) => {
              const isCurrent = acc.email.toLowerCase() === activeAccount.email.toLowerCase();
              return (
                <View
                  key={acc.email}
                  style={[
                    styles.accountCard,
                    {
                      backgroundColor: isCurrent ? colors.subCard : colors.card,
                      borderColor: isCurrent ? colors.primary : colors.cardBorder,
                    },
                  ]}
                >
                  <TouchableOpacity
                    style={{ flex: 1, flexDirection: "row", alignItems: "center", gap: 12 }}
                    onPress={() => {
                      switchWebmailAccount(acc.email);
                      setIsAccountModal(false);
                    }}
                  >
                    <View style={[styles.avatar, { backgroundColor: isCurrent ? colors.primary : colors.cardBorder }]}>
                      <Text style={styles.avatarText}>{acc.email.charAt(0).toUpperCase()}</Text>
                    </View>
                    <View style={{ flex: 1 }}>
                      <Text style={[styles.accountEmail, { color: colors.text, fontWeight: isCurrent ? "bold" : "600" }]}>
                        {acc.email}
                      </Text>
                      <Text style={[styles.accountDomain, { color: colors.textDim }]}>
                        Domain: @{acc.domain} {isCurrent ? "• Aktif Sekarang" : ""}
                      </Text>
                    </View>
                  </TouchableOpacity>

                  {isCurrent ? (
                    <Ionicons name="checkmark-circle" size={22} color={colors.primary} />
                  ) : (
                    <TouchableOpacity
                      onPress={() => removeWebmailAccount(acc.email)}
                      style={{ padding: 6 }}
                    >
                      <Ionicons name="close-circle-outline" size={20} color={colors.danger} />
                    </TouchableOpacity>
                  )}
                </View>
              );
            })}

            {/* Add New Account Form */}
            {isAddingNewAccount ? (
              <View style={[styles.authCard, { backgroundColor: colors.card, borderColor: colors.cardBorder, marginTop: 16 }]}>
                <Text style={[styles.cardTitle, { color: colors.text }]}>Tambah Akun Email Baru</Text>
                <Text style={[styles.cardSub, { color: colors.textMuted }]}>
                  Bisa menggunakan domain apa pun yang terdaftar di Ruang.Email
                </Text>

                <Text style={[styles.label, { color: colors.textMuted }]}>Alamat Email</Text>
                <TextInput
                  style={[styles.input, { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
                  placeholder="anda@domainlain.com"
                  placeholderTextColor={colors.textDim}
                  value={loginEmail}
                  onChangeText={setLoginEmail}
                  autoCapitalize="none"
                  keyboardType="email-address"
                />

                <Text style={[styles.label, { color: colors.textMuted, marginTop: 12 }]}>Kata Sandi</Text>
                <TextInput
                  style={[styles.input, { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
                  placeholder="••••••••"
                  placeholderTextColor={colors.textDim}
                  value={loginPass}
                  onChangeText={setLoginPass}
                  secureTextEntry
                />

                <View style={{ flexDirection: "row", gap: 10, marginTop: 16 }}>
                  <TouchableOpacity
                    style={[styles.primaryButton, { flex: 1, backgroundColor: colors.subCard }]}
                    onPress={() => setIsAddingNewAccount(false)}
                  >
                    <Text style={[styles.buttonText, { color: colors.textMuted }]}>Batal</Text>
                  </TouchableOpacity>

                  <TouchableOpacity
                    style={[styles.primaryButton, { flex: 2, backgroundColor: colors.primary }]}
                    onPress={handleLogin}
                    disabled={isLoggingIn}
                  >
                    {isLoggingIn ? (
                      <ActivityIndicator color="#fff" />
                    ) : (
                      <Text style={styles.buttonText}>Masuk & Simpan</Text>
                    )}
                  </TouchableOpacity>
                </View>
              </View>
            ) : (
              <TouchableOpacity
                style={[styles.addAccountBtn, { borderColor: colors.primary, backgroundColor: colors.primaryLight }]}
                onPress={() => setIsAddingNewAccount(true)}
              >
                <Ionicons name="person-add-outline" size={18} color={colors.primary} />
                <Text style={[styles.addAccountBtnText, { color: colors.primary }]}>
                  + Tambah Akun Email Lain (Multi-Domain)
                </Text>
              </TouchableOpacity>
            )}

            <TouchableOpacity
              style={[styles.logoutActiveBtn, { borderColor: colors.dangerLight, marginTop: 24 }]}
              onPress={() => {
                removeWebmailAccount(activeAccount.email);
                setIsAccountModal(false);
              }}
            >
              <Ionicons name="log-out-outline" size={18} color={colors.danger} />
              <Text style={{ color: colors.danger, fontWeight: "bold", fontSize: 13 }}>
                Keluar dari {activeAccount.email}
              </Text>
            </TouchableOpacity>
          </ScrollView>
        </SafeAreaView>
      </Modal>

      {/* Native Message Detail Modal */}
      <Modal visible={!!selectedMessage} animationType="slide" presentationStyle="pageSheet">
        <SafeAreaView style={[styles.modalContainer, { backgroundColor: colors.bg }]}>
          <View style={[styles.modalHeader, { borderBottomColor: colors.cardBorder }]}>
            <TouchableOpacity onPress={() => setSelectedMessage(null)} style={styles.iconBtn}>
              <Ionicons name="arrow-back" size={24} color={colors.text} />
            </TouchableOpacity>
            <Text style={[styles.modalTitle, { color: colors.text }]}>Detail Surat</Text>
            <TouchableOpacity onPress={handleDeleteCurrentMessage} style={styles.iconBtn}>
              <Ionicons name="trash-outline" size={22} color={colors.danger} />
            </TouchableOpacity>
          </View>

          {selectedMessage && (
            <ScrollView style={styles.detailScroll}>
              <Text style={[styles.detailSubject, { color: colors.text }]}>
                {selectedMessage.subject || "(Tanpa Subjek)"}
              </Text>

              <View style={[styles.senderBox, { backgroundColor: colors.card, borderColor: colors.cardBorder }]}>
                <View style={[styles.mailAvatar, { backgroundColor: colors.primary }]}>
                  <Text style={styles.mailAvatarText}>
                    {(selectedMessage.from || "P").charAt(0).toUpperCase()}
                  </Text>
                </View>
                <View style={{ flex: 1 }}>
                  <Text style={[styles.senderName, { color: colors.text }]}>
                    {selectedMessage.from}
                  </Text>
                  <Text style={[styles.senderTime, { color: colors.textDim }]}>
                    Kepada: {selectedMessage.to || activeAccount.email} • {selectedMessage.date}
                  </Text>
                </View>
              </View>

              <View style={[styles.detailBodyBox, { backgroundColor: colors.card, borderColor: colors.cardBorder }]}>
                {isLoadingDetail ? (
                  <ActivityIndicator color={colors.primary} />
                ) : (
                  <Text style={[styles.detailBodyText, { color: colors.text }]}>
                    {selectedMessage.body || selectedMessage.snippet || "(Surat tidak berisi teks)"}
                  </Text>
                )}
              </View>

              <TouchableOpacity
                style={[styles.replyBtn, { backgroundColor: colors.primaryLight, borderColor: colors.primary }]}
                onPress={() => {
                  const toEmail = selectedMessage.from_email || (selectedMessage.from && selectedMessage.from.includes('<') ? selectedMessage.from.split('<')[1].replace('>', '').trim() : selectedMessage.from);
                  const cleanSubject = `Re: ${(selectedMessage.subject || '').replace(/^(Re:\s*)+/i, '')}`;
                  const quoteBody = `\n\n--- Pada ${selectedMessage.date || ''}, ${selectedMessage.from || ''} menulis: ---\n${selectedMessage.body || selectedMessage.snippet || ''}`;
                  setComposeTo(toEmail);
                  setComposeSubject(cleanSubject);
                  setComposeBody(quoteBody);
                  setSelectedMessage(null);
                  setIsComposeVisible(true);
                }}
              >
                <Ionicons name="arrow-undo-outline" size={18} color={colors.primary} />
                <Text style={[styles.replyBtnText, { color: colors.primary }]}>Balas Surat Ini</Text>
              </TouchableOpacity>
            </ScrollView>
          )}
        </SafeAreaView>
      </Modal>

      {/* Native Compose Modal */}
      <Modal visible={isComposeVisible} animationType="slide" presentationStyle="pageSheet">
        <SafeAreaView style={[styles.modalContainer, { backgroundColor: colors.bg }]}>
          <View style={[styles.modalHeader, { borderBottomColor: colors.cardBorder }]}>
            <TouchableOpacity onPress={() => setIsComposeVisible(false)} style={styles.iconBtn}>
              <Ionicons name="close" size={24} color={colors.text} />
            </TouchableOpacity>
            <Text style={[styles.modalTitle, { color: colors.text }]}>Tulis Surat Baru</Text>
            <TouchableOpacity
              onPress={handleSendCompose}
              disabled={isSending}
              style={[styles.sendHeaderBtn, { backgroundColor: colors.primary }]}
            >
              {isSending ? (
                <ActivityIndicator size="small" color="#fff" />
              ) : (
                <>
                  <Ionicons name="paper-plane-outline" size={16} color="#fff" />
                  <Text style={styles.sendHeaderBtnText}>Kirim</Text>
                </>
              )}
            </TouchableOpacity>
          </View>

          <ScrollView style={styles.composeForm}>
            <Text style={[styles.label, { color: colors.textMuted }]}>Pengirim</Text>
            <Text style={[styles.staticFrom, { color: colors.primary }]}>{activeAccount.email}</Text>

            <Text style={[styles.label, { color: colors.textMuted, marginTop: 12 }]}>Kepada</Text>
            <TextInput
              style={[styles.input, { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
              placeholder="penerima@tujuan.com"
              placeholderTextColor={colors.textDim}
              value={composeTo}
              onChangeText={setComposeTo}
              autoCapitalize="none"
              keyboardType="email-address"
            />

            <Text style={[styles.label, { color: colors.textMuted, marginTop: 12 }]}>Subjek</Text>
            <TextInput
              style={[styles.input, { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text }]}
              placeholder="Judul pesan..."
              placeholderTextColor={colors.textDim}
              value={composeSubject}
              onChangeText={setComposeSubject}
            />

            <Text style={[styles.label, { color: colors.textMuted, marginTop: 12 }]}>Isi Pesan</Text>
            <TextInput
              style={[
                styles.input,
                styles.multilineInput,
                { backgroundColor: colors.inputBg, borderColor: colors.inputBorder, color: colors.text },
              ]}
              placeholder="Tulis pesan Anda di sini..."
              placeholderTextColor={colors.textDim}
              value={composeBody}
              onChangeText={setComposeBody}
              multiline
              textAlignVertical="top"
            />
          </ScrollView>
        </SafeAreaView>
      </Modal>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  authScroll: { padding: 24, justifyContent: "center", minHeight: "100%" },
  authHeader: { alignItems: "center", marginBottom: 24 },
  logoImage: { width: 140, height: 140, marginBottom: 12 },
  title: { fontSize: 24, fontWeight: "800", marginBottom: 6 },
  subtitle: { fontSize: 13, textAlign: "center", lineHeight: 18 },
  authCard: { borderRadius: 16, padding: 20, borderWidth: 1 },
  label: { fontSize: 12, fontWeight: "600", marginBottom: 6 },
  input: { borderWidth: 1, borderRadius: 10, paddingHorizontal: 14, paddingVertical: 12, fontSize: 14 },
  multilineInput: { height: 220 },
  primaryButton: { marginTop: 20, borderRadius: 12, paddingVertical: 14, alignItems: "center" },
  buttonText: { color: "#fff", fontWeight: "700", fontSize: 15 },
  topBar: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", paddingHorizontal: 16, paddingVertical: 10, borderBottomWidth: 1 },
  accountSelectorBtn: { flexDirection: "row", alignItems: "center", gap: 10, flex: 1 },
  avatar: { width: 38, height: 38, borderRadius: 19, alignItems: "center", justifyContent: "center" },
  avatarText: { color: "#fff", fontWeight: "bold", fontSize: 16 },
  userName: { fontSize: 14, fontWeight: "700" },
  userStatus: { fontSize: 11, fontWeight: "600" },
  topActions: { flexDirection: "row", gap: 6, alignItems: "center" },
  iconBtn: { padding: 6 },
  folderRow: { paddingVertical: 10 },
  folderScroll: { paddingHorizontal: 16, gap: 8 },
  folderChip: { flexDirection: "row", alignItems: "center", paddingHorizontal: 14, paddingVertical: 8, borderRadius: 20, borderWidth: 1, gap: 6 },
  folderChipText: { fontSize: 12, fontWeight: "600" },
  badge: { borderRadius: 10, paddingHorizontal: 6, paddingVertical: 1 },
  badgeText: { color: "#fff", fontSize: 10, fontWeight: "bold" },
  centerContainer: { flex: 1, alignItems: "center", justifyContent: "center", padding: 20 },
  loadingText: { marginTop: 10, fontSize: 13 },
  emptyText: { fontSize: 16, fontWeight: "700", marginTop: 12 },
  emptySubText: { fontSize: 13, marginTop: 4 },
  mailItem: { flexDirection: "row", padding: 14, marginHorizontal: 16, marginBottom: 8, borderRadius: 14, borderWidth: 1, alignItems: "center" },
  mailAvatar: { width: 42, height: 42, borderRadius: 21, alignItems: "center", justifyContent: "center", marginRight: 12 },
  mailAvatarText: { color: "#fff", fontWeight: "bold", fontSize: 16 },
  mailBody: { flex: 1 },
  mailHeaderRow: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", marginBottom: 2 },
  mailFrom: { fontSize: 14 },
  mailTime: { fontSize: 11 },
  mailSubject: { fontSize: 13, marginBottom: 4 },
  mailSnippet: { fontSize: 12, lineHeight: 16 },
  unreadDot: { width: 8, height: 8, borderRadius: 4, marginLeft: 8 },
  fab: { position: "absolute", bottom: 20, right: 20, flexDirection: "row", alignItems: "center", gap: 8, paddingHorizontal: 18, paddingVertical: 14, borderRadius: 30, elevation: 5, shadowColor: "#000", shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.3, shadowRadius: 5 },
  fabText: { color: "#fff", fontWeight: "700", fontSize: 14 },
  modalContainer: { flex: 1 },
  modalHeader: { flexDirection: "row", alignItems: "center", justifyContent: "space-between", paddingHorizontal: 16, paddingVertical: 14, borderBottomWidth: 1 },
  modalTitle: { fontSize: 16, fontWeight: "bold" },
  sendHeaderBtn: { flexDirection: "row", alignItems: "center", gap: 6, paddingHorizontal: 14, paddingVertical: 7, borderRadius: 16 },
  sendHeaderBtnText: { color: "#fff", fontWeight: "bold", fontSize: 13 },
  detailScroll: { padding: 16 },
  detailSubject: { fontSize: 20, fontWeight: "800", marginBottom: 16, lineHeight: 26 },
  senderBox: { flexDirection: "row", alignItems: "center", padding: 12, borderRadius: 12, borderWidth: 1, marginBottom: 16 },
  senderName: { fontSize: 14, fontWeight: "700" },
  senderTime: { fontSize: 12, marginTop: 2 },
  detailBodyBox: { padding: 16, borderRadius: 14, borderWidth: 1, minHeight: 200, marginBottom: 20 },
  detailBodyText: { fontSize: 14, lineHeight: 22 },
  replyBtn: { flexDirection: "row", alignItems: "center", justifyContent: "center", gap: 8, paddingVertical: 12, borderRadius: 12, borderWidth: 1, marginBottom: 40 },
  replyBtnText: { fontWeight: "700", fontSize: 14 },
  composeForm: { padding: 16 },
  staticFrom: { fontSize: 14, fontWeight: "bold", marginBottom: 6 },
  sectionHeading: { fontSize: 11, fontWeight: "bold", letterSpacing: 1, marginBottom: 10 },
  accountCard: { flexDirection: "row", alignItems: "center", padding: 14, borderRadius: 14, borderWidth: 1, marginBottom: 10 },
  accountEmail: { fontSize: 14 },
  accountDomain: { fontSize: 12, marginTop: 2 },
  addAccountBtn: { flexDirection: "row", alignItems: "center", justifyContent: "center", gap: 8, paddingVertical: 14, borderRadius: 14, borderWidth: 1, marginTop: 12 },
  addAccountBtnText: { fontWeight: "bold", fontSize: 13 },
  logoutActiveBtn: { flexDirection: "row", alignItems: "center", justifyContent: "center", gap: 6, paddingVertical: 12, borderRadius: 12, borderWidth: 1 },
  cardTitle: { fontSize: 16, fontWeight: "bold" },
  cardSub: { fontSize: 12, marginTop: 2, marginBottom: 14 },
});
