<template>
  <v-app-bar class="top-nav" density="compact" flat height="64">
    <v-btn icon="mdi-menu" variant="text" class="mr-1" title="Toggle menu" aria-label="Toggle navigation menu" @click="$emit('toggle-nav')" />
    <div class="top-nav-title">
      <div class="text-subtitle-2 quiet">{{ subtitle }}</div>
      <div class="text-h6 font-weight-bold">{{ title }}</div>
    </div>
    <v-spacer />
    <v-select
      v-if="companies.length > 1"
      :model-value="activeCompanyId"
      :items="companyItems"
      item-title="title"
      item-value="value"
      density="compact"
      variant="solo-filled"
      flat
      hide-details
      prepend-inner-icon="mdi-domain"
      class="company-switch mr-2"
      style="max-width:220px"
      aria-label="Active company"
      @update:model-value="$emit('change-company', $event)"
    />
    <v-chip v-else-if="companies.length === 1" size="small" variant="tonal" prepend-icon="mdi-domain" class="mr-2">{{ companies[0].name }}</v-chip>
    <slot name="actions" />
    <v-btn icon="mdi-help-circle-outline" variant="text" class="mr-1" title="User guide" aria-label="Open user guide" @click="$emit('open-help')" />
    <v-menu v-model="profileMenu" :close-on-content-click="false" location="bottom end">
      <template #activator="{ props }">
        <v-btn v-bind="props" class="profile-trigger" variant="text" aria-label="Account and appearance settings">
          <v-avatar color="primary" size="32">
            <span class="text-caption font-weight-bold">{{ initials }}</span>
          </v-avatar>
          <span class="profile-name">{{ user?.name }}</span>
          <v-icon icon="mdi-chevron-down" size="18" />
        </v-btn>
      </template>
      <v-card width="340">
        <v-card-text>
          <div class="d-flex align-center ga-3 mb-4">
            <v-avatar color="primary" size="42">
              <span class="font-weight-bold">{{ initials }}</span>
            </v-avatar>
            <div>
              <div class="font-weight-bold">{{ user?.name }}</div>
              <div class="text-caption quiet">{{ user?.email }} · {{ user?.role }}</div>
            </div>
          </div>
          <v-select
            v-model="localPreferences.theme"
            :items="themeItems"
            :item-props="themeItemProps"
            item-title="title"
            item-value="value"
            label="Theme"
            prepend-inner-icon="mdi-theme-light-dark"
          />

          <v-select
            v-model="localPreferences.fontScale"
            :items="fontSizeItems"
            :item-props="fontItemProps"
            item-title="title"
            item-value="value"
            label="Text size"
            prepend-inner-icon="mdi-format-size"
          />

          <div class="text-caption quiet mt-1 mb-1">Accent colour</div>
          <div class="accent-swatches" role="group" aria-label="Accent colour presets">
            <button
              type="button"
              class="accent-swatch accent-default"
              :class="{ selected: !localPreferences.accent }"
              title="Theme default"
              aria-label="Use theme default accent colour"
              :aria-pressed="!localPreferences.accent"
              @click="localPreferences.accent = ''"
            >
              <v-icon icon="mdi-cancel" size="16" />
            </button>
            <button
              v-for="color in accentPresets"
              :key="color"
              type="button"
              class="accent-swatch"
              :class="{ selected: sameColor(localPreferences.accent, color) }"
              :style="{ backgroundColor: color }"
              :title="color"
              :aria-label="`Accent colour ${color}`"
              :aria-pressed="sameColor(localPreferences.accent, color)"
              @click="localPreferences.accent = color"
            />
          </div>
          <v-text-field
            v-model="localPreferences.accent"
            label="Custom accent (hex)"
            placeholder="#2457a6"
            density="compact"
            class="mt-2"
            prepend-inner-icon="mdi-eyedropper-variant"
            clearable
          />

          <v-switch
            v-model="localPreferences.contrast"
            label="High-contrast boost"
            color="primary"
            density="compact"
            hide-details
            class="mt-1"
          />

          <v-alert v-if="status" class="mt-2" density="compact" type="success">{{ status }}</v-alert>
        </v-card-text>
        <v-card-actions>
          <v-btn variant="text" prepend-icon="mdi-logout" @click="$emit('logout')">Sign out</v-btn>
          <v-btn variant="text" prepend-icon="mdi-lock-reset" @click="profileMenu = false; $emit('change-password')">Change password</v-btn>
          <v-spacer />
          <v-btn color="primary" prepend-icon="mdi-content-save" :loading="saving" @click="save">Save</v-btn>
        </v-card-actions>
      </v-card>
    </v-menu>
  </v-app-bar>
</template>

<script>
import { accentPresets, fontSizeItems } from '../constants';

export default {
  props: {
    preferences: { type: Object, required: true },
    saving: { type: Boolean, default: false },
    subtitle: { type: String, required: true },
    themeItems: { type: Array, required: true },
    title: { type: String, required: true },
    user: { type: Object, required: true },
    companies: { type: Array, default: () => [] },
    activeCompanyId: { type: [Number, String], default: null }
  },
  emits: ['change-company', 'change-password', 'logout', 'open-help', 'save-preferences', 'toggle-nav'],
  data() {
    return {
      accentPresets,
      fontSizeItems,
      localPreferences: { ...this.preferences },
      profileMenu: false,
      syncing: false,
      status: ''
    };
  },
  computed: {
    companyItems() {
      return this.companies.map((c) => ({ title: c.name, value: c.id }));
    },
    initials() {
      return String(this.user?.name || 'MA')
        .split(/\s+/)
        .filter(Boolean)
        .slice(0, 2)
        .map((part) => part[0]?.toUpperCase())
        .join('');
    }
  },
  watch: {
    preferences: {
      handler(value) {
        // Sync from parent without echoing back a live-preview emit (avoids a feedback loop).
        this.syncing = true;
        this.localPreferences = { ...value };
        this.$nextTick(() => { this.syncing = false; });
      },
      deep: true
    },
    localPreferences: {
      handler(value) {
        if (this.syncing) return;
        this.$emit('save-preferences', { ...value }, { persist: false });
      },
      deep: true
    }
  },
  methods: {
    themeItemProps(item) {
      return { subtitle: item.props?.subtitle };
    },
    fontItemProps(item) {
      return { subtitle: item.props?.subtitle };
    },
    sameColor(a, b) {
      const norm = (value) => String(value || '').trim().toLowerCase().replace(/^#/, '');
      return norm(a) !== '' && norm(a) === norm(b);
    },
    async save() {
      await this.$emit('save-preferences', { ...this.localPreferences }, { persist: true });
      this.status = 'Preferences saved';
      window.setTimeout(() => {
        this.status = '';
      }, 1800);
    }
  }
};
</script>

<style scoped>
.accent-swatches {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.accent-swatch {
  width: 26px;
  height: 26px;
  border-radius: 50%;
  border: 2px solid rgba(var(--v-theme-on-surface), 0.25);
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  transition: transform 0.08s ease, border-color 0.08s ease;
}
.accent-swatch:hover {
  transform: scale(1.1);
}
.accent-swatch.selected {
  border-color: rgb(var(--v-theme-on-surface));
  box-shadow: 0 0 0 2px rgb(var(--v-theme-surface)), 0 0 0 4px rgb(var(--v-theme-primary));
}
.accent-swatch.accent-default {
  background: transparent;
}
.accent-swatch:focus-visible {
  outline: 3px solid rgb(var(--v-theme-info));
  outline-offset: 2px;
}
</style>
