<template>
  <div class="premium-phone-input-wrapper">
    <v-label v-if="label" class="phone-label">
      {{ label }}
      <span v-if="required" class="text-error ml-1">*</span>
    </v-label>
    
    <div class="premium-phone-container" :class="{ 
      'premium-phone-container--error': hasError,
      'premium-phone-container--focused': isFocused,
      'premium-phone-container--disabled': disabled
    }">
      <!-- Country Selector -->
      <div class="country-selector-section" @click="toggleCountryDropdown">
        <div class="selected-country-display">
          <div class="flag-container">
            <span class="flag-emoji">{{ selectedCountry.flag }}</span>
          </div>
          <span class="country-code">{{ selectedCountry.dialCode }}</span>
          <v-icon size="16" class="dropdown-icon" :class="{ 'rotated': showCountryDropdown }">
            mdi-chevron-down
          </v-icon>
        </div>
        
        <!-- Country Dropdown -->
        <div v-if="showCountryDropdown" class="country-dropdown" v-click-outside="closeCountryDropdown">
          <div class="country-search">
            <v-text-field
              v-model="countrySearch"
              placeholder="Search countries..."
              variant="outlined"
              density="compact"
              prepend-inner-icon="mdi-magnify"
              hide-details
              @click.stop
            />
          </div>
          <div class="country-list">
            <div 
              v-for="country in filteredCountries" 
              :key="country.iso2"
              class="country-option"
              :class="{ 'selected': country.iso2 === selectedCountry.iso2 }"
              @click.stop="selectCountry(country)"
            >
              <span class="country-flag">{{ country.flag }}</span>
              <span class="country-name">{{ country.name }}</span>
              <span class="country-dial-code">{{ country.dialCode }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- Phone Number Input -->
      <div class="phone-input-section">
        <v-text-field
          v-model="phoneNumber"
          :placeholder="dynamicPlaceholder"
          variant="plain"
          hide-details
          density="comfortable"
          @focus="handleFocus"
          @blur="handleBlur"
          @input="handlePhoneInput"
          :disabled="disabled"
          class="phone-number-input"
        />
      </div>

      <!-- Validation Icon -->
      <div class="validation-section" v-if="phoneNumber">
        <v-icon 
          v-if="isValidPhone" 
          color="success" 
          size="20"
          class="validation-icon success"
        >
          mdi-check-circle
        </v-icon>
        <v-icon 
          v-else-if="phoneNumber.length > 3" 
          color="warning" 
          size="20"
          class="validation-icon warning"
        >
          mdi-alert-circle
        </v-icon>
      </div>
    </div>

    <!-- Error Message -->
    <div v-if="errorMessage" class="error-message">
      <v-icon size="16" color="error" class="mr-1">mdi-alert-circle-outline</v-icon>
      <span class="text-error text-caption">{{ errorMessage }}</span>
    </div>

    <!-- Help Text -->
    <div v-else-if="helpText" class="help-text">
      <span class="text-medium-emphasis text-caption">{{ helpText }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
interface Country {
  name: string;
  iso2: string;
  dialCode: string;
  flag: string;
}

interface Props {
  modelValue?: string;
  label?: string;
  placeholder?: string;
  error?: boolean;
  errorMessage?: string;
  helpText?: string;
  required?: boolean;
  disabled?: boolean;
}

interface Emits {
  (e: 'update:modelValue', value: string): void;
  (e: 'phone-data', data: any): void;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  placeholder: 'Phone number',
  error: false,
  required: false,
  disabled: false
});

const emit = defineEmits<Emits>();

// Reactive state
const isFocused = ref(false);
const phoneNumber = ref('');
const showCountryDropdown = ref(false);
const countrySearch = ref('');

// Countries data with Monaco and France prioritized
const countries: Country[] = [
  { name: 'Monaco', iso2: 'MC', dialCode: '+377', flag: '🇲🇨' },
  { name: 'France', iso2: 'FR', dialCode: '+33', flag: '🇫🇷' },
  { name: 'United States', iso2: 'US', dialCode: '+1', flag: '🇺🇸' },
  { name: 'Italy', iso2: 'IT', dialCode: '+39', flag: '🇮🇹' },
  { name: 'Switzerland', iso2: 'CH', dialCode: '+41', flag: '🇨🇭' },
  { name: 'United Kingdom', iso2: 'GB', dialCode: '+44', flag: '🇬🇧' },
  { name: 'Germany', iso2: 'DE', dialCode: '+49', flag: '🇩🇪' },
  { name: 'Spain', iso2: 'ES', dialCode: '+34', flag: '🇪🇸' },
  { name: 'Canada', iso2: 'CA', dialCode: '+1', flag: '🇨🇦' },
  { name: 'Australia', iso2: 'AU', dialCode: '+61', flag: '🇦🇺' },
];

const selectedCountry = ref<Country>(countries[0]); // Default to Monaco

// Computed properties
const filteredCountries = computed(() => {
  if (!countrySearch.value) return countries;
  
  const search = countrySearch.value.toLowerCase();
  return countries.filter(country => 
    country.name.toLowerCase().includes(search) ||
    country.dialCode.includes(search) ||
    country.iso2.toLowerCase().includes(search)
  );
});

const dynamicPlaceholder = computed(() => {
  const examples: { [key: string]: string } = {
    'MC': '06 12 34 56 78',
    'FR': '01 23 45 67 89',
    'US': '(555) 123-4567',
    'IT': '320 123 4567',
    'CH': '078 123 45 67',
    'GB': '07700 123456',
    'DE': '0176 12345678',
    'ES': '612 34 56 78',
    'CA': '(555) 123-4567',
    'AU': '0412 345 678'
  };
  
  return examples[selectedCountry.value.iso2] || props.placeholder || 'Phone number';
});

const isValidPhone = computed(() => {
  if (!phoneNumber.value) return false;
  
  // Basic validation - at least 6 digits for most countries
  const digits = phoneNumber.value.replace(/\D/g, '');
  return digits.length >= 6 && digits.length <= 15;
});

const fullPhoneNumber = computed(() => {
  if (!phoneNumber.value) return '';
  return `${selectedCountry.value.dialCode} ${phoneNumber.value}`.trim();
});

const hasError = computed(() => {
  return props.error || !!props.errorMessage;
});

// Methods
const toggleCountryDropdown = () => {
  if (!props.disabled) {
    showCountryDropdown.value = !showCountryDropdown.value;
    if (showCountryDropdown.value) {
      countrySearch.value = '';
    }
  }
};

const closeCountryDropdown = () => {
  showCountryDropdown.value = false;
  countrySearch.value = '';
};

const selectCountry = (country: Country) => {
  selectedCountry.value = country;
  showCountryDropdown.value = false;
  countrySearch.value = '';
  
  // Emit updated full phone number
  emit('update:modelValue', fullPhoneNumber.value);
  emit('phone-data', {
    country: country,
    nationalNumber: phoneNumber.value,
    internationalNumber: fullPhoneNumber.value,
    isValid: isValidPhone.value
  });
};

const handleFocus = () => {
  isFocused.value = true;
};

const handleBlur = () => {
  isFocused.value = false;
};

const handlePhoneInput = (value: string) => {
  // Format the phone number as user types
  let formatted = value;
  
  // Remove any non-digits for processing
  const digits = value.replace(/\D/g, '');
  
  // Apply country-specific formatting
  switch (selectedCountry.value.iso2) {
    case 'MC':
    case 'FR':
      // Format as XX XX XX XX XX
      if (digits.length > 0) {
        formatted = digits.replace(/(\d{2})(?=\d)/g, '$1 ').trim();
      }
      break;
    case 'US':
    case 'CA':
      // Format as (XXX) XXX-XXXX
      if (digits.length >= 6) {
        formatted = `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6, 10)}`;
      } else if (digits.length >= 3) {
        formatted = `(${digits.slice(0, 3)}) ${digits.slice(3)}`;
      } else {
        formatted = digits;
      }
      break;
    case 'GB':
      // Format as XXXXX XXXXXX
      if (digits.length > 5) {
        formatted = `${digits.slice(0, 5)} ${digits.slice(5)}`;
      } else {
        formatted = digits;
      }
      break;
    default:
      // Default formatting with spaces every 3 digits
      formatted = digits.replace(/(\d{3})(?=\d)/g, '$1 ').trim();
  }
  
  phoneNumber.value = formatted;
  
  // Emit the full international number
  const fullNumber = fullPhoneNumber.value;
  emit('update:modelValue', fullNumber);
  emit('phone-data', {
    country: selectedCountry.value,
    nationalNumber: phoneNumber.value,
    internationalNumber: fullNumber,
    isValid: isValidPhone.value
  });
};

// Initialize phone number from modelValue
watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    // Try to extract country code and number
    for (const country of countries) {
      if (newValue.startsWith(country.dialCode)) {
        selectedCountry.value = country;
        phoneNumber.value = newValue.slice(country.dialCode.length).trim();
        break;
      }
    }
  } else {
    phoneNumber.value = '';
  }
}, { immediate: true });

