<template>
  <header class="header-container" :class="headerClass">
    <nav class="header-nav">
      <!-- Left side: Hamburger + Brand -->
      <div class="header-left">
        <button
          class="hamburger-btn"
          :class="{ active: menuOpen }"
          @click="$emit('menu-toggle')"
          aria-label="Toggle navigation menu"
        >
          <span class="hamburger-line"></span>
          <span class="hamburger-line"></span>
          <span class="hamburger-line"></span>
        </button>
        <router-link :to="brandLink" class="header-brand">
          <slot name="brand">
            <span>{{ title }}</span>
          </slot>
        </router-link>
      </div>

      <!-- Right side: Server + Period + Company + Theme + User -->
      <div class="header-actions">
        <!-- Server Switch Dropdown or Badge (US-008/US-026) -->
        <template v-if="availableServers && availableServers.length > 1">
          <ServerSelector
            v-model="currentServerId"
            :servers="availableServers"
            variant="header"
            @change="onServerChange"
          />
        </template>
        <div v-else-if="serverName" class="server-badge">
          <i class="pi pi-server"></i>
          <span>{{ serverName }}</span>
        </div>
        <PeriodSelector
          v-if="showPeriod && selectedCompany"
          :period-store="periodStore"
          :companies-store="companiesStore"
          variant="header"
          @period-changed="onPeriodChanged"
        />
        <CompanySelector
          v-if="showCompany"
          :companies-store="companiesStore"
          :show-fiscal-code="true"
          variant="header"
          @company-changed="onCompanyChanged"
        />
        <!-- Theme Toggle Button -->
        <button
          class="theme-toggle-btn"
          @click="cycleTheme"
          :title="themeLabel"
          aria-label="Change theme"
        >
          <i :class="themeIcon"></i>
        </button>
        <!-- User menu slot (only rendered if showUser is true) -->
        <div v-if="showUser">
          <slot name="user-menu">
            <div v-if="currentUser" class="header-user" @click="$emit('user-menu-toggle')">
              <i class="pi pi-user"></i>
              <span class="desktop-only">{{ currentUser?.username || 'User' }}</span>
            </div>
          </slot>
        </div>
      </div>
    </nav>

    <!-- Server Switch Modal - Password + 2FA steps (US-009) -->
    <Dialog
      v-model:visible="showPasswordModal"
      :header="`Schimbare server: ${targetServerName}`"
      :modal="true"
      :closable="!isSwitching"
      :style="{ width: '320px' }"
      class="server-switch-modal"
    >
      <div class="server-switch-modal-content">
        <!-- Step 1: Password -->
        <template v-if="switchStep === 'password'">
          <div class="form-field">
            <Password
              id="switch-password"
              v-model="switchPassword"
              :feedback="false"
              :toggleMask="true"
              inputClass="w-full"
              :inputStyle="passwordInputStyle"
              class="w-full"
              :disabled="isSwitching"
              @keyup.enter="confirmServerSwitch"
              autofocus
            />
          </div>
        </template>

        <!-- Step 2: 2FA OTP -->
        <template v-else-if="switchStep === '2fa'">
          <p v-if="switchMaskedEmail" class="otp-info">
            Cod trimis la <strong>{{ switchMaskedEmail }}</strong>
          </p>
          <div class="form-field">
            <InputText
              v-model="switchOtpCode"
              placeholder="000000"
              inputmode="numeric"
              maxlength="6"
              class="w-full otp-input"
              :disabled="isSwitching"
              @input="handleSwitchOtpInput"
              @keyup.enter="confirmSwitch2FA"
              autofocus
            />
          </div>
          <div class="form-field-inline">
            <Checkbox v-model="switchTrustDevice" inputId="switch-trust" :binary="true" />
            <label for="switch-trust" class="trust-label">Ține minte acest dispozitiv 30 zile</label>
          </div>
          <button
            type="button"
            class="resend-link"
            :disabled="authStore?.resendCountdown > 0"
            @click="handleSwitchResendOTP"
          >
            {{ authStore?.resendCountdown > 0 ? `Retrimite (${authStore.resendCountdown}s)` : 'Retrimite codul' }}
          </button>
          <!-- Backup code fallback pentru server switch -->
          <div class="backup-switch-toggle" style="margin-top: var(--space-sm); text-align: center;">
            <button
              v-if="!showSwitchBackupInput"
              type="button"
              class="resend-link"
              @click="showSwitchBackupInput = true"
            >
              Folosește cod de recuperare
            </button>
            <div v-else>
              <InputText
                v-model="switchBackupCode"
                placeholder="Cod recuperare"
                class="w-full"
                style="margin-bottom: var(--space-sm);"
                @input="switchBackupCode = switchBackupCode.toUpperCase().replace(/[^A-Z0-9]/g, '')"
              />
            </div>
          </div>
        </template>

        <div v-if="switchError" class="switch-error">
          <i class="pi pi-exclamation-circle"></i>
          <span>{{ switchError }}</span>
        </div>
      </div>

      <template #footer>
        <!-- Password step footer -->
        <template v-if="switchStep === 'password'">
          <Button
            label="Anulează"
            severity="secondary"
            :disabled="isSwitching"
            @click="cancelServerSwitch"
          />
          <Button
            label="Confirmă"
            :loading="isSwitching"
            :disabled="!switchPassword"
            @click="confirmServerSwitch"
          />
        </template>
        <!-- 2FA step footer -->
        <template v-else-if="switchStep === '2fa'">
          <Button
            label="Înapoi"
            severity="secondary"
            :disabled="isSwitching"
            @click="switchStep = 'password'"
          />
          <Button
            label="Verifică"
            :loading="isSwitching"
            :disabled="!switchOtpCode || switchOtpCode.length < 6"
            @click="confirmSwitch2FA"
          />
        </template>
      </template>
    </Dialog>
  </header>
