import { defineStore } from "pinia"; export type ContactStatus = "idle" | "loading" | "success" | "error"; /** `website` is a honeypot field, hidden from people and left empty */ const emptyForm = () => ({ name: "", org: "", phone: "", message: "", website: "" }); interface ApiError { statusCode?: number; data?: { message?: string }; } export const useContactStore = defineStore("contact", { state: () => ({ form: emptyForm(), status: "idle" as ContactStatus, error: "", }), actions: { async submit() { this.status = "loading"; this.error = ""; try { await useNuxtApp().$api("/public/contact", { method: "POST", body: this.form }); this.status = "success"; } catch (e) { const err = e as ApiError; this.error = err.statusCode === 429 ? "تعداد درخواست‌ها زیاد است؛ لطفاً چند دقیقه بعد دوباره تلاش کنید." : (err.data?.message ?? "ارسال درخواست انجام نشد؛ لطفاً دوباره تلاش کنید یا تماس بگیرید."); this.status = "error"; } }, /** Pre-fills the message, e.g. from a product page's "request a quote" button */ prefill(message: string) { if (this.status === "success") this.reset(); this.form.message = message; }, reset() { this.form = emptyForm(); this.status = "idle"; this.error = ""; }, }, });