"use client";


import ui from "../audit-requests/Form/BatchForm.module.css";

import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import Select from "react-select";
import CreatableSelect from "react-select/creatable";
import toast from "react-hot-toast";

import {
  createLead,
  updateLead,
  assignLead,
  getLead,
  checkLeadDuplicates,
  getAssignableUsers,
  getLeadTags,
  getStandardOptions,
} from "@/lib/api/leads.api";
import { formatUserName } from "@/lib/api/mappers/leads.mappers";
import type {
  ClientGroup,
  DuplicateMatch,
  Lead,
  LeadPriority,
  LeadStatus,
} from "@/lib/api/types/leads.types";

// ─── Options ────────────────────────────────────────────────────────────────
// Same shape and naming as BatchAuditRequestForm's option blocks.

const GROUP_VALUES: ClientGroup[] = ["QRS", "TQS", "QRS_B", "QRS_NEW"];
const groupLabel = (g: ClientGroup) =>
  g === "QRS_B" ? "QRS-B" : g === "QRS_NEW" ? "QRS New" : g;

// QRS_B counts as QRS — the same rule groupToSource() applies when it picks
// which CRM database to search.
const groupToBucket = (g: ClientGroup): "QRS" | "TQS" | "QRS_NEW" =>
  g === "TQS" ? "TQS" : g === "QRS_NEW" ? "QRS_NEW" : "QRS";

const STATUS_VALUES: Exclude<LeadStatus, "Converted">[] = [
  "New",
  "Interested",
  "Lost",
];

const PRIORITY_VALUES: LeadPriority[] = ["Low", "Medium", "High"];

const SOURCE_OPTIONS = [
  { value: "Website", label: "Website" },
  { value: "Referral", label: "Referral" },
  { value: "Cold Call", label: "Cold Call" },
  { value: "Email Campaign", label: "Email Campaign" },
  { value: "Trade Show", label: "Trade Show" },
  { value: "Social Media", label: "Social Media" },
  { value: "Other", label: "Other" },
];

const LOST_REASON_OPTIONS = [
  { value: "Price", label: "Price" },
  { value: "Went with competitor", label: "Went with competitor" },
  { value: "No budget", label: "No budget" },
  { value: "No response", label: "No response" },
  { value: "Not a fit", label: "Not a fit" },
  { value: "Other", label: "Other" },
];

const selectPortal = {
  menuPortalTarget:
    typeof document !== "undefined" ? document.body : undefined,
  styles: { menuPortal: (base: any) => ({ ...base, zIndex: 3000 }) },
};

const selectBase = {
  classNamePrefix: "rselect",
  ...selectPortal,
};

type StdOption = { value: string; label: string };
type UserOption = { value: number; label: string };
type TagOption = { value: string; label: string };

interface Props {
  /** Omit for create mode. */
  leadId?: number;
  /** Same StdOption[] shape BatchAuditRequestForm receives. */
  standards?: StdOption[];
}

const emptyLead = () => ({
  company: "",
  client_group: "QRS" as ClientGroup,
  contact: "",
  phone: "",
  email: "",
  website: "",
  standards: [] as string[],
  status: "New" as LeadStatus,
  priority: "Medium" as LeadPriority,
  source: "",
  notes: "",
  tags: [] as string[],
  lost_reason: "",
  lost_notes: "",
});

