import React, { useEffect, useMemo, useState } from "react";
import {
  Alert,
  Pressable,
  ScrollView,
  Share,
  StyleSheet,
  Switch,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useSession } from "../state/session-context";
import { formatTransactionKind, getLocale, useI18n } from "../i18n";
import { useTheme } from "../theme";
import type { AppTheme } from "../theme";
import type { Player, SessionSnapshot, Transaction } from "../shared/types";
import { getApiBaseUrl } from "../config/api";

function initials(value: string) {
  return value
    .split(" ")
    .filter(Boolean)
    .map((part) => part[0])
    .join("")
    .slice(0, 2)
    .toUpperCase();
}

function formatMoney(amount: number) {
  return `₦${amount.toLocaleString()}`;
}

function formatTransactionTimestamp(value: number) {
  const date = new Date(value);
  const now = new Date();
  const sameDay =
    date.getFullYear() === now.getFullYear() &&
    date.getMonth() === now.getMonth() &&
    date.getDate() === now.getDate();
  const time = date.toLocaleTimeString(getLocale(), { hour: "2-digit", minute: "2-digit" });
  if (sameDay) return time;
  const day = date.toLocaleDateString(getLocale(), { month: "short", day: "numeric" });
  return `${day} ${time}`;
}

function getTransactionLabel(
  kind: Transaction["kind"],
  note: string | null | undefined,
  t: ReturnType<typeof useI18n>["t"],
): string {
  if (kind === "banker_adjust" || kind === "banker_force_transfer") {
    const trimmed = note?.trim();
    return trimmed || t("common.noReason");
  }
  return formatTransactionKind(kind, t);
}

function getTransactionDisplay(
  transaction: Transaction,
  viewerId: string | null | undefined,
  players: Player[],
  t: ReturnType<typeof useI18n>["t"],
): { label: string; subtitle: string; amount: string; outgoing: boolean } {
  const absAmount = Math.abs(transaction.amount);
  const label = getTransactionLabel(transaction.kind, transaction.note, t);
  const findPlayer = (id: string | null) => players.find((player) => player.id === id);
  const from = findPlayer(transaction.fromId);
  const to = findPlayer(transaction.toId);
  let outgoing = false;
  let counterparty: string = t("common.bank");
  const timeLabel: string = formatTransactionTimestamp(transaction.createdAt);

  if (transaction.kind === "banker_adjust") {
    outgoing = transaction.amount < 0;
    counterparty = t("common.bank");
  } else if (transaction.kind === "transfer" || transaction.kind === "banker_force_transfer") {
    if (viewerId && transaction.fromId === viewerId) {
      outgoing = true;
      counterparty = to?.name ?? t("common.player");
    } else if (viewerId && transaction.toId === viewerId) {
      outgoing = false;
      counterparty = from?.name ?? t("common.player");
    } else {
      outgoing = true;
      counterparty = to?.name ?? t("common.player");
    }
  }

  return {
    label,
    subtitle: viewerId
      ? `${outgoing ? t("common.to") : t("common.from")} ${counterparty} · ${timeLabel}`
      : transaction.kind === "banker_adjust"
      ? outgoing
        ? `${to?.name ?? t("common.player")} → ${t("common.bank")} · ${timeLabel}`
        : `${t("common.bank")} → ${to?.name ?? t("common.player")} · ${timeLabel}`
      : `${from?.name ?? t("common.player")} → ${to?.name ?? t("common.player")} · ${timeLabel}`,
    amount: `${outgoing ? "-" : ""}${formatMoney(absAmount)}`,
    outgoing,
  };
}