// Click outside directive
const vClickOutside = {
  mounted(el: any, binding: any) {
    const handler = (event: Event) => {
      if (!el.contains(event.target as Node)) {
        binding.value();
      }
    };
    el.__clickOutsideHandler = handler;
    document.addEventListener('click', handler);
  },
  unmounted(el: any) {
    if (el.__clickOutsideHandler) {
      document.removeEventListener('click', el.__clickOutsideHandler);
      delete el.__clickOutsideHandler;
    }
  }
};
</script>

<style scoped>
.premium-phone-input-wrapper {
  width: 100%;
  position: relative;
}

.phone-label {
  display: block;
  font-size: 0.875rem;
  font-weight: 500;
  color: rgba(var(--v-theme-on-surface), var(--v-high-emphasis-opacity));
  margin-bottom: 8px;
}

.premium-phone-container {
  display: flex;
  align-items: center;
  background: rgb(var(--v-theme-surface));
  border: 2px solid rgba(var(--v-theme-outline), 0.38);
  border-radius: 12px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
  position: relative;
}

.premium-phone-container:hover {
  border-color: rgba(var(--v-theme-on-surface), 0.6);
  box-shadow: 0 2px 8px rgba(var(--v-theme-on-surface), 0.04);
}

.premium-phone-container--focused {
  border-color: rgb(var(--v-theme-primary)) !important;
  box-shadow: 0 0 0 3px rgba(var(--v-theme-primary), 0.12);
}

