<script setup>
import CustomerForm from "./partials/CustomerForm.vue";

import { computed, inject } from "vue";

const ctx = inject("customerDetailContext");
if (!ctx) {
  throw new Error("CustomerShowGeneral must be used under CustomerShowLayout");
}

const { customer, saving, errors, update, bumpRelatedLists } = ctx;
const bannerError = ctx.bannerError;

const generalDraft = computed(() => ({
  name: customer.value?.name ?? "",
  email: customer.value?.email ?? "",
  phone: customer.value?.phone ?? "",
  website: customer.value?.website ?? "",
  notes: customer.value?.notes ?? "",
  is_active: customer.value?.is_active !== false,
}));

const generalFormErrors = computed(() => ({
  ...errors.value,
  form: bannerError.value,
}));

async function submitGeneral(payload) {
  bannerError.value = "";
  if (!customer.value?.id) return;
  try {
    const updated = await update(customer.value.id, payload);
    customer.value = { ...customer.value, ...updated };
    bumpRelatedLists();
  } catch {
    /* field errors flow via errors ref */
  }
}
</script>

<template>
  <div class="rounded-2xl border border-surface-200 dark:border-surface-700 bg-surface-0 dark:bg-surface-950 p-5 shadow-sm">
    <CustomerForm
      embedded
      :draft="generalDraft"
      :saving="saving"
      :errors="generalFormErrors"
      @submit="submitGeneral"
    />
  </div>
</template>