export default function BankerToolsScreen() {
  const manager = useSession();
  const { t } = useI18n();
  const theme = useTheme();
  const styles = useMemo(() => createStyles(theme), [theme]);
  const placeholderColor = theme.colors.placeholder;
  const [tab, setTab] = useState<"players" | "admin">("players");
  const [selectedPlayerId, setSelectedPlayerId] = useState("");
  const [adjustAmount, setAdjustAmount] = useState("");
  const [adjustNote, setAdjustNote] = useState("");
  const [forceTo, setForceTo] = useState("");
  const [forceAmount, setForceAmount] = useState("");
  const [forceNote, setForceNote] = useState("");
  const [dummyName, setDummyName] = useState("");
  const [dummyBalance, setDummyBalance] = useState("1500");
  const [blackoutReason, setBlackoutReason] = useState("");
  const [autoSaveEnabled, setAutoSaveEnabled] = useState(false);
  const [autoSaveInterval, setAutoSaveInterval] = useState("3");
  const [autoSaveLimit, setAutoSaveLimit] = useState("5");
  const [autoSaveEntries, setAutoSaveEntries] = useState<
    { id: string; savedAt: number; state: SessionSnapshot }[]
  >([]);
  const [importJson, setImportJson] = useState("");
  const [autoSaveStatus, setAutoSaveStatus] = useState<string | null>(null);
  const pendingRequests = useMemo(
    () =>
      manager.session?.takeoverRequests.filter((request) => request.status === "pending") ??
      [],
    [manager.session?.takeoverRequests],
  );

  const autoSaveKey = `negopoly:autosave:${manager.sessionId}`;
  const autoSaveSettingsKey = `${autoSaveKey}:settings`;

  useEffect(() => {
    if (!manager.sessionId) return;
    let mounted = true;
    async function loadSettings() {
      try {
        const raw = await AsyncStorage.getItem(autoSaveSettingsKey);
        if (!raw || !mounted) return;
        const settings = JSON.parse(raw) as {
          enabled?: boolean;
          intervalMinutes?: number;
          maxEntries?: number;
        };
        setAutoSaveEnabled(Boolean(settings.enabled));
        if (settings.intervalMinutes) {
          setAutoSaveInterval(String(settings.intervalMinutes));
        }
        if (settings.maxEntries) {
          setAutoSaveLimit(String(settings.maxEntries));
        }
      } catch {
        // ignore invalid settings
      }
    }

    async function loadEntries() {
      try {
        const raw = await AsyncStorage.getItem(autoSaveKey);
        if (!raw || !mounted) return;
        const entries = JSON.parse(raw) as {
          id: string;
          savedAt: number;
          state: SessionSnapshot;
        }[];
        setAutoSaveEntries(entries);
      } catch {
        setAutoSaveEntries([]);
      }
    }

    loadSettings();
    loadEntries();

    return () => {
      mounted = false;
    };
  }, [autoSaveKey, autoSaveSettingsKey, manager.sessionId]);

  useEffect(() => {
    if (!manager.sessionId) return;
    async function persistSettings() {
      const intervalMinutes = Math.max(1, Number(autoSaveInterval) || 3);
      const maxEntries = Math.max(1, Number(autoSaveLimit) || 5);
      await AsyncStorage.setItem(
        autoSaveSettingsKey,
        JSON.stringify({
          enabled: autoSaveEnabled,
          intervalMinutes,
          maxEntries,
        }),
      );
    }
    persistSettings();
  }, [autoSaveEnabled, autoSaveInterval, autoSaveLimit, autoSaveSettingsKey, manager.sessionId]);

  async function fetchGameState(): Promise<SessionSnapshot | null> {
    if (!manager.sessionId || !manager.me?.id) return null;
    const response = await fetch(
      `${getApiBaseUrl()}/api/session/${manager.sessionId}/state?bankerId=${manager.me?.id}`,
    );
    if (!response.ok) return null;
    return (await response.json()) as SessionSnapshot;
  }

  async function persistAutoSaves(
    entries: { id: string; savedAt: number; state: SessionSnapshot }[],
  ) {
    if (!manager.sessionId) return;
    await AsyncStorage.setItem(autoSaveKey, JSON.stringify(entries));
  }

  async function handleAutoSaveNow() {
    const snapshot = await fetchGameState();
    if (!snapshot) {
      setAutoSaveStatus(t("banker.autosaveFailed"));
      return;
    }
    const maxEntries = Math.max(1, Number(autoSaveLimit) || 5);
    const entry = {
      id: `${Date.now()}-${Math.random().toString(16).slice(2)}`,
      savedAt: Date.now(),
      state: snapshot,
    };
    setAutoSaveEntries((prev) => {
      const next = [entry, ...prev].slice(0, maxEntries);
      persistAutoSaves(next);
      return next;
    });
    setAutoSaveStatus(t("banker.autosaveSaved"));
  }

  useEffect(() => {
    if (!autoSaveEnabled || !manager.sessionId) return;
    const intervalMinutes = Math.max(1, Number(autoSaveInterval) || 3);
    const intervalMs = intervalMinutes * 60 * 1000;
    const timer = setInterval(() => {
      handleAutoSaveNow();
    }, intervalMs);
    return () => clearInterval(timer);
  }, [autoSaveEnabled, autoSaveInterval, autoSaveLimit, manager.sessionId]);

  async function handleExport() {
    const snapshot = await fetchGameState();
    if (!snapshot) {
      Alert.alert(t("banker.stateDownloadError"));
      return;
    }
    await Share.share({
      message: JSON.stringify(snapshot, null, 2),
      title: t("banker.downloadState"),
    });
    setAutoSaveStatus(t("banker.stateDownloaded"));
  }

  async function handleLoadState(snapshot: SessionSnapshot) {
    if (!manager.sessionId || !manager.me?.id) return;
    const response = await fetch(`${getApiBaseUrl()}/api/session/${manager.sessionId}/state`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ bankerId: manager.me?.id, state: snapshot }),
    });
    if (!response.ok) {
      Alert.alert(t("banker.stateLoadError"));
      return;
    }
    Alert.alert(t("banker.stateLoaded"));
  }

  function handleImportJson() {
    if (!importJson.trim()) return;
    try {
      const parsed = JSON.parse(importJson) as SessionSnapshot;
      handleLoadState(parsed);
    } catch {
      Alert.alert(t("banker.stateLoadInvalid"));
    }
  }

  const eligiblePlayers = useMemo(
    () => manager.session?.players.filter((player) => player.role !== "banker") ?? [],
    [manager.session],
  );
  const selectedPlayer =
    eligiblePlayers.find((player) => player.id === selectedPlayerId) ?? null;
  const otherPlayers = eligiblePlayers.filter((player) => player.id !== selectedPlayerId);
  const playerTransactions =
    manager.session?.transactions.filter(
      (transaction) =>
        transaction.fromId === selectedPlayerId || transaction.toId === selectedPlayerId,
    ) ?? [];

  useEffect(() => {
    if (eligiblePlayers.length === 0) {
      if (selectedPlayerId) {
        setSelectedPlayerId("");
      }
      return;
    }
    if (!selectedPlayerId || !eligiblePlayers.some((player) => player.id === selectedPlayerId)) {
      setSelectedPlayerId(eligiblePlayers[0].id);
    }
  }, [eligiblePlayers, selectedPlayerId]);

  useEffect(() => {
    if (otherPlayers.length === 0) {
      if (forceTo) setForceTo("");
      return;
    }
    if (!forceTo || forceTo === selectedPlayerId) {
      setForceTo(otherPlayers[0].id);
    }
  }, [otherPlayers, forceTo, selectedPlayerId]);

  if (!manager.session || !manager.me) {
    return (
      <View style={styles.container}>
        <Text style={styles.helper}>{t("common.loading")}</Text>
      </View>
    );
  }

  const session = manager.session;
  const me = manager.me;

  const normalizedAdjustAmount = adjustAmount.replace(",", ".");
  const adjustValue = Number(normalizedAdjustAmount);
  const canAdjust =
    Boolean(selectedPlayerId) && Number.isFinite(adjustValue) && adjustValue !== 0;

  const normalizedForceAmount = forceAmount.replace(",", ".");
  const forceValue = Number(normalizedForceAmount);
  const canForce =
    Boolean(selectedPlayerId) &&
    Boolean(forceTo) &&
    Number.isFinite(forceValue) &&
    forceValue > 0;

  return (
    <ScrollView
      style={styles.scroll}
      contentContainerStyle={styles.container}
      keyboardShouldPersistTaps="handled"
    >
      <Text style={styles.title}>{t("banker.tools.title")}</Text>

      <View style={styles.tabRow}>
        {[
          { id: "players", label: t("banker.tools.playersTab") },
          { id: "admin", label: t("banker.tools.adminTab") },
        ].map((item) => (
          <TouchableOpacity
            key={item.id}
            style={[styles.tabButton, tab === item.id ? styles.tabButtonActive : null]}
            onPress={() => setTab(item.id as "players" | "admin")}
          >
            <Text style={[styles.tabText, tab === item.id ? styles.tabTextActive : null]}>
              {item.label}
            </Text>
          </TouchableOpacity>
        ))}
      </View>

      {tab === "players" ? (
        <>
          <View style={styles.card}>
            <Text style={styles.cardTitle}>{t("banker.tools.playersTab")}</Text>
            {eligiblePlayers.length === 0 ? (
              <Text style={styles.helper}>{t("banker.tools.noPlayers")}</Text>
            ) : (
              <View style={styles.playerList}>
                {eligiblePlayers.map((player) => {
                  const active = player.id === selectedPlayerId;
                  return (
                    <Pressable
                      key={player.id}
                      onPress={() => setSelectedPlayerId(player.id)}
                      style={({ pressed }) => [
                        styles.playerCard,
                        active ? styles.playerCardActive : null,
                        pressed ? styles.playerCardPressed : null,
                      ]}
                    >
                      <View style={styles.playerRow}>
                        <View style={styles.avatarBadge}>
                          <Text style={styles.avatarText}>{initials(player.name)}</Text>
                        </View>
                        <View style={styles.playerMeta}>
                          <Text style={styles.playerName}>{player.name}</Text>
                          <Text style={styles.playerSub}>
                            {player.isDummy ? t("common.dummy") : t("common.player")} ·{" "}
                            {player.connected ? t("common.online") : t("common.offline")}
                          </Text>
                        </View>
                        <View style={styles.balancePill}>
                          <Text style={styles.balanceText}>{formatMoney(player.balance)}</Text>
                        </View>
                      </View>
                    </Pressable>
                  );
                })}
              </View>
            )}
          </View>

          <View style={styles.card}>
            <Text style={styles.cardTitle}>{t("banker.tools.playerOverview")}</Text>
            {selectedPlayer ? (
              <>
                <View style={styles.summaryRow}>
                  <View>
                    <Text style={styles.summaryName}>{selectedPlayer.name}</Text>
                    <Text style={styles.summarySub}>
                      {selectedPlayer.isDummy ? t("common.dummy") : t("common.player")} ·{" "}
                      {selectedPlayer.connected ? t("common.online") : t("common.offline")}
                    </Text>
                  </View>
                  <Text style={styles.summaryBalance}>{formatMoney(selectedPlayer.balance)}</Text>
                </View>

                <Text style={styles.sectionLabel}>{t("common.transactions")}</Text>
                {playerTransactions.length === 0 ? (
                  <Text style={styles.helper}>{t("home.noActivity")}</Text>
                ) : (
                  <ScrollView
                    style={styles.transactionScroll}
                    contentContainerStyle={styles.transactionList}
                    nestedScrollEnabled
                    showsVerticalScrollIndicator={false}
                  >
                    {playerTransactions.map((transaction) => {
                      const display = getTransactionDisplay(
                        transaction,
                        selectedPlayerId,
                        session.players,
                        t,
                      );
                      return (
                        <View key={transaction.id} style={styles.transactionItem}>
                          <View style={styles.transactionInfo}>
                            <Text style={styles.transactionTitle}>{display.label}</Text>
                            <Text style={styles.transactionSub}>{display.subtitle}</Text>
                          </View>
                          <Text
                            style={[
                              styles.transactionAmount,
                              display.outgoing ? styles.amountNegative : null,
                            ]}
                          >
                            {display.amount}
                          </Text>
                        </View>
                      );
                    })}
                  </ScrollView>
                )}
              </>
            ) : (
              <Text style={styles.helper}>{t("banker.tools.noPlayers")}</Text>
            )}
          </View>

          <View style={styles.card}>
            <Text style={styles.cardTitle}>{t("banker.tools.adjust")}</Text>
            <Text style={styles.helper}>
              {selectedPlayer?.name ?? t("transfers.selectPlayer")}
            </Text>
            <TextInput
              style={styles.input}
              placeholder={t("banker.tools.amountAdjust")}
              placeholderTextColor={placeholderColor}
              value={adjustAmount}
              onChangeText={setAdjustAmount}
              keyboardType="decimal-pad"
            />
            <TextInput
              style={styles.input}
              placeholder={t("banker.tools.reason")}
              placeholderTextColor={placeholderColor}
              value={adjustNote}
              onChangeText={setAdjustNote}
            />
            <TouchableOpacity
              style={[styles.button, !canAdjust ? styles.buttonDisabled : null]}
              disabled={!canAdjust}
              onPress={() => {
                if (!selectedPlayerId || !Number.isFinite(adjustValue)) {
                  Alert.alert(t("transfers.error"));
                  return;
                }
                manager.sendMessage({
                  type: "banker_adjust",
                  sessionId: manager.sessionId,
                  bankerId: manager.me?.id,
                  targetId: selectedPlayerId,
                  amount: adjustValue,
                  note: adjustNote,
                });
                setAdjustAmount("");
                setAdjustNote("");
              }}
            >
              <Text style={styles.buttonText}>{t("banker.tools.apply")}</Text>
            </TouchableOpacity>
          </View>

          <View style={styles.card}>
            <Text style={styles.cardTitle}>{t("banker.tools.forceTransfer")}</Text>
            <Text style={styles.helper}>
              {t("transfers.from")} {selectedPlayer?.name ?? t("transfers.selectPlayer")}
            </Text>
            {otherPlayers.length === 0 ? (
              <Text style={styles.helper}>{t("transfers.noPlayers")}</Text>
            ) : (
              <View style={styles.recipientList}>
                {otherPlayers.map((player) => {
                  const active = player.id === forceTo;
                  return (
                    <Pressable
                      key={player.id}
                      onPress={() => setForceTo(player.id)}
                      style={({ pressed }) => [
                        styles.recipientCard,
                        active ? styles.recipientCardActive : null,
                        pressed ? styles.recipientCardPressed : null,
                      ]}
                    >
                      <View style={styles.recipientRow}>
                        <View style={styles.recipientAvatar}>
                          <Text style={styles.recipientInitials}>{initials(player.name)}</Text>
                        </View>
                        <View style={styles.recipientMeta}>
                          <Text style={styles.recipientName}>{player.name}</Text>
                          <Text style={styles.recipientSub}>
                            {player.isDummy ? t("common.dummy") : t("common.player")}
                          </Text>
                        </View>
                        <View style={[styles.radio, active ? styles.radioActive : null]} />
                      </View>
                    </Pressable>
                  );
                })}
              </View>
            )}
            <TextInput
              style={styles.input}
              placeholder={t("banker.tools.amount")}
              placeholderTextColor={placeholderColor}
              value={forceAmount}
              onChangeText={setForceAmount}
              keyboardType="decimal-pad"
            />
            <TextInput
              style={styles.input}
              placeholder={t("banker.tools.note")}
              placeholderTextColor={placeholderColor}
              value={forceNote}
              onChangeText={setForceNote}
            />
            <TouchableOpacity
              style={[styles.button, !canForce ? styles.buttonDisabled : null]}
              disabled={!canForce}
              onPress={() => {
                if (!selectedPlayerId || !forceTo || !Number.isFinite(forceValue)) {
                  Alert.alert(t("transfers.error"));
                  return;
                }
                manager.sendMessage({
                  type: "banker_force_transfer",
                  sessionId: manager.sessionId,
                  bankerId: manager.me?.id,
                  fromId: selectedPlayerId,
                  toId: forceTo,
                  amount: forceValue,
                  note: forceNote,
                });
                setForceAmount("");
                setForceNote("");
              }}
            >
              <Text style={styles.buttonText}>{t("banker.tools.force")}</Text>
            </TouchableOpacity>
          </View>

          <View style={styles.card}>
            <Text style={styles.cardTitle}>{t("banker.tools.createDummy")}</Text>
            <TextInput
              style={styles.input}
              placeholder={t("banker.tools.dummyName")}
              placeholderTextColor={placeholderColor}
              value={dummyName}
              onChangeText={setDummyName}
            />
            <TextInput
              style={styles.input}
              placeholder={t("banker.tools.startingBalance")}
              placeholderTextColor={placeholderColor}
              value={dummyBalance}
              onChangeText={setDummyBalance}
              keyboardType="number-pad"
            />
            <TouchableOpacity
              style={styles.buttonSecondary}
              onPress={() => {
                manager.sendMessage({
                  type: "banker_create_dummy",
                  sessionId: manager.sessionId,
                  bankerId: manager.me?.id,
                  name: dummyName,
                  balance: Number(dummyBalance) || undefined,
                });
                setDummyName("");
                setDummyBalance("1500");
              }}
            >
              <Text style={styles.buttonSecondaryText}>{t("banker.tools.addDummy")}</Text>
            </TouchableOpacity>
          </View>
        </>
      ) : (
        <>
          {pendingRequests.length > 0 ? (
            <View style={styles.card}>
              <Text style={styles.cardTitle}>{t("banker.takeoverApprovals")}</Text>
              <View style={styles.takeoverList}>
                {pendingRequests.map((request) => {
                  const requester = manager.session?.players.find(
                    (player) => player.id === request.requesterId,
                  );
                  const dummy = manager.session?.players.find(
                    (player) => player.id === request.dummyId,
                  );
                  const requesterName =
                    requester?.name ?? request.requesterName ?? t("common.player");
                  return (
                    <View key={request.id} style={styles.takeoverRow}>
                      <View style={styles.takeoverMeta}>
                        <Text style={styles.takeoverName}>{requesterName}</Text>
                        <Text style={styles.takeoverSub}>
                          {t("banker.wants", { name: dummy?.name ?? t("common.dummy") })}
                        </Text>
                      </View>
                      <TouchableOpacity
                        style={styles.buttonSmall}
                        onPress={() =>
                          manager.sendMessage({
                            type: "banker_takeover_approve",
                            sessionId: manager.sessionId,
                            bankerId: manager.me?.id,
                            dummyId: request.dummyId,
                            requesterId: request.requesterId,
                          })
                        }
                      >
                        <Text style={styles.buttonSmallText}>{t("banker.approve")}</Text>
                      </TouchableOpacity>
                    </View>
                  );
                })}
              </View>
            </View>
          ) : null}

          <View style={styles.card}>
            <Text style={styles.cardTitle}>{t("banker.tools.blackout")}</Text>
            <View style={styles.switchRow}>
              <Text style={styles.helper}>{t("banker.tools.blackoutActive")}</Text>
              <Switch
                value={manager.session.blackoutActive}
                onValueChange={(value) =>
                  manager.sendMessage({
                    type: "banker_blackout",
                    sessionId: manager.sessionId,
                    bankerId: manager.me?.id,
                    active: value,
                    reason: value ? blackoutReason : null,
                  })
                }
              />
            </View>
            <TextInput
              style={styles.input}
              placeholder={t("banker.tools.blackoutReason")}
              placeholderTextColor={placeholderColor}
              value={blackoutReason}
              onChangeText={setBlackoutReason}
            />
            <TouchableOpacity
              style={styles.buttonDanger}
              onPress={() =>
                manager.sendMessage({
                  type: "banker_blackout",
                  sessionId: manager.sessionId,
                  bankerId: me.id,
                  active: !session.blackoutActive,
                  reason: !session.blackoutActive ? blackoutReason : null,
                })
              }
            >
              <Text style={styles.buttonDangerText}>
                {session.blackoutActive
                  ? t("banker.tools.blackoutDisable")
                  : t("banker.tools.blackoutEnable")}
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.buttonDanger}
              onPress={() =>
                manager.sendMessage({
                  type: "banker_end",
                  sessionId: manager.sessionId,
                  bankerId: me.id,
                })
              }
            >
              <Text style={styles.buttonDangerText}>{t("banker.tools.endSession")}</Text>
            </TouchableOpacity>
          </View>

          <View style={styles.card}>
            <Text style={styles.cardTitle}>{t("banker.stateTitle")}</Text>
            <Text style={styles.helper}>{t("banker.stateSubtitle")}</Text>
            <TouchableOpacity style={styles.button} onPress={handleExport}>
              <Text style={styles.buttonText}>{t("banker.downloadState")}</Text>
            </TouchableOpacity>

            <TextInput
              style={[styles.input, styles.textarea]}
              placeholder={t("banker.importPlaceholder")}
              placeholderTextColor={placeholderColor}
              value={importJson}
              onChangeText={setImportJson}
              multiline
              textAlignVertical="top"
            />
            <TouchableOpacity style={styles.buttonSecondary} onPress={handleImportJson}>
              <Text style={styles.buttonSecondaryText}>{t("banker.loadFromFile")}</Text>
            </TouchableOpacity>

            {autoSaveEntries.length > 0 ? (
              <View style={styles.autosaveList}>
                {autoSaveEntries.map((entry) => (
                  <View key={entry.id} style={styles.autosaveItem}>
                    <Text style={styles.helper}>
                      {t("banker.savedAt", { time: new Date(entry.savedAt).toLocaleString() })}
                    </Text>
                    <TouchableOpacity
                      style={styles.buttonSmall}
                      onPress={() => handleLoadState(entry.state)}
                    >
                      <Text style={styles.buttonSmallText}>{t("common.load")}</Text>
                    </TouchableOpacity>
                  </View>
                ))}
              </View>
            ) : (
              <Text style={styles.helper}>{t("banker.noAutosaves")}</Text>
            )}

            {autoSaveStatus ? <Text style={styles.helper}>{autoSaveStatus}</Text> : null}
          </View>

          <View style={styles.card}>
            <Text style={styles.cardTitle}>{t("banker.autosaveTitle")}</Text>
            <Text style={styles.helper}>{t("banker.autosaveSubtitle")}</Text>

            <View style={styles.switchRow}>
              <Text style={styles.helper}>{t("banker.autosaveEnabled")}</Text>
              <Switch value={autoSaveEnabled} onValueChange={setAutoSaveEnabled} />
            </View>

            <TextInput
              style={styles.input}
              placeholder={t("banker.autosaveInterval")}
              placeholderTextColor={placeholderColor}
              value={autoSaveInterval}
              onChangeText={setAutoSaveInterval}
              keyboardType="number-pad"
            />
            <TextInput
              style={styles.input}
              placeholder={t("banker.autosaveKeep")}
              placeholderTextColor={placeholderColor}
              value={autoSaveLimit}
              onChangeText={setAutoSaveLimit}
              keyboardType="number-pad"
            />
            <TouchableOpacity style={styles.buttonSecondary} onPress={handleAutoSaveNow}>
              <Text style={styles.buttonSecondaryText}>{t("banker.autosaveNow")}</Text>
            </TouchableOpacity>
          </View>
        </>
      )}
    </ScrollView>
  );
}