.premium-phone-container--error {
  border-color: rgb(var(--v-theme-error)) !important;
  box-shadow: 0 0 0 3px rgba(var(--v-theme-error), 0.12);
}

.premium-phone-container--disabled {
  background: rgba(var(--v-theme-on-surface), 0.04);
  border-color: rgba(var(--v-theme-outline), 0.24);
  cursor: not-allowed;
  opacity: 0.6;
}

/* Country Selector Section */
.country-selector-section {
  position: relative;
  flex-shrink: 0;
}

.selected-country-display {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px 12px;
  cursor: pointer;
  transition: background-color 0.2s ease;
  border-radius: 8px 0 0 8px;
  min-width: 120px;
  background: linear-gradient(135deg, rgba(var(--v-theme-primary), 0.02) 0%, rgba(var(--v-theme-primary), 0.06) 100%);
  border-right: 1px solid rgba(var(--v-theme-outline), 0.12);
}

.selected-country-display:hover {
  background: linear-gradient(135deg, rgba(var(--v-theme-primary), 0.06) 0%, rgba(var(--v-theme-primary), 0.12) 100%);
}

.flag-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 18px;
  border-radius: 3px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
}

.flag-emoji {
  font-size: 16px;
  line-height: 1;
}

.country-code {
  font-weight: 600;
  font-size: 0.875rem;
  color: rgba(var(--v-theme-on-surface), var(--v-high-emphasis-opacity));
  min-width: 40px;
}

.dropdown-icon {
  transition: transform 0.2s ease;
  color: rgba(var(--v-theme-on-surface), var(--v-medium-emphasis-opacity));
}

.dropdown-icon.rotated {
  transform: rotate(180deg);
}

/* Country Dropdown */
.country-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 1000;
  background: rgb(var(--v-theme-surface));
  border: 1px solid rgba(var(--v-theme-outline), 0.24);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  margin-top: 4px;
  overflow: hidden;
  backdrop-filter: blur(8px);
}

.country-search {
  padding: 12px;
  border-bottom: 1px solid rgba(var(--v-theme-outline), 0.12);
  background: rgba(var(--v-theme-primary), 0.02);
}

.country-list {
  max-height: 200px;
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: rgba(var(--v-theme-primary), 0.3) transparent;
}

.country-list::-webkit-scrollbar {
  width: 6px;
}

