// app/onboarding.tsx
import { View, Text, KeyboardAvoidingView, Platform, ScrollView } from 'react-native';
import { useState } from 'react';
import { router } from 'expo-router';
import { Input } from '@/components/ui/Input';
import { Button } from '@/components/ui/Button';
import { useUserStore } from '@/store/useUserStore';
import { getDatabase } from '@/lib/database';
import * as Crypto from 'expo-crypto';

export default function OnboardingScreen() {
  const [name, setName] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const setUser = useUserStore((s) => s.setUser);

  async function handleContinue() {
    if (!name.trim()) {
      setError('Please enter your name');
      return;
    }
    setLoading(true);
    try {
      const id = Crypto.randomUUID();
      const shareId = Crypto.randomUUID().replace(/-/g, '').substring(0, 12).toUpperCase();
      const now = Math.floor(Date.now() / 1000);
      const db = await getDatabase();
      await db.runAsync(
        'INSERT INTO users (id, display_name, share_id, is_self, created_at) VALUES (?, ?, ?, 1, ?)',
        [id, name.trim(), shareId, now]
      );
      setUser({ id, displayName: name.trim(), shareId });
      router.replace('/(tabs)');
    } catch (e) {
      setError('Something went wrong. Please try again.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} className="flex-1">
      <ScrollView contentContainerStyle={{ flexGrow: 1 }} className="bg-secondary">
        <View className="flex-1 justify-center px-6 py-12">
          <View className="mb-10">
            <Text className="text-4xl font-bold text-primary mb-2">TerritoryLog</Text>
            <Text className="text-charcoal text-lg">Your ministry field records, private and organized.</Text>
          </View>
          <View className="mb-6">
            <Text className="text-xl font-semibold text-charcoal mb-6">What should we call you?</Text>
            <Input
              label="Your Name"
              placeholder="e.g. Brother Kevin"
              value={name}
              onChangeText={(t) => { setName(t); setError(''); }}
              error={error}
              autoFocus
              returnKeyType="done"
              onSubmitEditing={handleContinue}
            />
          </View>
          <Button label="Get Started" onPress={handleContinue} loading={loading} disabled={!name.trim()} />
          <Text className="text-gray-400 text-sm text-center mt-6">
            Your data stays on your device. We never collect or share it.
          </Text>
        </View>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}
