// Settings — sync status (first-class on mobile) + device registration for push.
import { useState } from 'react'
import { Pressable, Text, View } from 'react-native'
import { useMobileConnectionStatus } from '@voltro/react-native'
import { buildDeviceRegistration } from '../lib/notifications'
import { onlineSource } from '../client'

export default function Settings() {
  // Same injected source as the banner in _layout: the default reads
  // `navigator.onLine`, which React Native does not have.
  const { status, reportSuccess, reportFailure } = useMobileConnectionStatus({ onlineSource })
  const [registered, setRegistered] = useState<string | null>(null)

  return (
    <View style={{ flex: 1, padding: 16, gap: 16 }}>
      <View>
        <Text style={{ fontSize: 18, fontWeight: '700' }}>Sync</Text>
        <Text style={{ color: '#666' }}>Connection: {status}</Text>
        <View style={{ flexDirection: 'row', gap: 8, marginTop: 8 }}>
          {/* In a real app these are driven by NetInfo + the client's transport
              errors (see plans/open/mobile/03). Buttons here make the seam visible. */}
          <Pressable onPress={reportSuccess} style={btn}>
            <Text style={btnText}>Mark reachable</Text>
          </Pressable>
          <Pressable onPress={reportFailure} style={btn}>
            <Text style={btnText}>Mark unreachable</Text>
          </Pressable>
        </View>
      </View>

      <View>
        <Text style={{ fontSize: 18, fontWeight: '700' }}>Push</Text>
        <Text style={{ color: '#666' }}>
          {registered ? `Registered token ${registered.slice(0, 12)}…` : 'Not registered'}
        </Text>
        <Pressable
          onPress={() => {
            // In a real app the token comes from expo-notifications'
            // getExpoPushTokenAsync(); the SENDER is server-side + creds-gated
            // (see plans/open/mobile/02). This builds the _voltro_devices row.
            const row = buildDeviceRegistration('ExponentPushToken[demo]', 'ios')
            setRegistered(row.deviceToken)
          }}
          style={[btn, { marginTop: 8 }]}
        >
          <Text style={btnText}>Register this device</Text>
        </Pressable>
      </View>
    </View>
  )
}

const btn = { backgroundColor: '#2563eb', borderRadius: 8, paddingHorizontal: 14, paddingVertical: 10 } as const
const btnText = { color: 'white', fontWeight: '600' } as const