.country-list::-webkit-scrollbar-track {
  background: transparent;
}

.country-list::-webkit-scrollbar-thumb {
  background: rgba(var(--v-theme-primary), 0.3);
  border-radius: 3px;
}

.country-option {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.15s ease;
  border-bottom: 1px solid rgba(var(--v-theme-outline), 0.06);
}

.country-option:hover {
  background: rgba(var(--v-theme-primary), 0.08);
  transform: translateX(2px);
}

.country-option.selected {
  background: rgba(var(--v-theme-primary), 0.12);
  font-weight: 600;
  color: rgb(var(--v-theme-primary));
}

.country-option:last-child {
  border-bottom: none;
}

.country-flag {
  font-size: 18px;
  width: 24px;
  text-align: center;
}

.country-name {
  flex: 1;
  font-size: 0.875rem;
  font-weight: 500;
}

.country-dial-code {
  font-size: 0.8125rem;
  font-weight: 600;
  color: rgba(var(--v-theme-on-surface), var(--v-medium-emphasis-opacity));
  font-family: 'Roboto Mono', monospace;
}

/* Phone Input Section */
.phone-input-section {
  flex: 1;
  min-width: 0;
}

.phone-number-input {
  height: 56px;
}

.phone-number-input :deep(.v-field) {
  border: none !important;
  box-shadow: none !important;
}

.phone-number-input :deep(.v-field__field) {
  padding: 0 16px;
  font-size: 1rem;
  font-weight: 500;
}

.phone-number-input :deep(.v-field__input) {
  padding: 0;
  font-family: 'Roboto Mono', 'Roboto', sans-serif;
  letter-spacing: 0.5px;
}

/* Validation Section */
.validation-section {
  display: flex;
  align-items: center;
  padding: 0 16px 0 8px;
  flex-shrink: 0;
}

.validation-icon {
  animation: fadeIn 0.2s ease-in-out;
}

.validation-icon.success {
  animation: bounceIn 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}

.validation-icon.warning {
  animation: shake 0.5s ease-in-out;
}

/* Error Message */
.error-message {
  display: flex;
  align-items: center;
  margin-top: 8px;
  padding: 8px 12px;
  background: rgba(var(--v-theme-error), 0.08);
  border-radius: 8px;
  border-left: 4px solid rgb(var(--v-theme-error));
}

/* Help Text */
.help-text {
  margin-top: 6px;
  padding: 0 12px;
  opacity: 0.8;
}

/* Monaco & France Priority Styling */
.country-option:nth-child(1),
.country-option:nth-child(2) {
  background: linear-gradient(90deg, rgba(var(--v-theme-primary), 0.04) 0%, transparent 100%);
  border-left: 3px solid rgb(var(--v-theme-primary));
}

/* Animations */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes bounceIn {
  0% { transform: scale(0.3); opacity: 0; }
  50% { transform: scale(1.05); }
  70% { transform: scale(0.9); }
  100% { transform: scale(1); opacity: 1; }
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70%, 90% { transform: translateX(-2px); }
  20%, 40%, 60%, 80% { transform: translateX(2px); }
}

/* Dark Theme Support */
@media (prefers-color-scheme: dark) {
  .premium-phone-container {
    border-color: rgba(var(--v-theme-outline), 0.3);
  }
  
  .country-dropdown {
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
  }
}

/* Responsive Design */
@media (max-width: 768px) {
  .premium-phone-container {
    border-radius: 8px;
  }
  
  .selected-country-display {
    min-width: 100px;
    padding: 14px 10px;
  }
  
  .country-code {
    font-size: 0.8125rem;
  }
  
  .phone-number-input :deep(.v-field__field) {
    padding: 0 12px;
    font-size: 0.9375rem;
  }
  
  .country-dropdown {
    margin-left: -1px;
    margin-right: -1px;
  }
}

/* iOS Safari fixes */
@supports (-webkit-touch-callout: none) {
  .phone-number-input :deep(.v-field__input) {
    font-size: 16px !important; /* Prevent zoom on focus */
  }
}

/* High contrast mode support */
@media (prefers-contrast: high) {
  .premium-phone-container {
    border-width: 3px;
  }
  
  .country-option.selected {
    outline: 2px solid rgb(var(--v-theme-primary));
    outline-offset: -2px;
  }
}
</style>
