import { z } from "zod";
import { getCountry, validateNationalNumber } from "./countries";

export const leadSchema = z
  .object({
  name: z
    .string()
    .trim()
    .min(2, "Please enter your full name.")
    .max(80)
    .regex(
      /^[A-Za-z][A-Za-z .'-]*$/,
      "Please enter a valid name (letters only)."
    ),
  company: z.string().trim().min(2, "Please enter your company name.").max(100),
  email: z.string().trim().email("Please enter a valid work email.").max(120),
  phone: z
    .string()
    .trim()
    .max(20)
    .refine((v) => v === "" || /^\+\d{7,16}$/.test(v), {
      message: "Please enter a valid phone number.",
    })
    .optional(),
  phoneCountry: z.string().trim().max(4).optional(),
  industry: z.enum(
    ["Manufacturing", "Construction & infrastructure", "EPC projects", "Both"],
    { message: "Please choose your industry." }
  ),
  companySize: z.string().trim().max(60).optional(),
  interests: z.array(z.string().trim().max(40)).max(12).optional(),
  notes: z.string().trim().max(1000).optional(),
  consent: z.literal(true, {
    message: "Please accept the consent to proceed.",
  }),
  // Honeypot — must stay empty
  website: z.string().max(0).optional(),
})
  .superRefine((v, ctx) => {
    // Phone is optional in demo forms — validate country rules only when filled.
    if (v.phone) {
      const iso = (v.phoneCountry ?? "").trim() || "ZZ";
      const err = validateNationalNumber(iso, nationalDigits(v.phone, iso));
      if (err) {
        ctx.addIssue({ code: "custom", path: ["phone"], message: err });
      }
    }
  });

export type LeadInput = z.infer<typeof leadSchema>;

export const CALLBACK_SLOTS = [
  "As soon as possible",
  "Morning (9am–12pm)",
  "Afternoon (12–4pm)",
  "Evening (4–7pm)",
] as const;

export const callbackSchema = z
  .object({
  name: z
    .string()
    .trim()
    .min(2, "Please enter your full name.")
    .max(80)
    .regex(
      /^[A-Za-z][A-Za-z .'-]*$/,
      "Please enter a valid name (letters only)."
    ),
  phone: z
    .string()
    .trim()
    .regex(/^\+\d{7,16}$/, "Please enter a valid phone number."),
  phoneCountry: z.string().trim().max(4).optional(),
  email: z
    .string()
    .trim()
    .max(120)
    .refine((v) => v === "" || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v), {
      message: "Please enter a valid email address.",
    })
    .optional(),
  industry: z.enum(
    ["Manufacturing", "Construction & infrastructure", "EPC projects", "Both"],
    { message: "Please choose your industry." }
  ),
  slot: z.enum(CALLBACK_SLOTS, { message: "Please choose a time." }),
  consent: z.literal(true, {
    message: "Please accept the consent to proceed.",
  }),
  // Honeypot — must stay empty
  website: z.string().max(0).optional(),
})
  .superRefine((v, ctx) => {
    // Authoritative per-country check — never trust the client's rules.
    const iso = (v.phoneCountry ?? "").trim() || "ZZ";
    const err = validateNationalNumber(iso, nationalDigits(v.phone, iso));
    if (err) {
      ctx.addIssue({ code: "custom", path: ["phone"], message: err });
    }
  });

function nationalDigits(e164: string, iso: string): string {
  // Remove "+" then the country's dial code (ISO is posted alongside)
  const dial = getCountry(iso).dial;
  const body = e164.replace(/^\+/, "");
  if (dial && body.startsWith(dial)) return body.slice(dial.length);
  return body;
}

export type CallbackInput = z.infer<typeof callbackSchema>;
