import { Ionicons } from "@expo/vector-icons";
import { router } from "expo-router";
import { StyleSheet, View } from "react-native";
import { Pressable, Text } from "react-native";

import { AccountSwitcher } from "@/components/AccountSwitcher";
import { Logo } from "@/components/Logo";
import { fonts, radii, spacing } from "@/constants/theme";
import { useAppTheme } from "@/contexts/ThemeContext";
import { TOP_CHROME_ROW_HEIGHT } from "@/lib/top-chrome-insets";

type TopChromeProps = {
  showMoreBack?: boolean;
};

/** Wordmark left, account switcher right — sits on TopChromeBar blur. */
export function TopChrome({ showMoreBack = false }: TopChromeProps) {
  const { colors, isDark } = useAppTheme();

  function handleBack() {
    if (router.canGoBack()) {
      router.back();
      return;
    }
    router.replace("/(app)/more" as never);
  }

  return (
    <View style={styles.row}>
      {showMoreBack ? (
        <Pressable
          accessibilityRole="button"
          accessibilityLabel="Back to More"
          onPress={handleBack}
          style={({ pressed }) => [
            styles.backButton,
            { borderColor: colors.borderGlass, backgroundColor: colors.cardGlass },
            pressed && styles.pressed,
          ]}
        >
          <Ionicons name="chevron-back" size={18} color={colors.foreground} />
          <Text style={[styles.backLabel, { color: colors.foreground }]}>More</Text>
        </Pressable>
      ) : (
        <Logo size="xs" onDark={isDark} />
      )}
      <AccountSwitcher />
    </View>
  );
}

const styles = StyleSheet.create({
  row: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    height: TOP_CHROME_ROW_HEIGHT,
    paddingHorizontal: spacing.md,
  },
  backButton: {
    minHeight: 36,
    flexDirection: "row",
    alignItems: "center",
    gap: spacing.xs,
    paddingHorizontal: spacing.sm,
    borderWidth: 1,
    borderRadius: radii.pill,
  },
  backLabel: {
    fontFamily: fonts.bodySemiBold,
    fontSize: 13,
  },
  pressed: {
    opacity: 0.82,
  },
});