export default function LeadForm({ leadId, standards = [] }: Props) {
  const router = useRouter();
  const isEdit = typeof leadId === "number";

  const [form, setForm] = useState(emptyLead());
  const [original, setOriginal] = useState<Lead | null>(null);
  const [loading, setLoading] = useState(isEdit);
  const [submitting, setSubmitting] = useState(false);

  const [users, setUsers] = useState<UserOption[]>([]);
  const [tagOptions, setTagOptions] = useState<TagOption[]>([]);
  const [fetchedStandards, setFetchedStandards] = useState<StdOption[]>([]);
  const [loadingStandards, setLoadingStandards] = useState(false);

  // Ownership is held outside `form` because it saves through a different
  // endpoint (POST /leads/:id/assign) — the one that fires the recipient's
  // notification and email.
  const [assignedTo, setAssignedTo] = useState<number | "">("");
  const [handoverNote, setHandoverNote] = useState("");
  const [notifyOnAssign, setNotifyOnAssign] = useState(true);

  const [duplicates, setDuplicates] = useState<DuplicateMatch[]>([]);
  const [overrideDuplicate, setOverrideDuplicate] = useState(false);

  const setField = <K extends keyof ReturnType<typeof emptyLead>>(
    key: K,
    value: ReturnType<typeof emptyLead>[K],
  ) => setForm((prev) => ({ ...prev, [key]: value }));

  // Prop wins when supplied (same as BatchForm, which is handed its list by
  // the parent). Otherwise the form fetches the list itself, so the two
  // routes don't each need to know where standards come from.
  const standardOptions = standards.length ? standards : fetchedStandards;

  // ── Load reference data ───────────────────────────────────────────────
  useEffect(() => {
    getAssignableUsers()
      .then((res: any) => {
        const rows = Array.isArray(res) ? res : (res?.data ?? res?.rows ?? []);
        setUsers(
          rows.map((u: any) => ({ value: u.id, label: formatUserName(u) })),
        );
      })
      .catch(() => setUsers([]));

    getLeadTags()
      .then((tags) => setTagOptions(tags.map((t) => ({ value: t, label: t }))))
      .catch(() => setTagOptions([]));

    // Skip the round-trip when the parent already handed us the list.
    if (standards.length) return;
    setLoadingStandards(true);
    getStandardOptions()
      .then(setFetchedStandards)
      .catch(() => setFetchedStandards([]))
      .finally(() => setLoadingStandards(false));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // ── Load the lead in edit mode ────────────────────────────────────────
  useEffect(() => {
    if (!isEdit) return;
    setLoading(true);
    getLead(leadId!)
      .then((lead) => {
        setOriginal(lead);
        setForm({
          company: lead.company ?? "",
          client_group: (lead.client_group ?? "QRS") as ClientGroup,
          contact: lead.contact ?? "",
          phone: lead.phone ?? "",
          email: lead.email ?? "",
          website: lead.website ?? "",
          standards: lead.standards ?? [],
          status: lead.status,
          priority: lead.priority,
          source: lead.source ?? "",
          notes: lead.notes ?? "",
          tags: lead.tags ?? [],
          lost_reason: lead.lost_reason ?? "",
          lost_notes: lead.lost_notes ?? "",
        });
        setAssignedTo(lead.assigned_to ?? "");
      })
      .catch((err: any) =>
        toast.error(err?.message || "Could not load the lead"),
      )
      .finally(() => setLoading(false));
  }, [leadId, isEdit]);

  // ── Live duplicate check, debounced ───────────────────────────────────
  const runDuplicateCheck = useCallback(async () => {
    if (!form.company.trim() && !form.email.trim() && !form.phone.trim()) {
      setDuplicates([]);
      return;
    }
    try {
      const res = await checkLeadDuplicates({
        company: form.company.trim() || undefined,
        contact: form.contact.trim() || undefined,
        email: form.email.trim() || undefined,
        phone: form.phone.trim() || undefined,
        ignore_id: leadId,
      });
      setDuplicates((res.matches ?? []).filter((m) => m.severity === "high"));
    } catch {
      setDuplicates([]);
    }
  }, [form.company, form.contact, form.email, form.phone, leadId]);

  useEffect(() => {
    const t = setTimeout(runDuplicateCheck, 600);
    return () => clearTimeout(t);
  }, [runDuplicateCheck]);

  const ownerChanged = useMemo(
    () =>
      isEdit && assignedTo !== "" && assignedTo !== (original?.assigned_to ?? ""),
    [isEdit, assignedTo, original],
  );

  const currentOwnerLabel = original?.assignedUser
    ? formatUserName(original.assignedUser)
    : "nobody";
  const newOwnerLabel =
    users.find((u) => u.value === assignedTo)?.label ?? "the new owner";

  // ── Validation ────────────────────────────────────────────────────────
  const validate = (): string | null => {
    if (!form.company.trim()) return "Company name is required.";
    if (!form.client_group) return "Select a client group.";
    if (!form.contact.trim()) return "Contact person is required.";
    if (!form.email.trim()) return "Email is required.";
    if (!form.standards.length) return "Select at least one standard.";
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email))
      return "Enter a valid email address.";
    if (form.status === "Lost" && !form.lost_reason)
      return "Pick a reason lost so the pipeline report stays meaningful.";
    if (duplicates.length > 0 && !overrideDuplicate && !isEdit)
      return 'This looks like an existing lead — review the matches, then tick "Save anyway" if it really is different.';
    return null;
  };

  // ── Submit ────────────────────────────────────────────────────────────
  const handleSubmit = async (e?: React.FormEvent) => {
    e?.preventDefault();
    const v = validate();
    if (v) return toast.error(v);

    setSubmitting(true);
    try {
      const payload = {
        company: form.company.trim(),
        client_group: form.client_group,
        contact: form.contact.trim() || undefined,
        phone: form.phone.trim() || undefined,
        email: form.email.trim() || undefined,
        website: form.website.trim() || undefined,
        standards: form.standards.length ? form.standards : undefined,
        priority: form.priority,
        source: form.source || undefined,
        notes: form.notes.trim() || undefined,
        tags: form.tags.length ? form.tags : undefined,
        lost_reason: form.status === "Lost" ? form.lost_reason : undefined,
        lost_notes:
          form.status === "Lost"
            ? form.lost_notes.trim() || undefined
            : undefined,
      };

      let savedId: number;

      if (isEdit) {
        // 'Converted' is not a value this endpoint accepts — the backend
        // rejects any transition into it, and re-sending the lead's own
        // current status is a no-op anyway. Omitting the key keeps the
        // payload type-correct without a cast.
        const statusPatch =
          form.status === "Converted" ? {} : { status: form.status };
        await updateLead(leadId!, { ...payload, ...statusPatch });
        savedId = leadId!;
      } else {
        const created = await createLead({
          ...payload,
          status: form.status as Exclude<LeadStatus, "Converted">,
          assigned_to: assignedTo === "" ? undefined : Number(assignedTo),
          override_duplicate: overrideDuplicate || undefined,
        });
        savedId = created.id;
      }

      // Separate call on purpose — this is the one that pings the new owner.
      if (ownerChanged) {
        await assignLead(savedId, {
          assigned_to: Number(assignedTo),
          note: handoverNote.trim() || undefined,
          notify: notifyOnAssign,
        });
      }

      toast.success(
        isEdit
          ? ownerChanged && notifyOnAssign
            ? `Saved. ${newOwnerLabel} has been notified.`
            : "Lead saved"
          : "Lead created",
      );
      router.push("/modules/leads");
      router.refresh();
    } catch (err: any) {
      const dupes = err?.response?.duplicate_matches ?? err?.duplicate_matches;
      if (dupes?.length) {
        toast.error("Possible duplicate — review the matches above.");
        setDuplicates(dupes);
      } else {
        toast.error(err?.message || "Could not save the lead");
      }
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div className={ui.page}>
        <div className={ui.content}>
          <div className={ui.note}>
            <span>⏳</span>
            <span>Loading lead…</span>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className={ui.page}>
      {/* ══ Top bar ═══════════════════════════════════════════════════════ */}
      <div className={ui.topbar}>
        <div className={ui.topbarLeft}>
          <button
            type="button"
            className={ui.backBtn}
            onClick={() => router.push("/modules/leads")}
            disabled={submitting}
            aria-label="Back"
          >
            ←
          </button>
          <div>
            <h1 className={ui.pageTitle}>
              {isEdit ? (original?.lead_code ?? "Edit Lead") : "New Lead"}
            </h1>
            <p className={ui.pageSub}>
              {isEdit
                ? `${original?.company ?? ""} · owned by ${currentOwnerLabel}`
                : "Capture the prospect, then assign an owner"}
            </p>
          </div>
        </div>
        <div className={ui.topbarActions}>
          <button
            type="button"
            className={ui.btnGhost}
            onClick={() => router.push("/modules/leads")}
            disabled={submitting}
          >
            Cancel
          </button>
          <button
            type="button"
            className={ui.btnPrimary}
            onClick={() => handleSubmit()}
            disabled={submitting}
          >
            {submitting
              ? "Saving…"
              : isEdit
                ? ownerChanged
                  ? "Save & Hand Over"
                  : "Save Changes"
                : "Create Lead"}
          </button>
        </div>
      </div>

      {/* ══ Content ═══════════════════════════════════════════════════════ */}
      <div className={ui.content}>
        <form onSubmit={handleSubmit}>
          {/* Duplicate warning — sits above everything because it changes
              what you do next. Reuses .note with an amber override. */}
          {duplicates.length > 0 && (
            <div
              className={ui.note}
              style={{
                background: "#fffbeb",
                border: "1px solid #fde68a",
                color: "#92400e",
                marginBottom: 16,
              }}
            >
              <span>⚠️</span>
              <span>
                <strong>
                  {duplicates.length} existing lead
                  {duplicates.length > 1 ? "s look" : " looks"} like this one
                </strong>
                <ul style={{ margin: "6px 0 0", paddingLeft: 18 }}>
                  {duplicates.slice(0, 4).map((d) => (
                    <li key={d.id} style={{ marginBottom: 3 }}>
                      <strong>{d.lead_code}</strong> — {d.company}
                      {d.contact ? ` · ${d.contact}` : ""} ({d.status})
                    </li>
                  ))}
                </ul>
                {!isEdit && (
                  <label
                    style={{
                      display: "inline-flex",
                      alignItems: "center",
                      gap: 7,
                      marginTop: 9,
                      cursor: "pointer",
                      fontWeight: 600,
                    }}
                  >
                    <input
                      type="checkbox"
                      checked={overrideDuplicate}
                      onChange={(e) => setOverrideDuplicate(e.target.checked)}
                      style={{ accentColor: "#b45309" }}
                    />
                    Save anyway — this is a different company
                  </label>
                )}
              </span>
            </div>
          )}

          {/* ── Step 1 · Company ─────────────────────────────────────────── */}
          <div className={ui.card}>
            <div className={ui.cardHead}>
              <div className={ui.cardHeadLeft}>
                <span className={ui.stepBadge}>1</span>
                <div>
                  <p className={ui.cardTitle}>Company</p>
                  <p className={ui.cardHint}>
                    Who the lead is, and which group they belong to
                  </p>
                </div>
              </div>
            </div>
            <div className={ui.cardBody}>
              <div className={ui.grid}>
                <div className={ui.full}>
                  <label className={`${ui.label} ${ui.req}`}>Company Name</label>
                  <input
                    type="text"
                    className={ui.input}
                    value={form.company}
                    onChange={(e) => setField("company", e.target.value)}
                    placeholder="e.g., Acme Industries LLC"
                    maxLength={255}
                  />
                </div>

                {/* 🆕 Client group — identical toggle to BatchForm's Group */}
                <div className={`${ui.field} ${ui.half}`}>
                  <label className={ui.req}>Group</label>
                  <div className={ui.groupToggle}>
                    {GROUP_VALUES.map((g) => (
                      <button
                        key={g}
                        type="button"
                        className={`${ui.groupBtn} ${form.client_group === g ? ui.groupBtnActive : ""}`}
                        onClick={() => setField("client_group", g)}
                        disabled={submitting}
                      >
                        {groupLabel(g)}
                        {form.client_group === g && (
                          <span className={ui.groupCheck}>✓</span>
                        )}
                      </button>
                    ))}
                  </div>
                  <div className={ui.helper}>
                    Reports and filters count this lead under{" "}
                    <strong>{groupToBucket(form.client_group)}</strong>
                    {form.client_group === "QRS_B" ? " — QRS-B rolls into QRS" : ""}
                  </div>
                </div>

                <div className={`${ui.field} ${ui.half}`}>
                  <label>Source</label>
                  <Select
                    {...selectBase}
                    options={SOURCE_OPTIONS}
                    value={
                      SOURCE_OPTIONS.find((o) => o.value === form.source) ?? null
                    }
                    onChange={(o) =>
                      setField("source", (o?.value as string) ?? "")
                    }
                    placeholder="How did they reach us?"
                    isClearable
                    isDisabled={submitting}
                  />
                </div>

                <div className={ui.full}>
                  <label className={ui.label}>Website</label>
                  <input
                    type="url"
                    className={ui.input}
                    value={form.website}
                    onChange={(e) => setField("website", e.target.value)}
                    placeholder="https://www.company.com"
                  />
                </div>

                {/* Standards — identical control to BatchAuditRequestForm:
                    same react-select multi, same placeholder, same required
                    rule. Values are standard NAMES here because the leads
                    table stores them as a JSON array of strings, not FK ids. */}
                <div className={ui.full}>
                  <label className={`${ui.label} ${ui.req}`}>Standards</label>
                  <Select
                    {...selectBase}
                    isMulti
                    options={standardOptions}
                    value={standardOptions.filter((o) =>
                      form.standards.includes(o.value),
                    )}
                    onChange={(opts) =>
                      setField(
                        "standards",
                        (opts ?? []).map((o: any) => o.value),
                      )
                    }
                    placeholder="Pick one or more standards (e.g., ISO 9001:2015)"
                    isDisabled={submitting}
                    isLoading={loadingStandards}
                    noOptionsMessage={() =>
                      loadingStandards
                        ? "Loading standards…"
                        : "No standards found"
                    }
                  />
                </div>
              </div>
            </div>
          </div>

          {/* ── Step 2 · Contact ─────────────────────────────────────────── */}
          <div className={ui.card}>
            <div className={ui.cardHead}>
              <div className={ui.cardHeadLeft}>
                <span className={ui.stepBadge}>2</span>
                <div>
                  <p className={ui.cardTitle}>Contact</p>
                  <p className={ui.cardHint}>Who to call, and how</p>
                </div>
              </div>
            </div>
            <div className={ui.cardBody}>
              <div className={ui.grid}>
                <div className={`${ui.field} ${ui.half}`}>
                  <label className={ui.req}>Contact Person</label>
                  <input
                    type="text"
                    className={ui.input}
                    value={form.contact}
                    onChange={(e) => setField("contact", e.target.value)}
                    placeholder="e.g., Mr. Azhar K Mohamed"
                  />
                </div>

                <div className={`${ui.field} ${ui.half}`}>
                  <label>Phone</label>
                  <input
                    type="text"
                    className={ui.input}
                    value={form.phone}
                    onChange={(e) => setField("phone", e.target.value)}
                    placeholder="+971 56 367 9416"
                  />
                </div>

                <div className={`${ui.field} ${ui.half}`}>
                  <label className={ui.req}>Email</label>
                  <input
                    type="email"
                    className={ui.input}
                    value={form.email}
                    onChange={(e) => setField("email", e.target.value)}
                    placeholder="contact@company.com"
                  />
                </div>

                <div className={`${ui.field} ${ui.half}`}>
                  <label>Priority</label>
                  <div className={ui.groupToggle}>
                    {PRIORITY_VALUES.map((p) => (
                      <button
                        key={p}
                        type="button"
                        className={`${ui.groupBtn} ${form.priority === p ? ui.groupBtnActive : ""}`}
                        onClick={() => setField("priority", p)}
                        disabled={submitting}
                      >
                        {p}
                        {form.priority === p && (
                          <span className={ui.groupCheck}>✓</span>
                        )}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* ── Step 3 · Pipeline ────────────────────────────────────────── */}
          <div className={ui.card}>
            <div className={ui.cardHead}>
              <div className={ui.cardHeadLeft}>
                <span className={ui.stepBadge}>3</span>
                <div>
                  <p className={ui.cardTitle}>Pipeline Status</p>
                  <p className={ui.cardHint}>Where this sits today</p>
                </div>
              </div>
            </div>
            <div className={ui.cardBody}>
              <div className={ui.grid}>
                <div className={`${ui.field} ${ui.half}`}>
                  <label className={ui.req}>Status</label>
                  {original?.status === "Converted" ? (
                    <div className={ui.note}>
                      <span>✅</span>
                      <span>
                        Already converted to a client. Status changes go through
                        the convert-to-client flow, not this form.
                      </span>
                    </div>
                  ) : (
                    <div className={ui.groupToggle}>
                      {STATUS_VALUES.map((s) => (
                        <button
                          key={s}
                          type="button"
                          className={`${ui.groupBtn} ${form.status === s ? ui.groupBtnActive : ""}`}
                          onClick={() => setField("status", s)}
                          disabled={submitting}
                        >
                          {s}
                          {form.status === s && (
                            <span className={ui.groupCheck}>✓</span>
                          )}
                        </button>
                      ))}
                    </div>
                  )}
                </div>

                {form.status === "Lost" && (
                  <div className={`${ui.field} ${ui.half}`}>
                    <label className={ui.req}>Reason Lost</label>
                    <Select
                      {...selectBase}
                      options={LOST_REASON_OPTIONS}
                      value={
                        LOST_REASON_OPTIONS.find(
                          (o) => o.value === form.lost_reason,
                        ) ?? null
                      }
                      onChange={(o) =>
                        setField("lost_reason", (o?.value as string) ?? "")
                      }
                      placeholder="Why did it fall through?"
                        isDisabled={submitting}
                  />
                  </div>
                )}

                {form.status === "Lost" && (
                  <div className={ui.full}>
                    <label className={ui.label}>What Happened</label>
                    <textarea
                      className={ui.textarea}
                      rows={2}
                      value={form.lost_notes}
                      onChange={(e) => setField("lost_notes", e.target.value)}
                      placeholder="Context for whoever picks this up again in six months…"
                      maxLength={2000}
                    />
                  </div>
                )}

                <div className={ui.full}>
                  <label className={ui.label}>Tags</label>
                  <CreatableSelect
                    {...selectBase}
                    isMulti
                    options={tagOptions}
                    value={form.tags.map((t) => ({ value: t, label: t }))}
                    onChange={(opts) =>
                      setField(
                        "tags",
                        (opts ?? []).map((o: any) => o.value),
                      )
                    }
                    placeholder="Type a tag and press Enter…"
                    formatCreateLabel={(v) => `Add tag "${v}"`}
                    isDisabled={submitting}
                  />
                  <div className={ui.helper}>
                    Existing tags are suggested as you type — reuse them rather
                    than inventing near-duplicates, or the tag filter fragments.
                  </div>
                </div>

                <div className={ui.full}>
                  <label className={ui.label}>Notes</label>
                  <textarea
                    className={ui.textarea}
                    rows={3}
                    value={form.notes}
                    onChange={(e) => setField("notes", e.target.value)}
                    placeholder="Pricing discussed, follow-up commitments, etc."
                    maxLength={4000}
                  />
                </div>
              </div>
            </div>
          </div>

          {/* ── Step 4 · Ownership ───────────────────────────────────────── */}
          <div className={ui.card}>
            <div className={ui.cardHead}>
              <div className={ui.cardHeadLeft}>
                <span className={ui.stepBadge}>4</span>
                <div>
                  <p className={ui.cardTitle}>Ownership</p>
                  <p className={ui.cardHint}>
                    {isEdit
                      ? "Changing the owner notifies them straight away"
                      : "Who should follow this up"}
                  </p>
                </div>
              </div>
            </div>
            <div className={ui.cardBody}>
              <div className={ui.grid}>
                <div className={`${ui.field} ${ui.half}`}>
                  <label>Assigned To</label>
                  <Select
                    {...selectBase}
                    options={users}
                    value={users.find((u) => u.value === assignedTo) ?? null}
                    onChange={(o) => setAssignedTo((o?.value as number) ?? "")}
                    placeholder={
                      users.length ? "Pick an owner…" : "Loading people…"
                    }
                    isClearable
                    isDisabled={submitting}
                  />
                  <div className={ui.helper}>
                    {isEdit
                      ? `Currently ${currentOwnerLabel}`
                      : "Leave blank to keep it yourself."}
                  </div>
                </div>

                {ownerChanged && (
                  <>
                    <div className={ui.full}>
                      <div className={ui.note}>
                        <span>📤</span>
                        <span>
                          <strong>{currentOwnerLabel}</strong> →{" "}
                          <strong>{newOwnerLabel}</strong>
                          {notifyOnAssign
                            ? " — they'll get a notification and an email as soon as you save."
                            : " — notifications are off, so nobody will be told."}
                        </span>
                      </div>
                    </div>

                    <div className={ui.full}>
                      <label className={ui.label}>Handover Note</label>
                      <textarea
                        className={ui.textarea}
                        rows={2}
                        value={handoverNote}
                        onChange={(e) => setHandoverNote(e.target.value)}
                        placeholder="e.g., You've worked with this client before — they asked for you by name."
                        maxLength={1000}
                      />
                      <div className={ui.helper}>
                        Included in both the notification and the email.
                      </div>
                    </div>

                    <div className={ui.full}>
                      <label
                        style={{
                          display: "inline-flex",
                          alignItems: "flex-start",
                          gap: 8,
                          cursor: "pointer",
                        }}
                      >
                        <input
                          type="checkbox"
                          checked={notifyOnAssign}
                          onChange={(e) => setNotifyOnAssign(e.target.checked)}
                          style={{ marginTop: 2, accentColor: "#0f766e" }}
                        />
                        <span>
                          <strong>Tell {newOwnerLabel} about this</strong>
                          <div className={ui.helper}>
                            On by default. Turn it off only for bulk cleanups —
                            a silent handover is how leads get dropped.
                          </div>
                        </span>
                      </label>
                    </div>
                  </>
                )}
              </div>
            </div>
          </div>

          <div className={ui.note}>
            <span>💡</span>
            <span>
              {isEdit ? (
                <>
                  Field edits save straight away, but{" "}
                  <strong>ownership is sent separately</strong> so the new owner
                  gets a notification and an email — which is why the button
                  reads &ldquo;Save &amp; Hand Over&rdquo; once you pick someone
                  new.
                </>
              ) : (
                <>
                  The lead code is generated automatically on save. If this
                  company already exists as a lead or a client, you&rsquo;ll be
                  warned before anything is written.
                </>
              )}
            </span>
          </div>
        </form>
      </div>
    </div>
  );
}