<template>
  <div class="space-y-4">
    <div>
      <h3 class="text-2xl font-black text-black mb-6">
        What's your equal hourly wage?
      </h3>
    </div>

    <div class="max-w-md">
      <UInput
        v-model="wageText"
        type="text"
        placeholder="0.00"
        size="xl"
        class="text-4xl font-black w-full h-20"
        @update:model-value="validateAndSaveWage">
        <template #leading>
          <span class="text-neutral-500 text-3xl">$</span>
        </template>
      </UInput>
    </div>
  </div>
</template>

<script setup lang="ts">
const emit = defineEmits<{
  "save-status": [status: "saving" | "saved" | "error"];
}>();

// Store
const policiesStore = usePoliciesStore();

function parseNumberInput(val: unknown): number {
  if (typeof val === "number") return val;
  if (typeof val === "string") {
    const cleaned = val.replace(/,/g, ".").replace(/[^0-9.\-]/g, "");
    const parsed = parseFloat(cleaned);
    return Number.isFinite(parsed) ? parsed : 0;
  }
  return 0;
}

// Text input for wage with validation
const wageText = ref(
  policiesStore.equalHourlyWage > 0
    ? policiesStore.equalHourlyWage.toString()
    : ""
);

// Watch for store changes to update text field
watch(
  () => policiesStore.equalHourlyWage,
  (newWage) => {
    wageText.value = newWage > 0 ? newWage.toString() : "";
  }
);

function validateAndSaveWage(value: string) {
  const cleanValue = value.replace(/[^\d.]/g, "");
  const numValue = parseFloat(cleanValue);

  wageText.value = cleanValue;

  if (!isNaN(numValue) && numValue >= 0) {
    policiesStore.setEqualWage(numValue);

    // Set sensible defaults when wage is set
    if (numValue > 0) {
      setDefaults();
      emit("save-status", "saved");
    }
  }
}

// Set reasonable defaults for hidden fields
function setDefaults() {
  if (policiesStore.payrollOncostPct === 0) {
    policiesStore.setOncostPct(25); // 25% on-costs
  }
  if (policiesStore.savingsTargetMonths === 0) {
    policiesStore.setSavingsTargetMonths(3); // 3 months savings
  }
  if (policiesStore.minCashCushionAmount === 0) {
    policiesStore.setMinCashCushion(3000); // €3k cushion
  }
  if (policiesStore.deferredCapHoursPerQtr === 0) {
    policiesStore.setDeferredCap(240); // 240 hours quarterly cap
  }
  if (policiesStore.deferredSunsetMonths === 0) {
    policiesStore.setDeferredSunset(12); // 12 month sunset
  }
  // Set default volunteer flows
  if (policiesStore.volunteerScope.allowedFlows.length === 0) {
    policiesStore.setVolunteerScope(["Care", "SharedLearning"]);
  }
}

// Set defaults on mount if needed
onMounted(() => {
  if (policiesStore.equalHourlyWage > 0) {
    setDefaults();
  }
});
</script>
