<template>
  <select 
    v-model="selectedCategory"
    @change="handleSelection(selectedCategory)"
    class="w-full px-3 py-2 border border-neutral-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
  >
    <option v-for="option in options" :key="option" :value="option">
      {{ option }}
    </option>
  </select>
</template>

<script setup lang="ts">
interface Props {
  modelValue: string;
  type: 'revenue' | 'expenses';
  mainCategory?: string;
  placeholder?: string;
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: 'Select subcategory'
});

const emit = defineEmits<{
  'update:modelValue': [value: string];
}>();

const budgetStore = useBudgetStore();

const selectedCategory = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
});

const options = computed(() => {
  if (props.type === 'revenue' && props.mainCategory) {
    // Show subcategories for the revenue main category
    return budgetStore.revenueSubcategories[props.mainCategory] || [];
  } else if (props.type === 'expenses' && props.mainCategory) {
    // For expenses, we don't have predefined subcategories, so show common ones or empty
    const expenseSubcategories = {
      'Salaries & Benefits': ['Base wages and benefits', 'Health insurance', 'Retirement contributions', 'Payroll taxes'],
      'Development Costs': ['Software tools', 'Development kits', 'Contractor fees', 'Testing costs'],
      'Equipment & Technology': ['Hardware', 'Software licenses', 'Cloud services', 'IT support'],
      'Marketing & Outreach': ['Advertising', 'Content creation', 'Event costs', 'PR services'],
      'Office & Operations': ['Rent', 'Utilities', 'Insurance', 'Office supplies'],
      'Legal & Professional': ['Legal fees', 'Accounting', 'Consulting', 'Professional services'],
      'Other Expenses': ['Miscellaneous', 'Travel', 'Training', 'Other']
    };
    return expenseSubcategories[props.mainCategory] || ['Miscellaneous'];
  } else {
    // Fallback to main categories if no mainCategory provided
    return props.type === 'revenue' 
      ? budgetStore.revenueCategories 
      : budgetStore.expenseCategories;
  }
});

function handleSelection(value: string) {
  // If it's a new category (not in existing list), add it
  if (value && !options.value.includes(value)) {
    budgetStore.addCustomCategory(props.type, value);
  }
  emit('update:modelValue', value);
}
</script>