import { useState } from 'react';
import { FlatList, Pressable, StyleSheet, Text, View } from 'react-native';
import { Image } from 'expo-image';

import { LUOGHI } from '../gioco.ts';
import { FOTO_LUOGHI } from '../immagini.ts';
import { nomeLuogo } from '../testi/index.ts';
import { FONT, vibra } from './componenti.tsx';
import { useStato } from './stato.tsx';

const SPAZIO = 4;

/** Tutti i luoghi con foto e nome: 3 colonne sul telefono, 5 dai 600 punti in su. */
export function GrigliaLuoghi({ onScegli }: { onScegli?: (id: number) => void }) {
  const { lingua, imp } = useStato();
  const [larghezza, setLarghezza] = useState(0);
  const colonne = larghezza >= 600 ? 5 : 3;
  const lato = larghezza > 0 ? (larghezza - SPAZIO * (colonne + 1)) / colonne : 0;

  return (
    <View style={st.pieno} onLayout={(e) => setLarghezza(e.nativeEvent.layout.width)}>
      {lato > 0 && (
        <FlatList
          key={colonne}
          data={LUOGHI}
          numColumns={colonne}
          keyExtractor={(id) => String(id)}
          contentContainerStyle={{ padding: SPAZIO / 2 }}
          renderItem={({ item: id }) => (
            <Pressable
              disabled={!onScegli}
              accessibilityRole={onScegli ? 'button' : undefined}
              onPress={() => {
                vibra();
                onScegli?.(id);
              }}
              style={({ pressed }) => [{ width: lato, margin: SPAZIO / 2 }, pressed && st.premuto]}
            >
              <Image source={FOTO_LUOGHI[imp.stile][id]} style={{ width: lato, height: (lato * 3) / 4 }} contentFit="cover" />
              <Text style={st.nome} numberOfLines={1} adjustsFontSizeToFit>
                {nomeLuogo(lingua, id)}
              </Text>
            </Pressable>
          )}
        />
      )}
    </View>
  );
}

const st = StyleSheet.create({
  pieno: { flex: 1 },
  premuto: { opacity: 0.6 },
  nome: { fontFamily: FONT, fontSize: 15, color: '#FFFFFF', textAlign: 'center', paddingVertical: 4 },
});