</template>

<script>
import { computed, ref, onMounted, watch } from "vue";
import CompanySelector from "../CompanySelector.vue";
import PeriodSelector from "../PeriodSelector.vue";
import ServerSelector from "../ServerSelector.vue";
import Dialog from "primevue/dialog";
import Password from "primevue/password";
import Button from "primevue/button";
import InputText from "primevue/inputtext";
import Checkbox from "primevue/checkbox";

export default {
  name: "AppHeader",
  components: {
    CompanySelector,
    PeriodSelector,
    ServerSelector,
    Dialog,
    Password,
    Button,
    InputText,
    Checkbox,
  },
  props: {
    // Header title/brand text
    title: {
      type: String,
      default: "ROA2WEB",
    },
    // Router link for brand click
    brandLink: {
      type: String,
      default: "/",
    },
    // Additional CSS class for header (e.g., 'header-container--gradient')
    headerClass: {
      type: String,
      default: "",
    },
    // Is hamburger menu open?
    menuOpen: {
      type: Boolean,
      default: false,
    },
    // Companies store instance (required for selectors)
    companiesStore: {
      type: Object,
      required: true,
    },
    // Period store instance (required for period selector)
    periodStore: {
      type: Object,
      required: true,
    },
    // Current user object for display
    currentUser: {
      type: Object,
      default: null,
    },
    // Show/hide period selector
    showPeriod: {
      type: Boolean,
      default: true,
    },
    // Show/hide company selector
    showCompany: {
      type: Boolean,
      default: true,
    },
    // Show/hide user info
    showUser: {
      type: Boolean,
      default: true,
    },
    // Server name to display (US-026)
    serverName: {
      type: String,
      default: null,
    },
    // Available servers for dropdown (US-008)
    availableServers: {
      type: Array,
      default: () => [],
    },
    // Current server ID for dropdown selection (US-008)
    currentServerIdProp: {
      type: String,
      default: null,
    },
    // Auth store instance for server switch (US-009)
    authStore: {
      type: Object,
      default: null,
    },
  },
  emits: ["menu-toggle", "company-changed", "period-changed", "user-menu-toggle", "server-switch-request", "server-switched"],
  setup(props, { emit }) {
    const selectedCompany = computed(() => props.companiesStore.selectedCompany);

    // Server switch logic (US-008)
    const currentServerId = ref(props.currentServerIdProp);

    // Watch for external changes to currentServerIdProp
    watch(() => props.currentServerIdProp, (newVal) => {
      currentServerId.value = newVal;
    });

    const getServerName = (serverId) => {
      const server = props.availableServers?.find(s => s.id === serverId);
      return server?.name || serverId;
    };

    // Dark mode detection for password input styling
    const isDarkMode = computed(() => {
      const attr = document.documentElement.getAttribute('data-theme');
      if (attr === 'dark') return true;
      if (attr === 'light') return false;
      return window.matchMedia('(prefers-color-scheme: dark)').matches;
    });

    const passwordInputStyle = computed(() => isDarkMode.value ? {
      background: 'var(--color-bg)',
      color: 'var(--color-text)',
      webkitTextFillColor: 'var(--color-text)',
      borderColor: 'var(--color-border)',
    } : {});

    // Password confirmation modal state (US-009)
    const showPasswordModal = ref(false);
    const switchPassword = ref("");
    const targetServerId = ref(null);
    const targetServerName = ref("");
    const isSwitching = ref(false);
    const switchError = ref("");

    // 2FA step state for server switch
    const switchStep = ref("password"); // 'password' | '2fa'
    const switchOtpCode = ref("");
    const switchTrustDevice = ref(false);
    const switchMaskedEmail = ref("");

    // Backup code state for server switch
    const showSwitchBackupInput = ref(false);
    const switchBackupCode = ref("");

    const onServerChange = (event) => {
      const newServerId = event.value;
      // Don't process if same server selected
      if (newServerId === props.currentServerIdProp) {
        return;
      }

      // Store target server info for modal
      targetServerId.value = newServerId;
      targetServerName.value = getServerName(newServerId);

      // Reset modal state
      switchPassword.value = "";
      switchError.value = "";
      isSwitching.value = false;

      // Revert dropdown to current server (will update after successful switch)
      currentServerId.value = props.currentServerIdProp;

      // Open password modal
      showPasswordModal.value = true;
    };

    const cancelServerSwitch = () => {
      showPasswordModal.value = false;
      switchPassword.value = "";
      switchError.value = "";
      switchOtpCode.value = "";
      switchTrustDevice.value = false;
      switchMaskedEmail.value = "";
      switchStep.value = "password";
      showSwitchBackupInput.value = false;
      switchBackupCode.value = "";
      targetServerId.value = null;
      targetServerName.value = "";
      // Clear pending server in auth store
      if (props.authStore) {
        props.authStore.pendingServerId = null;
      }
    };

    const finishServerSwitch = () => {
      showPasswordModal.value = false;
      switchPassword.value = "";
      switchOtpCode.value = "";
      switchTrustDevice.value = false;
      switchMaskedEmail.value = "";
      switchStep.value = "password";
      showSwitchBackupInput.value = false;
      switchBackupCode.value = "";
      // Update local state to reflect new server
      currentServerId.value = targetServerId.value;
      // Emit event for parent to reload data (companies, periods)
      emit("server-switched", targetServerId.value);
    };

    const confirmServerSwitch = async () => {
      if (!switchPassword.value || !targetServerId.value) {
        switchError.value = "Introduceți parola";
        return;
      }

      // Check if authStore is available
      if (!props.authStore?.switchServer) {
        switchError.value = "Eroare: authStore nu este disponibil";
        return;
      }

      isSwitching.value = true;
      switchError.value = "";

      try {
        const result = await props.authStore.switchServer(targetServerId.value, switchPassword.value);

        if (result.requires_2fa) {
          // Show 2FA step — don't close modal
          switchStep.value = "2fa";
          switchMaskedEmail.value = result.masked_email || "";
          switchError.value = "";
        } else if (result.success) {
          finishServerSwitch();
        } else {
          // Show error in modal
          switchError.value = result.error || "Autentificare eșuată";
        }
      } catch (err) {
        switchError.value = err.message || "Eroare la schimbarea serverului";
      } finally {
        isSwitching.value = false;
      }
    };

    const confirmSwitch2FA = async () => {
      isSwitching.value = true;
      switchError.value = "";

      try {
        let result;
        if (showSwitchBackupInput.value && switchBackupCode.value) {
          // Verifică cu backup code
          result = await props.authStore.verifyBackupCode({
            code: switchBackupCode.value,
          });
        } else {
          if (!switchOtpCode.value || switchOtpCode.value.trim().length === 0) {
            switchError.value = "Introduceți codul OTP";
            isSwitching.value = false;
            return;
          }
          result = await props.authStore.verify2FA({
            code: switchOtpCode.value,
            trustDevice: switchTrustDevice.value,
          });
        }

        if (result.success) {
          finishServerSwitch();
        } else {
          switchError.value = result.error || "Cod invalid";
        }
      } catch (err) {
        switchError.value = err.message || "Eroare la verificare";
      } finally {
        isSwitching.value = false;
      }
    };

    const handleSwitchResendOTP = async () => {
      const result = await props.authStore.resendOTP();
      if (!result.success) {
        switchError.value = result.error || "Nu s-a putut retrimite codul";
      }
    };

    const handleSwitchOtpInput = (event) => {
      switchOtpCode.value = event.target.value.replace(/\D/g, "").slice(0, 6);
    };

    const onCompanyChanged = (company) => {
      emit("company-changed", company);
    };

    const onPeriodChanged = (period) => {
      emit("period-changed", period);
    };

    // Theme toggle logic
    const currentTheme = ref(localStorage.getItem('user-theme') || 'auto');

    const themeIcon = computed(() => ({
      'auto': 'pi pi-desktop',
      'light': 'pi pi-sun',
      'dark': 'pi pi-moon'
    }[currentTheme.value]));

    const themeLabel = computed(() => ({
      'auto': 'Tema: Auto (sistem)',
      'light': 'Tema: Light',
      'dark': 'Tema: Dark'
    }[currentTheme.value]));

    const applyTheme = (theme) => {
      if (theme === 'auto') {
        document.documentElement.removeAttribute('data-theme');
        localStorage.removeItem('user-theme');
      } else {
        document.documentElement.setAttribute('data-theme', theme);
        localStorage.setItem('user-theme', theme);
      }
    };

    const cycleTheme = () => {
      const themes = ['auto', 'light', 'dark'];
      const idx = themes.indexOf(currentTheme.value);
      const next = themes[(idx + 1) % 3];
      currentTheme.value = next;
      applyTheme(next);
    };

    // Initialize theme on mount
    onMounted(() => {
      if (currentTheme.value !== 'auto') {
        applyTheme(currentTheme.value);
      }
    });

    return {
      selectedCompany,
      onCompanyChanged,
      onPeriodChanged,
      currentTheme,
      themeIcon,
      themeLabel,
      cycleTheme,
      // Server switch (US-008)
      currentServerId,
      getServerName,
      onServerChange,
      // Password modal (US-009)
      showPasswordModal,
      switchPassword,
      targetServerId,
      targetServerName,
      isSwitching,
      switchError,
      cancelServerSwitch,
      confirmServerSwitch,
      // 2FA step in server switch modal
      switchStep,
      switchOtpCode,
      switchTrustDevice,
      switchMaskedEmail,
      finishServerSwitch,
      confirmSwitch2FA,
      handleSwitchResendOTP,
      handleSwitchOtpInput,
      // Backup code in server switch
      showSwitchBackupInput,
      switchBackupCode,
      // Dark mode password input
      passwordInputStyle,
    };
  },
};
</script>

<style scoped>
/* Server switch modal - 2FA step styles */
.otp-info {
  font-size: var(--text-sm);
  color: var(--text-color-secondary);
  margin-bottom: var(--space-sm);
}

.form-field {
  margin-bottom: var(--space-sm);
}

.form-field-inline {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  margin-bottom: var(--space-sm);
}

.trust-label {
  font-size: var(--text-sm);
  color: var(--text-color);
  cursor: pointer;
}

.otp-input {
  letter-spacing: 0.3em;
  font-size: var(--text-lg);
  text-align: center;
}

.resend-link {
  background: none;
  border: none;
  color: var(--color-primary);
  font-size: var(--text-sm);
  cursor: pointer;
  padding: 0;
  text-decoration: underline;
}

.resend-link:disabled {
  color: var(--text-color-secondary);
  cursor: not-allowed;
  text-decoration: none;
}

.switch-error {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  padding: var(--space-sm) var(--space-md);
  background: var(--red-50);
  color: var(--red-600);
  border-radius: var(--radius-md);
  font-size: var(--text-sm);
  margin-top: var(--space-sm);
}
</style>
