<template>
  <!--
    MobileChatShell
    ----------------
    Shell voor mobiele schermen. Biedt een header met logo + tabbar en toont
    per tab een deel van de CoreChatApp:
    - chat: actieve AI-boodschap + invoer
    - history: volledige berichtenhistoriek
    - setup: taalkeuze + uitleg
  -->
  <div class="mobile-chat-shell">
    <header class="chat-mobile-header">
      <div class="chat-mobile-header-left">
        <SideBarLogo :logo-url="tenantLogoUrl" :make-name="tenantName" />
      </div>
      <div class="chat-mobile-header-right">
        <MobileTabBar
          v-model="activeTabId"
          :tabs="mobileTabs"
          placement="header"
        />
      </div>
    </header>

    <div class="chat-mobile-content" :class="`tab-${activeTabId}`">
      <CoreChatApp
        :api-prefix="apiPrefix"
        :conversation-id="conversationId"
        :user-id="userId"
        :user-name="userName"
        :initial-language="initialLanguage"
        :supported-language-details="supportedLanguageDetails"
        :allowed-languages="allowedLanguages"
      >
        <!-- Historiek-tab -->
        <template #history="historyProps">
          <MessageHistory
            v-if="activeTabId === 'history'"
            :messages="historyProps.messages"
            :is-typing="historyProps.isTyping"
            :is-submitting-form="historyProps.isSubmittingForm"
            :api-prefix="apiPrefix"
            :auto-scroll="true"
            @specialist-error="event => {
              console.log('🧐 [MobileChatShell] specialist-error vanuit history ontvangen:', event);
              (historyProps.onSpecialistError || handleSpecialistError)(event);
            }"
            @specialist-complete="event => {
              console.log('🧐 [MobileChatShell] specialist-complete vanuit history ontvangen:', event);
              (historyProps.onSpecialistComplete || handleSpecialistComplete)(event);
            }"
            ref="messageHistory"
            class="chat-messages-area"
          />
        </template>

        <!-- Chat-tab: actieve boodschap + input -->
        <template #active-message-input="inputProps">
          <ChatInput
            v-if="activeTabId === 'chat'"
            :current-message="inputProps.currentMessage"
            :is-loading="inputProps.isLoading"
            :max-length="settings.maxMessageLength"
            :allow-file-upload="settings.allowFileUpload"
            :allow-voice-message="settings.allowVoiceMessage"
            :form-data="inputProps.formData"
            :active-ai-message="inputProps.activeAiMessage"
            :api-prefix="apiPrefix"
            @send-message="inputProps.onSendMessage"
            @update-message="inputProps.onUpdateMessage"
            @upload-file="inputProps.onUploadFile"
            @record-voice="inputProps.onRecordVoice"
            @submit-form="inputProps.onSubmitForm"
            @specialist-error="event => {
              console.log('🧐 [MobileChatShell] specialist-error vanuit ChatInput ontvangen:', event);
              (inputProps.onSpecialistError || handleSpecialistError)(event);
            }"
            @specialist-complete="event => {
              console.log('🧐 [MobileChatShell] specialist-complete vanuit ChatInput ontvangen:', event);
              (inputProps.onSpecialistComplete || handleSpecialistComplete)(event);
            }"
            ref="chatInput"
            class="chat-input-area tab-chat-input"
          />
        </template>

        <!-- Setup-tab -->
        <template #setup="setupProps">
          <SideBarMobileSetup
            v-if="activeTabId === 'setup'"
            :tenant-make="{ name: tenantName, subtitle: tenantSubtitle }"
            :explanation-text="setupProps.explanationText || explanationText"
            :initial-language="initialLanguage"
            :current-language="setupProps.currentLanguage || currentLanguage"
            :supported-language-details="supportedLanguageDetails"
            :allowed-languages="allowedLanguages"
            :api-prefix="apiPrefix"
            @language-changed="handleLanguageChangedFromSetup"
          />
        </template>
      </CoreChatApp>
    </div>
  </div>
</template>

<script>
import CoreChatApp from './CoreChatApp.vue';
import MessageHistory from './MessageHistory.vue';
import ChatInput from './ChatInput.vue';
import SideBarLogo from './SideBarLogo.vue';
import MobileTabBar from './MobileTabBar.vue';
import SideBarMobileSetup from './SideBarMobileSetup.vue';

export default {
  name: 'MobileChatShell',

  components: {
    CoreChatApp,
    MessageHistory,
    ChatInput,
    SideBarLogo,
    MobileTabBar,
    SideBarMobileSetup
  },

  props: {
    apiPrefix: {
      type: String,
      default: ''
    },
    conversationId: {
      type: String,
      default: 'default'
    },
    userId: {
      type: [String, Number, null],
      default: null
    },
    userName: {
      type: String,
      default: ''
    },
    initialLanguage: {
      type: String,
      default: 'en'
    },
    supportedLanguageDetails: {
      type: Object,
      default: () => ({})
    },
    allowedLanguages: {
      type: Array,
      default: () => ['nl', 'en', 'fr', 'de']
    },
    tenantName: {
      type: String,
      default: 'EveAI'
    },
    tenantSubtitle: {
      type: String,
      default: ''
    },
    tenantLogoUrl: {
      type: String,
      default: ''
    },
    explanationText: {
      type: String,
      default: ''
    },
    settings: {
      type: Object,
      default: () => ({
        maxMessageLength: 2000,
        allowFileUpload: true,
        allowVoiceMessage: false
      })
    }
  },

  data() {
    return {
      activeTabId: 'chat',
      currentLanguage: this.initialLanguage || 'en'
    };
  },

  computed: {
    mobileTabs() {
      return [
        { id: 'chat', iconName: 'chat', label: 'Chat' },
        { id: 'history', iconName: 'history', label: 'Historiek' },
        { id: 'setup', iconName: 'settings', label: 'Setup' }
      ];
    }
  },

  mounted() {
    // Initiale tab kan later uit config komen (defaultTab), voorlopig chat.
  },

  methods: {
    handleSpecialistComplete(eventData) {
      this.$emit('specialist-complete', eventData);
    },

    handleSpecialistError(eventData) {
      this.$emit('specialist-error', eventData);
    },

    handleLanguageChangedFromSetup(newLanguage) {
      this.currentLanguage = newLanguage;
      this.$emit('language-changed', newLanguage);
    }
  }
};
</script>

<style scoped>
.mobile-chat-shell {
  display: flex;
  flex-direction: column;
  flex: 1 1 auto;
  min-height: 0;
}

.chat-mobile-header {
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  flex-direction: row;
  align-items: stretch;
  justify-content: space-between;
  padding: 6px 8px;
  background: var(--tab-background, #0a0a0a);
}

.chat-mobile-header-left {
  flex: 0 0 auto;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  min-width: 56px;
  margin-right: 4px;
}

.chat-mobile-header-right {
  flex: 1 1 auto;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  overflow: hidden;
}

.chat-mobile-content {
  flex: 1 1 auto;
  min-height: 0;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.chat-mobile-content.tab-chat {
  display: flex;
  flex-direction: column;
}

.tab-chat-input {
  margin-top: auto;
  flex-shrink: 0;
  padding-bottom: calc(6px + var(--safe-bottom-inset, 0px));
}

body.chat-keyboard-open .tab-chat-input {
  padding-bottom: 6px;
}
</style>
