/**
 * App.tsx — root orchestrator (CORE calling build, no CallKeep/push).
 *
 * Screen state machine:
 *   1. Not logged in           -> LoginScreen
 *   2. Incoming call ringing   -> IncomingCallScreen (in-app)
 *   3. Any active call         -> ActiveCallScreen
 *   4. Otherwise               -> DialpadScreen
 *
 * On cold start we restore the saved profile and open the WSS registration so a
 * returning engineer lands on the dialpad already online.
 */
import React, { useEffect, useState, useCallback } from 'react';
import {
  StatusBar, View, ActivityIndicator, StyleSheet,
  PermissionsAndroid, Platform,
} from 'react-native';
import LoginScreen from './screens/LoginScreen';
import DialpadScreen from './screens/DialpadScreen';
import IncomingCallScreen from './screens/IncomingCallScreen';
import ActiveCallScreen from './screens/ActiveCallScreen';
import { useSip } from './hooks/useSip';
import { sipEngine } from './services/SipEngine';
import { getStoredSipConfig, clearSipConfig } from './services/authStore';
import { SipConfig } from './config';
import { colors } from './theme';

type Boot = 'loading' | 'loggedOut' | 'loggedIn';

async function ensureMicPermission() {
  if (Platform.OS !== 'android') return;
  await PermissionsAndroid.request(
    PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
    {
      title: 'Microphone access',
      message: 'ePhone needs the microphone to place and receive calls.',
      buttonPositive: 'Allow',
    },
  );
}

export default function App() {
  const [boot, setBoot] = useState<Boot>('loading');
  const [cfg, setCfg] = useState<SipConfig | null>(null);
  const sip = useSip();

  useEffect(() => {
    (async () => {
      await ensureMicPermission();
      const saved = await getStoredSipConfig();
      if (saved) {
        setCfg(saved);
        await sipEngine.start(saved);
        setBoot('loggedIn');
      } else {
        setBoot('loggedOut');
      }
    })();
  }, []);

  const onLoggedIn = useCallback(async (config: SipConfig) => {
    setCfg(config);
    await sipEngine.start(config);
    setBoot('loggedIn');
  }, []);

  const onLogout = useCallback(async () => {
    sipEngine.stop();
    await clearSipConfig();
    setCfg(null);
    setBoot('loggedOut');
  }, []);

  if (boot === 'loading') {
    return (
      <View style={styles.splash}>
        <StatusBar barStyle="dark-content" />
        <ActivityIndicator size="large" color={colors.primary} />
      </View>
    );
  }

  if (boot === 'loggedOut') {
    return (
      <>
        <StatusBar barStyle="dark-content" />
        <LoginScreen onLoggedIn={onLoggedIn} />
      </>
    );
  }

  const { call } = sip;

  if (call && call.direction === 'incoming' && call.phase === 'ringing') {
    return (
      <>
        <StatusBar barStyle="light-content" />
        <IncomingCallScreen caller={call.caller} onAccept={sip.answer} onDecline={sip.hangup} />
      </>
    );
  }

  if (call) {
    return (
      <>
        <StatusBar barStyle="light-content" />
        <ActiveCallScreen
          caller={call.caller}
          phase={call.phase}
          muted={call.muted}
          speaker={call.speaker}
          held={call.held}
          onMute={sip.toggleMute}
          onSpeaker={sip.toggleSpeaker}
          onHold={sip.toggleHold}
          onHangup={sip.hangup}
        />
      </>
    );
  }

  return (
    <>
      <StatusBar barStyle="dark-content" />
      <DialpadScreen
        registered={sip.registered}
        extension={cfg?.extension || ''}
        onCall={sip.placeCall}
        onLogout={onLogout}
      />
    </>
  );
}

const styles = StyleSheet.create({
  splash: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.bg },
});
