import React, { useEffect, useRef, useState } from 'react';
import {
  Image,
  Modal,
  Pressable,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import { ps } from '@/api/client';
import { useTheme } from '@/theme/ThemeContext';

const TAPS_TO_UNLOCK = 7;

export function AboutScreen() {
  const { colors } = useTheme();
  const [about, setAbout] = useState<string | null>(null);
  const [showJoel, setShowJoel] = useState(false);
  const taps = useRef(0);
  const resetTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    ps.getAbout()
      .then((r) => setAbout(r.Value ?? ''))
      .catch(() => setAbout(''));
  }, []);

  // Tap the title 7 times (within a rolling window) to summon Joel.
  const onTitleTap = () => {
    taps.current += 1;
    if (resetTimer.current) clearTimeout(resetTimer.current);
    resetTimer.current = setTimeout(() => (taps.current = 0), 1500);
    if (taps.current >= TAPS_TO_UNLOCK) {
      taps.current = 0;
      setShowJoel(true);
    }
  };

  return (
    <ScrollView style={{ backgroundColor: colors.bg }} contentContainerStyle={styles.container}>
      <Pressable onPress={onTitleTap}>
        <Text style={[styles.title, { color: colors.text }]}>About BigBrainParking</Text>
      </Pressable>

      <Text style={[styles.body, { color: colors.text }]}>{about ?? 'Loading…'}</Text>

      <Text style={[styles.meta, { color: colors.subtext }]}>
        Unofficial, de-Googled client for ParkSmarter. Not affiliated with IPS Group.
      </Text>

      <Modal visible={showJoel} transparent animationType="fade" onRequestClose={() => setShowJoel(false)}>
        <TouchableOpacity style={styles.joelBackdrop} activeOpacity={1} onPress={() => setShowJoel(false)}>
          <Image source={require('../../assets/joelangel.png')} style={styles.joel} resizeMode="contain" />
        </TouchableOpacity>
      </Modal>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: { padding: 20 },
  title: { fontSize: 24, fontWeight: '700', marginBottom: 16 },
  body: { fontSize: 15, lineHeight: 22, color: '#333' },
  meta: { fontSize: 12, color: '#999', marginTop: 24 },
  joelBackdrop: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.92)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  joel: { width: '92%', height: '80%' },
});