const createStyles = (theme: AppTheme) =>
  StyleSheet.create({
    scroll: {
      flex: 1,
      backgroundColor: theme.colors.background,
    },
    container: {
      padding: 20,
      gap: 16,
    },
    title: {
      fontSize: 20,
      fontWeight: "700",
      color: theme.colors.text,
    },
    tabRow: {
      flexDirection: "row",
      gap: 8,
      padding: 4,
      borderRadius: 999,
      backgroundColor: theme.colors.surface,
      borderWidth: 1,
      borderColor: theme.colors.border,
    },
    tabButton: {
      flex: 1,
      paddingVertical: 8,
      borderRadius: 999,
      alignItems: "center",
    },
    tabButtonActive: {
      backgroundColor: theme.colors.primary,
    },
    tabText: {
      color: theme.colors.textMuted,
      fontWeight: "600",
    },
    tabTextActive: {
      color: theme.colors.primaryText,
    },
    card: {
      backgroundColor: theme.colors.surface,
      borderRadius: 16,
      padding: 16,
      gap: 10,
    },
    cardTitle: {
      fontWeight: "600",
      color: theme.colors.text,
    },
    input: {
      borderWidth: 1,
      borderColor: theme.colors.border,
      backgroundColor: theme.colors.inputBackground,
      color: theme.colors.inputText,
      borderRadius: 12,
      paddingHorizontal: 12,
      paddingVertical: 10,
    },
    buttonDisabled: {
      opacity: 0.6,
    },
    button: {
      backgroundColor: theme.colors.primary,
      paddingVertical: 12,
      borderRadius: 999,
      alignItems: "center",
    },
    buttonText: {
      color: theme.colors.primaryText,
      fontWeight: "600",
    },
    buttonSecondary: {
      backgroundColor: theme.colors.secondary,
      paddingVertical: 12,
      borderRadius: 999,
      alignItems: "center",
    },
    buttonSecondaryText: {
      color: theme.colors.secondaryText,
      fontWeight: "600",
    },
    buttonDanger: {
      backgroundColor: theme.colors.danger,
      paddingVertical: 12,
      borderRadius: 999,
      alignItems: "center",
    },
    buttonDangerText: {
      color: theme.colors.primaryText,
      fontWeight: "600",
    },
    textarea: {
      minHeight: 120,
    },
    playerList: {
      gap: 10,
    },
    playerCard: {
      borderRadius: 14,
      padding: 12,
      backgroundColor: theme.colors.surfaceAlt,
      borderWidth: 1,
      borderColor: "transparent",
    },
    playerCardActive: {
      borderColor: theme.colors.accent,
      backgroundColor: theme.colors.accentSurface,
    },
    playerCardPressed: {
      opacity: 0.9,
    },
    playerRow: {
      flexDirection: "row",
      alignItems: "center",
      gap: 12,
    },
    avatarBadge: {
      width: 40,
      height: 40,
      borderRadius: 14,
      backgroundColor: theme.colors.avatarSurface,
      alignItems: "center",
      justifyContent: "center",
    },
    avatarText: {
      color: theme.colors.avatarText,
      fontWeight: "700",
    },
    playerMeta: {
      flex: 1,
      gap: 2,
    },
    playerName: {
      fontWeight: "600",
      color: theme.colors.text,
    },
    playerSub: {
      fontSize: 12,
      color: theme.colors.textMuted,
    },
    balancePill: {
      backgroundColor: theme.colors.chipBackground,
      borderRadius: 999,
      paddingHorizontal: 10,
      paddingVertical: 4,
      borderWidth: 1,
      borderColor: theme.colors.chipBorder,
    },
    balanceText: {
      fontSize: 12,
      fontWeight: "700",
      color: theme.colors.chipText,
    },
    summaryRow: {
      flexDirection: "row",
      justifyContent: "space-between",
      alignItems: "center",
      padding: 12,
      borderRadius: 14,
      backgroundColor: theme.colors.brandSurface,
    },
    summaryName: {
      fontSize: 16,
      fontWeight: "700",
      color: theme.colors.brandText,
    },
    summarySub: {
      color: theme.colors.brandTextMuted,
      fontSize: 12,
    },
    summaryBalance: {
      fontSize: 16,
      fontWeight: "700",
      color: theme.colors.brandText,
    },
    sectionLabel: {
      fontSize: 12,
      fontWeight: "700",
      textTransform: "uppercase",
      letterSpacing: 1,
      color: theme.colors.textMuted,
    },
    transactionList: {
      gap: 8,
    },
    transactionScroll: {
      maxHeight: 240,
    },
    transactionItem: {
      flexDirection: "row",
      justifyContent: "space-between",
      alignItems: "center",
      paddingVertical: 8,
      borderBottomWidth: 1,
      borderBottomColor: theme.colors.borderMuted,
    },
    transactionInfo: {
      flex: 1,
      paddingRight: 12,
    },
    transactionTitle: {
      fontWeight: "600",
      color: theme.colors.text,
    },
    transactionSub: {
      fontSize: 12,
      color: theme.colors.textMuted,
    },
    transactionAmount: {
      fontWeight: "600",
      color: theme.colors.primary,
    },
    amountNegative: {
      color: theme.colors.danger,
    },
    recipientList: {
      gap: 10,
    },
    recipientCard: {
      borderRadius: 14,
      padding: 12,
      backgroundColor: theme.colors.surfaceAlt,
      borderWidth: 1,
      borderColor: "transparent",
    },
    recipientCardActive: {
      borderColor: theme.colors.accent,
      backgroundColor: theme.colors.accentSurface,
    },
    recipientCardPressed: {
      opacity: 0.9,
    },
    recipientRow: {
      flexDirection: "row",
      alignItems: "center",
      gap: 12,
    },
    recipientAvatar: {
      width: 38,
      height: 38,
      borderRadius: 12,
      backgroundColor: theme.colors.listAvatarBackground,
      alignItems: "center",
      justifyContent: "center",
    },
    recipientInitials: {
      fontWeight: "700",
      color: theme.colors.listAvatarText,
    },
    recipientMeta: {
      flex: 1,
      gap: 2,
    },
    recipientName: {
      fontWeight: "600",
      color: theme.colors.text,
    },
    recipientSub: {
      fontSize: 12,
      color: theme.colors.textMuted,
    },
    radio: {
      width: 12,
      height: 12,
      borderRadius: 6,
      borderWidth: 2,
      borderColor: theme.colors.radioBorder,
    },
    radioActive: {
      borderColor: theme.colors.accent,
      backgroundColor: theme.colors.accent,
    },
    autosaveList: {
      gap: 8,
    },
    autosaveItem: {
      flexDirection: "row",
      justifyContent: "space-between",
      alignItems: "center",
      paddingVertical: 6,
      borderBottomWidth: 1,
      borderBottomColor: theme.colors.borderMuted,
    },
    takeoverList: {
      gap: 10,
    },
    takeoverRow: {
      flexDirection: "row",
      justifyContent: "space-between",
      alignItems: "center",
      paddingVertical: 6,
      borderBottomWidth: 1,
      borderBottomColor: theme.colors.borderMuted,
    },
    takeoverMeta: {
      flex: 1,
      paddingRight: 12,
    },
    takeoverName: {
      fontWeight: "600",
      color: theme.colors.text,
    },
    takeoverSub: {
      fontSize: 12,
      color: theme.colors.textMuted,
      marginTop: 2,
    },
    buttonSmall: {
      backgroundColor: theme.colors.secondary,
      paddingHorizontal: 10,
      paddingVertical: 6,
      borderRadius: 999,
    },
    buttonSmallText: {
      color: theme.colors.secondaryText,
      fontWeight: "600",
      fontSize: 12,
    },
    switchRow: {
      flexDirection: "row",
      alignItems: "center",
      justifyContent: "space-between",
    },
    helper: {
      color: theme.colors.textMuted,
    },
  });
