"use client";

import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import toast from "react-hot-toast";
import {
  FiArrowLeft,
  FiSave,
  FiCircle,
  FiPlus,
  FiChevronDown,
  FiChevronRight,
  FiInfo,
  FiCheck,
  FiLock,
  FiFileText,
  FiSearch,
  FiList,
  FiClipboard,
  FiCalendar,
  FiUser,
  FiTag,
  FiAward,
  FiUserCheck,
} from "react-icons/fi";
import { EnterpriseLoader } from "../../../../../components/loader/loader";
import {
  getPreviousNc,
  updatePreviousNc,
  deleteEntry,
} from "@/lib/api/previous-nc.api";
import type {
  NcSource,
  PreviousNcDetailResponse,
  UpdatePreviousNcDto,
} from "@/lib/api/types/previous-nc.types";
import FindingListItem from "./FindingListItem";
import FindingDetail from "./FindingDetail";
import AddFindingPanel from "./AddFindingPanel";
import EmailNotificationsPanel, {
  defaultEmailPrefs,
  type EmailPrefs,
} from "./EmailNotificationsPanel";
import ClosurePanel from "./ClosurePanel"; // 🆕 PHASE 2A
import type { EditableEntry } from "./findings.types";
import { isDraft } from "./findings.types";
// 🆕 Field-level permissions — same hook the Company form uses
import { useModulePermissions } from "@/lib/api/hooks/useModulePermissions";



// Module key used for permission lookups (change to match your config).
const PERMISSION_MODULE = "previous-nc";

// ── Raw API base + auth (create endpoint isn't in previous-nc.api yet) ──
const API_BASE =
  process.env.NEXT_PUBLIC_API_URL?.replace(/\/api$/, "") ||
  process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/api$/, "") ||
  "";

function getAuthToken(): string {
  if (typeof window === "undefined") return "";
  return (
    localStorage.getItem("access_token") ||
    sessionStorage.getItem("access_token") ||
    localStorage.getItem("token") ||
    localStorage.getItem("authToken") ||
    ""
  );
}

function authHeaders(): HeadersInit {
  const token = getAuthToken();
  return token
    ? { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }
    : { "Content-Type": "application/json" };
}

export default function NcEditPage() {
  const router = useRouter();
  const search = useSearchParams();

  // ── Mode detection ──────────────────────────────────────────────────
  // RAISE route passes ?audit_id=… with no id  → create mode.
  // EDIT route passes ?source=…&id=…           → edit mode.
  const idStr = search.get("id") || "";
  const id = Number(idStr);
  const auditId = Number(search.get("audit_id") || "");
  const mode: "create" | "edit" = !id && auditId ? "create" : "edit";
  const isCreate = mode === "create";

  const source = (
    isCreate ? "NEW" : (search.get("source") || "QRS").toUpperCase()
  ) as NcSource;

  // ── Field-level permissions (same as the Company form) ──────────────
  const { visibleFieldKeys, isReady: permsReady } =
    useModulePermissions(PERMISSION_MODULE);

  const showField = (key: string): boolean => {
    if (!permsReady) return true; // still loading → show everything
    if (!visibleFieldKeys) return true; // no restriction configured
    return visibleFieldKeys.includes(key);
  };

  const [data, setData] = useState<PreviousNcDetailResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [sendingEmail, setSendingEmail] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // ── NC-level editable state ──
  const [auditeeName, setAuditeeName] = useState("");
  const [auditType, setAuditType] = useState("");
  const [ncType, setNcType] = useState("");
  const [status, setStatus] = useState<"open" | "closed">("open");
  const [dueDate, setDueDate] = useState("");
  const [followUpDate, setFollowUpDate] = useState("");
  const [followUpNotes, setFollowUpNotes] = useState("");
  const [remark, setRemark] = useState("");
  const [auditees, setAuditees] = useState<{ name: string; designation: string }[]>([]);
  // ── Findings ──
  const [entries, setEntries] = useState<EditableEntry[]>([]);
  const [selectedEntryId, setSelectedEntryId] = useState<number | null>(null);
  const [findingSearch, setFindingSearch] = useState("");
  const [showAddPanel, setShowAddPanel] = useState(false);
  const [nextDraftId, setNextDraftId] = useState(-1);

  // ── Remarks ──
  const [newRemark, setNewRemark] = useState<string>("");

  // ── Email prefs (client-side, Phase 2 backend) ──
  const [emailPrefs, setEmailPrefs] = useState<EmailPrefs>(defaultEmailPrefs);

  // ── Section toggles ──
  const [contextOpen, setContextOpen] = useState(true); // EXPANDED at top
  const [closureOpen, setClosureOpen] = useState(true); // NEW closure section
  const [remarksOpen, setRemarksOpen] = useState(false);
  const [followupOpen, setFollowupOpen] = useState(true); // create-mode notes

  // ─── Load NC ───────────────────────────────────────────────────────
  const fetchData = useCallback(async () => {
    // ── CREATE MODE: no NC yet — seed a blank workspace from the audit ──
    if (isCreate) {
      if (!auditId) {
        setError("No audit_id in URL.");
        setLoading(false);
        return;
      }
      setLoading(true);
      setError(null);
      try {
        // Pull company / audit type / standards / contact details from the audit.
        let company_name: string | null = null;
        let audit_type: string | null = null;
        let standard_names: string[] = [];
        let created_by_name: string | null = null;
        let audit_date: string | null = null;
        let contact_person: string | null = null;
        let designation: string | null = null;
        let client_email: string | null = null;
        let mobile: string | null = null;
        let prefillAuditee = "";
        try {
          const r = await fetch(
            `${API_BASE}/api/audits/${auditId}/workspace`,
            { headers: authHeaders(), cache: "no-store" },
          );
          if (r.ok) {
            const d = await r.json();
            const row = d?.audit ?? d?.row ?? d ?? {};
            const company = row.company ?? d?.company ?? {};
            audit_type = row.audit_type ?? d?.audit_type ?? null;
            company_name =
              company.name ??
              row.company_name ??
              d?.company_name ??
              null;
            standard_names =
              row.standard_names ??
              d?.standard_names ??
              (company.standards || row.standards || [])
                .map((s: any) => (typeof s === "object" ? s.name : s))
                .filter(Boolean);
            created_by_name = d?.current_user_name ?? null;

            // Auditor shown on top = the audit's lead auditor.
            const fmtUser = (u: any): string | null => {
              if (!u) return null;
              if (typeof u === "string") return u.trim() || null;
              const n = [
                u.firstName ?? u.first_name,
                u.lastName ?? u.last_name,
              ]
                .filter(Boolean)
                .join(" ")
                .trim();
              return n || u.name || null;
            };
            created_by_name =
              fmtUser(row.lead_auditor) ??
              fmtUser(d?.lead_auditor) ??
              row.lead_auditor_name ??
              d?.lead_auditor_name ??
              fmtUser(row.auditor) ??
              fmtUser(d?.auditor) ??
              d?.current_user_name ??
              null;

            // Audit date (schedule date) — try a few common shapes.
            audit_date =
              row.schedule_date ??
              row.schedule?.schedule_date ??
              d?.schedule_date ??
              d?.schedule?.schedule_date ??
              null;

            // Auditee / company contact details.
            contact_person = company.contact_person ?? row.contact_person ?? null;
            designation = company.designation ?? row.designation ?? null;
            client_email = company.email ?? row.email ?? null;
            mobile = company.mobile ?? row.mobile ?? null;

            // Prefill the editable "Auditee name" from contact + designation,
            // skipping placeholder designations like "Unknown" / "N/A" / "—".
            const junk = ["unknown", "n/a", "na", "-", "—", ""];
            const cleanDesignation =
              designation && !junk.includes(designation.trim().toLowerCase())
                ? designation
                : null;
            prefillAuditee = [contact_person, cleanDesignation]
              .filter(Boolean)
              .join(" - ");
            prefillAuditee = [contact_person, cleanDesignation]
              .filter(Boolean)
              .join(" - ");

            // 🆕 pre-fill attendance list from the linked audit request
            const reqAuditees =
              d?.audit_request?.auditees ??
              row?.audit_request?.auditees ??
              d?.auditees ??
              row?.auditees ??
              [];
            if (Array.isArray(reqAuditees) && reqAuditees.length) {
              setAuditees(
                reqAuditees
                  .map((a: any) => ({
                    name: String(a?.name ?? "").trim(),
                    designation: String(a?.designation ?? a?.position ?? "").trim(),
                  }))
                  .filter((a: any) => a.name),
              );
            }
          }
        } catch {
          /* non-fatal — user can still raise the NC */
        }

        // Synthetic detail response so the whole edit UI renders unchanged.
        const synthetic = {
          nc: {
            company_name,
            audit_type,
            audit_date,
            created_by_name,
            assigned_to_name: null,
            closed_at: null,
            standard_names,
            status: "open",
            nc_type: "Minor",
            auditee_name: prefillAuditee,
            due_date: null,
            follow_up_date: null,
            follow_up_notes: "",
            remark: "",
            // extra create-mode display fields (read from audit)
            contact_person,
            designation,
            client_email,
            mobile,
          },
          entries: [],
          remarks: [],
        } as unknown as PreviousNcDetailResponse;

        setData(synthetic);
        setAuditeeName(prefillAuditee);
        setAuditType(audit_type || "");
        setNcType("Minor");
        setStatus("open");
        setDueDate("");
        setFollowUpDate("");
        setFollowUpNotes("");
        setRemark("");

        // Start with one blank draft finding so the workspace isn't empty.
        const firstDraft: EditableEntry = {
          id: -1,
          nc_type: "",
          ncr_statement: "",
          criteria_clause: "",
          corrective_action: "",
          status: "open",
          document_path: null,
          _dirty: true,
        };
        setEntries([firstDraft]);
        setSelectedEntryId(-1);
        setNextDraftId(-2);
      } catch (err: any) {
        setError(err?.message ?? "Failed to start new NC");
      } finally {
        setLoading(false);
      }
      return;
    }

    // ── EDIT MODE ──
    if (!id || (source !== "QRS" && source !== "TQS" && source !== "NEW")) {
      setError("Invalid source or id in URL.");
      setLoading(false);
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const res = await getPreviousNc(source, id);
      setData(res);
      setAuditeeName(res.nc.auditee_name || "");
      setAuditType(res.nc.audit_type || "");
      setNcType(res.nc.nc_type || "");
      setStatus((res.nc.status as "open" | "closed") || "open");
      setDueDate(toDateInput(res.nc.due_date));
      setFollowUpDate(toDateInput(res.nc.follow_up_date));
      setFollowUpNotes(res.nc.follow_up_notes || "");
      setRemark(res.nc.remark || "");
      const savedAuditees =
        (res.nc as any).auditees_json ?? (res.nc as any).auditees;
      if (savedAuditees) {
        try {
          const arr =
            typeof savedAuditees === "string"
              ? JSON.parse(savedAuditees)
              : savedAuditees;
          if (Array.isArray(arr)) {
            setAuditees(
              arr
                .map((a: any) => ({
                  name: String(a?.name ?? "").trim(),
                  designation: String(a?.designation ?? a?.position ?? "").trim(),
                }))
                .filter((a: any) => a.name),
            );
          }
        } catch {
          /* ignore */
        }
      }
      const mapped = (res.entries || []).map((e) => ({
        id: e.id,
        nc_type: e.nc_type || "",
        ncr_statement: e.ncr_statement || "",
        criteria_clause: e.criteria_clause || "",
        corrective_action: e.corrective_action || "",
        status: (e.status as "open" | "closed" | "pending") || "open",
        document_path: e.document_path || null,
        _dirty: false,
      }));
      setEntries(mapped);
      if (mapped.length > 0 && !selectedEntryId) {
        setSelectedEntryId(mapped[0].id);
      }
    } catch (err: any) {
      setError(err?.message ?? "Failed to load NC");
    } finally {
      setLoading(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [source, id, isCreate, auditId]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  // ─── Filtered findings (search) ────────────────────────────────────
  const filteredEntries = useMemo(() => {
    const q = findingSearch.trim().toLowerCase();
    if (!q) return entries;
    return entries.filter(
      (e) =>
        (e.ncr_statement || "").toLowerCase().includes(q) ||
        (e.criteria_clause || "").toLowerCase().includes(q) ||
        (e.nc_type || "").toLowerCase().includes(q),
    );
  }, [entries, findingSearch]);

  // ─── Selected entry ────────────────────────────────────────────────
  const selectedIdx = useMemo(
    () => entries.findIndex((e) => e.id === selectedEntryId),
    [entries, selectedEntryId],
  );
  const selected = selectedIdx >= 0 ? entries[selectedIdx] : null;

  // ─── Update entry ──────────────────────────────────────────────────
  const updateEntry = useCallback(
    (entryId: number, patch: Partial<EditableEntry>) => {
      setEntries((prev) =>
        prev.map((e) =>
          e.id === entryId
            ? {
              ...e,
              ...patch,
              _dirty: patch.document_path !== undefined ? e._dirty : true,
            }
            : e,
        ),
      );
    },
    [],
  );

  const refreshEntryFile = useCallback(
    (entryId: number, newPath: string | null) => {
      setEntries((prev) =>
        prev.map((e) =>
          e.id === entryId ? { ...e, document_path: newPath } : e,
        ),
      );
    },
    [],
  );

  // ─── Add new finding (draft) ───────────────────────────────────────
  const handleAddDraft = useCallback(
    (draft: Omit<EditableEntry, "id" | "_dirty">) => {
      const newId = nextDraftId;
      const entry: EditableEntry = { id: newId, _dirty: true, ...draft };
      setEntries((prev) => [...prev, entry]);
      setSelectedEntryId(newId);
      setNextDraftId(newId - 1);
      setShowAddPanel(false);
      toast.success("Draft NC added — fill in remaining fields");
    },
    [nextDraftId],
  );
  // 🆕 auditee list helpers
  const addAuditee = () =>
    setAuditees((p) => [...p, { name: "", designation: "" }]);
  const removeAuditee = (i: number) =>
    setAuditees((p) => p.filter((_, idx) => idx !== i));
  const updateAuditee = (i: number, key: "name" | "designation", val: string) =>
    setAuditees((p) => p.map((a, idx) => (idx === i ? { ...a, [key]: val } : a)));
  // ─── Prev / Next navigation ────────────────────────────────────────
  const goPrev = useCallback(() => {
    if (selectedIdx > 0) setSelectedEntryId(entries[selectedIdx - 1].id);
  }, [entries, selectedIdx]);

  const goNext = useCallback(() => {
    if (selectedIdx < entries.length - 1)
      setSelectedEntryId(entries[selectedIdx + 1].id);
  }, [entries, selectedIdx]);

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      const tag = (e.target as HTMLElement)?.tagName;
      if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return;
      if (e.key === "ArrowDown" || e.key === "j") {
        e.preventDefault();
        goNext();
      } else if (e.key === "ArrowUp" || e.key === "k") {
        e.preventDefault();
        goPrev();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [goPrev, goNext]);

  // ─── Delete a finding ──────────────────────────────────────────────
  const handleDeleteEntry = useCallback(
    async (entryId: number) => {
      const entry = entries.find((e) => e.id === entryId);
      if (!entry) return;

      // Draft entries: just remove locally
      if (isDraft(entry)) {
        if (!window.confirm("Discard this draft finding?")) return;
        const remaining = entries.filter((e) => e.id !== entryId);
        setEntries(remaining);
        if (selectedEntryId === entryId) {
          const newIdx = Math.min(selectedIdx, remaining.length - 1);
          setSelectedEntryId(remaining[newIdx]?.id ?? null);
        }
        toast.success("Draft discarded");
        return;
      }

      // Real entries: confirm + delete via backend
      const hasFile = !!entry.document_path;
      const isLegacy = hasFile && !entry.document_path!.startsWith("new:");
      const msg = hasFile
        ? isLegacy
          ? "Delete this finding?\n\nThe linked legacy file stays in the old CRM. Only the link is removed.\n\nThis cannot be undone."
          : "Delete this finding?\n\nThe uploaded evidence file will also be permanently deleted.\n\nThis cannot be undone."
        : "Delete this finding?\n\nThis cannot be undone.";
      if (!window.confirm(msg)) return;
      try {
        await deleteEntry(source, id, entryId);
        const remaining = entries.filter((e) => e.id !== entryId);
        setEntries(remaining);
        if (selectedEntryId === entryId) {
          const newIdx = Math.min(selectedIdx, remaining.length - 1);
          setSelectedEntryId(remaining[newIdx]?.id ?? null);
        }
        toast.success("NC deleted");
      } catch (err: any) {
        toast.error(err?.message ?? "Failed to delete finding");
      }
    },
    [entries, source, id, selectedEntryId, selectedIdx],
  );

  // ─── Save ──────────────────────────────────────────────────────────
  const handleSave = async () => {
    if (!data) return;

    // ── CREATE MODE: POST a brand-new NC, then slide into edit mode ──
    if (isCreate) {
      const valid = entries.filter((e) => e.ncr_statement.trim());
      if (valid.length === 0) {
        toast.error("Add at least one NC with a statement.");
        return;
      }
      if (!ncType.trim()) {
        toast.error("Select an NC type.");
        return;
      }
      setSaving(true);
      try {
        const body = {
          audit_id: auditId,
          nc_type: ncType,
          status: "open",
          auditee_name: auditeeName.trim() || null,
          auditees: auditees.filter((a) => a.name.trim()),   // 🆕
          follow_up_date: followUpDate || null,
          due_date: dueDate || null,
          follow_up_notes: followUpNotes.trim() || null,
          remark: remark.trim() || null,
          findings: valid.map((f) => ({
            ncr_statement: f.ncr_statement.trim(),
            criteria_clause: f.criteria_clause.trim() || undefined,
            corrective_action: f.corrective_action.trim() || undefined,
            nc_type: f.nc_type.trim() || undefined,
            status: f.status || "open",
          })),
        };
        const res = await fetch(`${API_BASE}/api/previous-nc/new`, {
          method: "POST",
          headers: authHeaders(),
          body: JSON.stringify(body),
        });
        if (!res.ok) {
          let detail = "";
          try {
            const b = await res.json();
            detail = Array.isArray(b?.message)
              ? b.message.join("; ")
              : b?.message || "";
          } catch { }
          throw new Error(detail || `Request failed (${res.status})`);
        }
        const result = await res.json();
        toast.success("New NC Raised Successfully", { duration: 3000 });
        // Show the toast, then go back to the Previous NC module list.
        setTimeout(() => {
          router.push("/modules/previous-nc");
          router.refresh(); // re-fetch so the new NC appears in the list
        }, 800);
      } catch (err: any) {
        toast.error(err?.message ?? "Failed to raise NC");
        setSaving(false);
      }
      return;
    }



    // ── EDIT MODE ──
    const drafts = entries.filter((e) => isDraft(e));
    setSaving(true);
    try {
      const payload: UpdatePreviousNcDto = {
        nc: {
          auditee_name: auditeeName.trim() || null,
          audit_type: auditType.trim() || null,
          nc_type: ncType.trim() || null,
          status,
          due_date: dueDate || null,
          follow_up_date: followUpDate || null,
          follow_up_notes: followUpNotes.trim() || null,
          remark: remark.trim() || null,
        },
        entries: entries
          .filter((e) => !isDraft(e) && e._dirty)
          .map((e) => ({
            id: e.id,
            nc_type: e.nc_type,
            ncr_statement: e.ncr_statement,
            criteria_clause: e.criteria_clause,
            corrective_action: e.corrective_action,
            status: e.status,
          })),
        new_findings: drafts
          .filter((e) => e.ncr_statement.trim())
          .map((e) => ({
            ncr_statement: e.ncr_statement.trim(),
            nc_type: e.nc_type.trim() || undefined,
            criteria_clause: e.criteria_clause.trim() || undefined,
            corrective_action: e.corrective_action.trim() || undefined,
            status: e.status || "open",
          })),
        new_remark: newRemark.trim() || undefined,
      };
      const res = await updatePreviousNc(source, id, payload);
      toast.success(
        `Saved — ${res.updated_fields.length} field(s), ${res.updated_entries} NC(s)`,
      );
      await fetchData();
      setNewRemark("");
    } catch (err: any) {
      toast.error(err?.message ?? "Failed to save NC");
    } finally {
      setSaving(false);
    }
  };

  // ── Send NC notification emails (manual) ──
  const handleSendEmail = async () => {
    if (isCreate || !id) {
      toast.error("Raise the NC first, then send the email.");
      return;
    }
    setSendingEmail(true);
    try {
      const done: string[] = [];

      // ── Option 1: NC doc → client (existing notification endpoint) ──
      if (emailPrefs.send_nc_to_client) {
        const res = await fetch(
          `${API_BASE}/api/previous-nc/${source}/${id}/send-email`,
          {
            method: "POST",
            headers: authHeaders(),
            body: JSON.stringify({
              send_nc_to_client: true,
              client_to: emailPrefs.client_to,
              client_cc: emailPrefs.client_cc,
              client_bcc: emailPrefs.client_bcc,
              send_to_coord_auditor: false,
            }),
          },
        );
        if (!res.ok) {
          const b = await res.json().catch(() => ({}));
          throw new Error(
            Array.isArray(b?.message) ? b.message.join("; ") : b?.message || `Failed (${res.status})`,
          );
        }
        done.push("NC doc → client");
      }

      // ── Option 2: uploaded evidence → coordinator / auditor ──
      if (emailPrefs.send_to_coord_auditor) {
        const evidence_to = [emailPrefs.auditor_email, emailPrefs.coordinator_email]
          .map((s) => (s || "").trim())
          .filter(Boolean)
          .join(", ");

        if (!evidence_to) {
          throw new Error("Enter an auditor or coordinator email for the evidence.");
        }

        const res = await fetch(
          `${API_BASE}/api/previous-nc/closures/${source}/${id}/send-evidence`,
          {
            method: "POST",
            headers: authHeaders(),
            body: JSON.stringify({ evidence_to }),
          },
        );
        if (!res.ok) {
          const b = await res.json().catch(() => ({}));
          throw new Error(
            Array.isArray(b?.message) ? b.message.join("; ") : b?.message || `Failed (${res.status})`,
          );
        }
        const r = await res.json();
        done.push(`evidence (${r.files_attached} file${r.files_attached === 1 ? "" : "s"})`);
      }

      if (done.length === 0) {
        toast.error("Select at least one option to send.");
      } else {
        toast.success(`Email sent successfully — ${done.join(" + ")}`, {
          duration: 4000,
        });
      }
    } catch (err: any) {
      toast.error(err?.message ?? "Failed to send email");
    } finally {
      setSendingEmail(false);
    }
  };

  const dirtyCount = useMemo(
    () => entries.filter((e) => e._dirty && !isDraft(e)).length,
    [entries],
  );
  const draftCount = useMemo(
    () => entries.filter((e) => isDraft(e)).length,
    [entries],
  );

  if (loading) return <EnterpriseLoader />;

  if (error) {
    return (
      <div
        style={{
          padding: "60px 20px",
          textAlign: "center",
          color: "#dc2626",
        }}
      >
        <h3 style={{ margin: "0 0 8px", color: "#111827", fontSize: 16 }}>
          Error
        </h3>
        <p style={{ margin: "0 0 16px", fontSize: 13 }}>{error}</p>
        <button
          onClick={() => router.push("/modules/previous-nc")}
          style={{
            padding: "9px 18px",
            background: "#0b1220",
            color: "#fff",
            border: "none",
            borderRadius: 8,
            fontSize: 13,
            fontWeight: 600,
            cursor: "pointer",
          }}
        >
          Back to list
        </button>
      </div>
    );
  }

  if (!data) return null;
  const { nc, remarks } = data;
  const ncCode = isCreate
    ? `Audit #${auditId}`
    : `NC-${source}-${String(id).padStart(6, "0")}`;
  const closedCount = entries.filter(
    (e) => e.status === "closed" && !isDraft(e),
  ).length;
  const openCount = entries.filter(
    (e) => e.status === "open" && !isDraft(e),
  ).length;
  const withEvidenceCount = entries.filter(
    (e) => !!e.document_path && !isDraft(e),
  ).length;
  const realCount = entries.filter((e) => !isDraft(e)).length;

  return (
    <div
      style={{
        background: "#f6f8fa",
        minHeight: "100vh",
        fontFamily:
          "Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
        color: "#0b1220",
      }}
    >
      {/* ════════════════════════════════════════════════════════════════
          TOP BAR (sticky)
      ════════════════════════════════════════════════════════════════ */}
      <div
        style={{
          background: "#fff",
          borderBottom: "1px solid #e2e8f0",
          padding: "14px 24px",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 16,
          flexWrap: "wrap",
          position: "sticky",
          top: 0,
          zIndex: 50,
        }}
      >
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 14,
            minWidth: 0,
            flex: 1,
          }}
        >
          <button
            onClick={() => router.back()}
            title="Back"
            style={{
              background: "#fff",
              border: "1px solid #e2e8f0",
              borderRadius: 7,
              padding: "6px 11px",
              color: "#475569",
              cursor: "pointer",
              fontSize: 11,
              fontWeight: 500,
              display: "inline-flex",
              alignItems: "center",
              gap: 5,
              flexShrink: 0,
            }}
          >
            <FiArrowLeft size={13} />
            Back
          </button>
          <div style={{ minWidth: 0 }}>
            <div
              style={{
                display: "flex",
                alignItems: "center",
                gap: 6,
                marginBottom: 2,
              }}
            >
              <span
                style={{
                  fontSize: 9,
                  padding: "2px 7px",
                  background: isCreate ? "#15803d" : "#0b1220",
                  color: "#fff",
                  borderRadius: 4,
                  fontWeight: 700,
                  letterSpacing: "0.06em",
                }}
              >
                {isCreate ? "NEW" : source}
              </span>
              <span
                style={{
                  fontSize: 10,
                  color: "#94a3b8",
                  fontFamily: "'JetBrains Mono', monospace",
                  letterSpacing: "0.02em",
                }}
              >
                {ncCode}
              </span>
            </div>
            <div
              style={{
                fontSize: 14,
                fontWeight: 600,
                color: "#0b1220",
                letterSpacing: "-0.01em",
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
              }}
              title={nc.company_name || "Unknown"}
            >
              {nc.company_name || (isCreate ? "Raise new NC" : "Unknown company")}
            </div>
          </div>
        </div>

        <div
          style={{
            display: "flex",
            gap: 8,
            alignItems: "center",
            flexWrap: "wrap",
          }}
        >
          <StatusPill status={nc.status} />
          <NcTypePill type={nc.nc_type} />
          {(dirtyCount > 0 || draftCount > 0) && (
            <span
              style={{
                fontSize: 11,
                color: "#92400e",
                display: "inline-flex",
                alignItems: "center",
                gap: 4,
                padding: "3px 8px",
                background: "#fef3c7",
                borderRadius: 6,
                fontWeight: 600,
              }}
            >
              <FiCircle fill="#d97706" color="#d97706" size={8} />
              {dirtyCount > 0 && `${dirtyCount} unsaved`}
              {dirtyCount > 0 && draftCount > 0 && " · "}
              {draftCount > 0 && `${draftCount} draft`}
            </span>
          )}
          <button onClick={() => router.back()} style={btnStyle("secondary")}>
            Cancel
          </button>
          <button
            onClick={handleSave}
            disabled={saving}
            style={btnStyle("primary", saving)}
          >
            <FiSave size={13} />
            {saving ? (isCreate ? "Raising…" : "Saving…") : isCreate ? "Raise NC" : "Save changes"}
          </button>
        </div>
      </div>

      {/* ════════════════════════════════════════════════════════════════
          MAIN
      ════════════════════════════════════════════════════════════════ */}
      <div
        style={{ padding: "20px 24px 90px", maxWidth: 1280, margin: "0 auto" }}
      >
        {/* ─── Compact metadata strip (always visible) ─── */}
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 16,
            padding: "11px 16px",
            background: "#fff",
            border: "1px solid #e2e8f0",
            borderRadius: 9,
            marginBottom: 12,
            fontSize: 11,
            color: "#475569",
            flexWrap: "wrap",
          }}
        >
          <MetaBit
            icon={<FiClipboard size={11} color="#94a3b8" />}
            label="Audit"
            value={nc.audit_type || "—"}
          />
          <Sep />
          <MetaBit
            icon={<FiCalendar size={11} color="#94a3b8" />}
            label="Date"
            value={formatDate(nc.audit_date)}
          />
          <Sep />
          <MetaBit
            icon={<FiUser size={11} color="#94a3b8" />}
            label="Auditor"
            value={nc.created_by_name || "—"}
          />
          <Sep />
          <MetaBit
            icon={<FiAward size={11} color="#94a3b8" />}
            label="Standards"
            value={
              (nc.standard_names || []).length
                ? nc.standard_names!.join(" · ")
                : "—"
            }
          />
          <div
            style={{
              marginLeft: "auto",
              display: "flex",
              gap: 4,
              alignItems: "center",
            }}
          >
            <span
              style={{
                fontSize: 10,
                color: "#94a3b8",
                fontFamily: "'JetBrains Mono', monospace",
              }}
            >
              {realCount} NCs · {openCount} open · {closedCount} closed ·{" "}
              {withEvidenceCount} w/ evidence
            </span>
          </div>
        </div>

        {/* ═══ AUDIT CONTEXT (at TOP, slimmed down) ═══ */}
        {showField("section.audit_context") && (
          <SectionCard
            icon={<FiInfo size={14} color="#185FA5" />}
            iconBg="#E6F1FB"
            title="Audit context"
            subtitle="Auditee, audit type, applicable standards and notes"
            open={contextOpen}
            onToggle={() => setContextOpen((v) => !v)}
          >
            <div style={{ padding: "16px 18px" }}>
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(2, 1fr)",
                  gap: 14,
                }}
              >
                {/* CREATE MODE: read-only details fetched from the audit */}
                {isCreate && (
                  <>
                    <Field label="Audit date" readOnly>
                      <ReadOnlyValue value={formatDate(nc.audit_date)} />
                    </Field>
                    <Field label="Contact person" readOnly>
                      <ReadOnlyValue
                        value={(nc as any).contact_person || "—"}
                      />
                    </Field>
                    <Field label="Mobile" readOnly>
                      <ReadOnlyValue value={(nc as any).mobile || "—"} />
                    </Field>
                    <Field label="Client email" readOnly>
                      <ReadOnlyValue value={(nc as any).client_email || "—"} />
                    </Field>
                  </>
                )}

                {showField("field.auditee_name") && (
                  <Field label="Auditee name">
                    <input
                      value={auditeeName}
                      onChange={(e) => setAuditeeName(e.target.value)}
                      style={inputStyle()}
                      placeholder="Name - Designation, Name2 - Designation"
                    />
                  </Field>
                )}
                {/* 🆕 Auditees / Attendees — drives the attendance sheet & NC report */}
                {source === "NEW" && (
                  <div style={{ gridColumn: "span 2" }}>
                    <Field label="Auditees / Attendees (attendance sheet)">
                      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                        {auditees.length === 0 && (
                          <div style={{ fontSize: 11, color: "#94a3b8" }}>
                            No auditees yet — add the people who attended the audit.
                          </div>
                        )}
                        {auditees.map((a, i) => (
                          <div key={i} style={{ display: "flex", gap: 8, alignItems: "center" }}>
                            <input
                              value={a.name}
                              placeholder="Name"
                              onChange={(e) => updateAuditee(i, "name", e.target.value)}
                              style={{ ...inputStyle(), flex: 1 }}
                            />
                            <input
                              value={a.designation}
                              placeholder="Designation"
                              onChange={(e) => updateAuditee(i, "designation", e.target.value)}
                              style={{ ...inputStyle(), flex: 1 }}
                            />
                            <button
                              type="button"
                              onClick={() => removeAuditee(i)}
                              style={{
                                border: "1px solid #fca5a5",
                                background: "#fef2f2",
                                color: "#b91c1c",
                                borderRadius: 7,
                                padding: "8px 11px",
                                cursor: "pointer",
                                height: 36,
                              }}
                              title="Remove auditee"
                            >
                              ✕
                            </button>
                          </div>
                        ))}
                        <button
                          type="button"
                          onClick={addAuditee}
                          style={{
                            alignSelf: "flex-start",
                            border: "1px dashed #93c5fd",
                            background: "#eff6ff",
                            color: "#185FA5",
                            borderRadius: 7,
                            padding: "7px 13px",
                            cursor: "pointer",
                            fontWeight: 700,
                            fontSize: 12,
                          }}
                        >
                          + Add Auditee
                        </button>
                      </div>
                    </Field>
                  </div>
                )}
                {showField("field.audit_type") && (
                  <Field label="Audit type">
                    <select
                      value={auditType}
                      onChange={(e) => setAuditType(e.target.value)}
                      style={inputStyle()}
                    >
                      <option value="initial audit">Initial Audit</option>
                      <option value="surveillance(No. 01)">
                        Surveillance (No. 01)
                      </option>
                      <option value="surveillance(No. 02)">
                        Surveillance (No. 02)
                      </option>
                      <option value="Re-Assessment">Re-Assessment</option>
                      <option value="Other">Other</option>
                    </select>
                  </Field>
                )}

                {showField("field.nc_type") && (
                  <Field label="Overall NC type">
                    <select
                      value={ncType}
                      onChange={(e) => setNcType(e.target.value)}
                      style={inputStyle()}
                    >
                      <option value="">— select —</option>
                      <option value="Major">Major</option>
                      <option value="Minor">Minor</option>
                      <option value="Observation">Observation</option>
                    </select>
                  </Field>
                )}
                {showField("field.follow_up_date") && (
                  <Field label="Follow-up date">
                    <input
                      type="date"
                      value={followUpDate}
                      onChange={(e) => setFollowUpDate(e.target.value)}
                      style={inputStyle()}
                    />
                  </Field>
                )}

                {!isCreate && showField("field.follow_up_notes") && (
                  <div style={{ gridColumn: "span 2" }}>
                    <Field label="Follow-up notes">
                      <textarea
                        value={followUpNotes}
                        onChange={(e) => setFollowUpNotes(e.target.value)}
                        placeholder="Add any follow-up information or actions taken"
                        rows={3}
                        style={{
                          ...inputStyle(),
                          height: "auto",
                          paddingTop: 9,
                          fontFamily: "inherit",
                          resize: "vertical",
                          lineHeight: 1.5,
                        }}
                      />
                    </Field>
                  </div>
                )}

                {!isCreate && showField("field.remark") && (
                  <div style={{ gridColumn: "span 2" }}>
                    <Field label="Remark (NC-level)">
                      <textarea
                        value={remark}
                        onChange={(e) => setRemark(e.target.value)}
                        placeholder="Overall remark for this NC"
                        rows={2}
                        style={{
                          ...inputStyle(),
                          height: "auto",
                          paddingTop: 9,
                          fontFamily: "inherit",
                          resize: "vertical",
                          lineHeight: 1.5,
                        }}
                      />
                    </Field>
                  </div>
                )}

                {/* ─── Standards with colored badges ─── */}
                <div
                  style={{
                    gridColumn: "span 2",
                    paddingTop: 8,
                    marginTop: 4,
                    borderTop: "1px dashed #e2e8f0",
                  }}
                >
                  <div
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 7,
                      marginBottom: 9,
                    }}
                  >
                    <FiAward size={13} color="#185FA5" />
                    <span
                      style={{
                        fontSize: 10,
                        fontWeight: 700,
                        color: "#185FA5",
                        textTransform: "uppercase",
                        letterSpacing: "0.08em",
                      }}
                    >
                      Applicable Standards
                    </span>
                    <span
                      style={{
                        fontSize: 8,
                        padding: "1px 5px",
                        background: "#f1f5f9",
                        color: "#94a3b8",
                        borderRadius: 4,
                        fontWeight: 700,
                        letterSpacing: "0.04em",
                      }}
                    >
                      AUTO
                    </span>
                  </div>
                  <div
                    style={{
                      display: "flex",
                      gap: 8,
                      flexWrap: "wrap",
                    }}
                  >
                    {(nc.standard_names || []).length === 0 ? (
                      <span style={{ fontSize: 12, color: "#94a3b8" }}>—</span>
                    ) : (
                      nc.standard_names!.map((s) => (
                        <StandardBadge key={s} standard={s} />
                      ))
                    )}
                  </div>
                </div>
              </div>
            </div>
          </SectionCard>
        )}

        {/* ═══ WORKSPACE: Sidebar + Detail ═══ */}
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "260px 1fr",
            gap: 14,
            marginBottom: 14,
          }}
        >
          {/* ── Sidebar ── */}
          <div
            style={{
              background: "#fff",
              border: "1px solid #e2e8f0",
              borderRadius: 12,
              overflow: "hidden",
              alignSelf: "flex-start",
              position: "sticky",
              top: 88,
              maxHeight: "calc(100vh - 100px)",
              display: "flex",
              flexDirection: "column",
            }}
          >
            <div
              style={{
                padding: "12px 13px 10px",
                borderBottom: "1px solid #f1f5f9",
              }}
            >
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "space-between",
                  marginBottom: 9,
                }}
              >
                <div
                  style={{
                    display: "inline-flex",
                    alignItems: "center",
                    gap: 7,
                  }}
                >
                  <FiList size={13} color="#475569" />
                  <span
                    style={{
                      fontSize: 11,
                      fontWeight: 700,
                      color: "#475569",
                      textTransform: "uppercase",
                      letterSpacing: "0.06em",
                    }}
                  >
                    NCs
                  </span>
                </div>
                <span
                  style={{
                    fontSize: 10,
                    padding: "2px 7px",
                    background: "#f1f5f9",
                    color: "#64748b",
                    borderRadius: 99,
                    fontWeight: 600,
                    fontFamily: "'JetBrains Mono', monospace",
                  }}
                >
                  {entries.length}
                </span>
              </div>
              <div style={{ position: "relative" }}>
                <FiSearch
                  size={11}
                  style={{
                    position: "absolute",
                    left: 8,
                    top: "50%",
                    transform: "translateY(-50%)",
                    color: "#94a3b8",
                  }}
                />
                <input
                  value={findingSearch}
                  onChange={(e) => setFindingSearch(e.target.value)}
                  placeholder="Filter findings…"
                  style={{
                    width: "100%",
                    padding: "6px 8px 6px 25px",
                    fontSize: 11,
                    border: "1px solid #e2e8f0",
                    borderRadius: 5,
                    background: "#fafbfc",
                    color: "#0b1220",
                    outline: "none",
                    boxSizing: "border-box",
                  }}
                />
              </div>
            </div>

            <div
              style={{
                overflowY: "auto",
                flex: 1,
                minHeight: 200,
              }}
            >
              {filteredEntries.length === 0 ? (
                <div
                  style={{
                    padding: "30px 12px",
                    textAlign: "center",
                    fontSize: 11,
                    color: "#94a3b8",
                  }}
                >
                  {findingSearch ? "No NCs match." : "No NCs yet."}
                </div>
              ) : (
                filteredEntries.map((e) => (
                  <FindingListItem
                    key={e.id}
                    entry={e}
                    index={entries.filter((x) => !isDraft(x)).indexOf(e) + 1}
                    selected={selectedEntryId === e.id}
                    onSelect={() => setSelectedEntryId(e.id)}
                  />
                ))
              )}
            </div>

            {/* "+ Add finding" button — now a WORKING TOGGLE */}
            <button
              onClick={() => setShowAddPanel((v) => !v)}
              style={{
                padding: "10px 13px",
                background: showAddPanel ? "#185FA5" : "#fafbfc",
                border: "none",
                borderTop: "1px solid #e2e8f0",
                color: showAddPanel ? "#fff" : "#185FA5",
                fontSize: 11,
                fontWeight: 700,
                cursor: "pointer",
                display: "inline-flex",
                alignItems: "center",
                justifyContent: "center",
                gap: 5,
                textAlign: "center",
                transition: "all 0.15s",
                letterSpacing: "0.02em",
              }}
            >
              {showAddPanel ? (
                <>
                  <FiChevronDown size={13} /> Close form
                </>
              ) : (
                <>
                  <FiPlus size={13} /> Add more NC items
                </>
              )}
            </button>
          </div>

          {/* ── Detail panel ── */}
          <div>
            {/* Show the add-form OR the detail panel */}
            {showAddPanel ? (
              <AddFindingPanel
                onAdd={handleAddDraft}
                onCancel={() => setShowAddPanel(false)}
              />
            ) : selected ? (
              <FindingDetail
                entry={selected}
                index={entries.filter((e) => !isDraft(e)).indexOf(selected) + 1}
                source={source}
                ncId={id}
                hasPrev={selectedIdx > 0}
                hasNext={selectedIdx < entries.length - 1}
                onPrev={goPrev}
                onNext={goNext}
                onChange={(patch) => updateEntry(selected.id, patch)}
                onFileChanged={(p) => refreshEntryFile(selected.id, p)}
                onDelete={() => handleDeleteEntry(selected.id)}
                onAddNew={() => setShowAddPanel(true)}
              />
            ) : (
              <div
                style={{
                  background: "#fff",
                  border: "1px dashed #e2e8f0",
                  borderRadius: 12,
                  padding: "60px 20px",
                  textAlign: "center",
                  color: "#94a3b8",
                  fontSize: 13,
                }}
              >
                {entries.length === 0
                  ? 'No NCs on this record. Click "Add more NC items" to add one.'
                  : "Select an NC from the left to view details."}
              </div>
            )}
          </div>
        </div>

        {/* ═══ NC CLOSURE & TRACKING (new — before email) ═══ */}
        {!isCreate && showField("section.closure_tracking") && (
          <SectionCard
            icon={<FiUserCheck size={14} color="#0F6E56" />}
            iconBg="#E1F5EE"
            title="NC closure & tracking"
            subtitle="Assignment, due dates, closure status — most fields auto-set on close"
            open={closureOpen}
            onToggle={() => setClosureOpen((v) => !v)}
          >
            <div style={{ padding: "16px 18px" }}>
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(2, 1fr)",
                  gap: 14,
                }}
              >
                <Field label="Created by" readOnly>
                  <ReadOnlyValue value={nc.created_by_name || "—"} />
                </Field>
                <Field label="Overall status">
                  <div style={{ display: "flex", gap: 6 }}>
                    <button
                      onClick={() => setStatus("open")}
                      style={statusBtn(
                        status === "open",
                        "#A32D2D",
                        "#FCEBEB",
                        "#dc2626",
                      )}
                    >
                      {status === "open" && (
                        <span
                          style={{
                            width: 6,
                            height: 6,
                            background: "#dc2626",
                            borderRadius: 50,
                          }}
                        />
                      )}
                      Open
                    </button>
                    <button
                      onClick={() => setStatus("closed")}
                      style={statusBtn(
                        status === "closed",
                        "#0F6E56",
                        "#E1F5EE",
                        "#16a34a",
                      )}
                    >
                      {status === "closed" && (
                        <span
                          style={{
                            width: 6,
                            height: 6,
                            background: "#16a34a",
                            borderRadius: 50,
                          }}
                        />
                      )}
                      Closed
                    </button>
                  </div>
                </Field>

                <Field label="Audit date" readOnly>
                  <ReadOnlyValue value={formatDate(nc.audit_date)} />
                </Field>
                <Field label="Due date">
                  <input
                    type="date"
                    value={dueDate}
                    onChange={(e) => setDueDate(e.target.value)}
                    style={inputStyle()}
                  />
                </Field>

                <Field label="NC closed by" readOnly>
                  <ReadOnlyValue value={nc.assigned_to_name || "—"} />
                </Field>
                <Field label="NC closed date" readOnly>
                  <ReadOnlyValue value={formatDate(nc.closed_at)} />
                </Field>
              </div>
            </div>
          </SectionCard>
        )}

        {/* ═══ EMAIL NOTIFICATIONS (before Remarks) ═══ */}
        {showField("section.email") && (
          <EmailNotificationsPanel
            value={emailPrefs}
            onChange={(patch) => setEmailPrefs((p) => ({ ...p, ...patch }))}
            onSend={isCreate ? undefined : handleSendEmail}
            sending={sendingEmail}
          />
        )}

        {/* ═══ CREATE MODE: Follow-up notes + Remark (below email) ═══ */}
        {isCreate && (
          <SectionCard
            icon={<FiFileText size={14} color="#475569" />}
            iconBg="#f1f5f9"
            title="Follow-up & remarks"
            subtitle="Optional notes for this NC — saved when you raise it"
            open={followupOpen}
            onToggle={() => setFollowupOpen((v) => !v)}
          >
            <div
              style={{
                padding: "16px 18px",
                display: "grid",
                gridTemplateColumns: "1fr",
                gap: 14,
              }}
            >
              <Field label="Follow-up notes">
                <textarea
                  value={followUpNotes}
                  onChange={(e) => setFollowUpNotes(e.target.value)}
                  placeholder="Add any follow-up information or actions taken"
                  rows={3}
                  style={{
                    ...inputStyle(),
                    height: "auto",
                    paddingTop: 9,
                    fontFamily: "inherit",
                    resize: "vertical",
                    lineHeight: 1.5,
                  }}
                />
              </Field>
              <Field label="Remark (NC-level)">
                <textarea
                  value={remark}
                  onChange={(e) => setRemark(e.target.value)}
                  placeholder="Overall remark for this NC"
                  rows={2}
                  style={{
                    ...inputStyle(),
                    height: "auto",
                    paddingTop: 9,
                    fontFamily: "inherit",
                    resize: "vertical",
                    lineHeight: 1.5,
                  }}
                />
              </Field>
            </div>
          </SectionCard>
        )}

        {/* ═══ INTERNAL REMARKS ═══ */}
        {!isCreate && showField("section.remarks") && (
          <SectionCard
            icon={<FiFileText size={14} color="#475569" />}
            iconBg="#f1f5f9"
            title={`Internal remarks · ${remarks.length}`}
            subtitle="Notes shared between coordinators and auditors"
            open={remarksOpen}
            onToggle={() => setRemarksOpen((v) => !v)}
          >
            <div style={{ padding: "14px 18px" }}>
              {remarks.length === 0 ? (
                <div style={{ fontSize: 12, color: "#94a3b8", marginBottom: 12 }}>
                  No remarks logged yet.
                </div>
              ) : (
                <div
                  style={{
                    display: "flex",
                    flexDirection: "column",
                    gap: 8,
                    marginBottom: 14,
                  }}
                >
                  {remarks.map((r) => (
                    <div
                      key={r.id}
                      style={{
                        background: "#fafbfc",
                        border: "1px solid #e2e8f0",
                        borderLeft: "3px solid #185FA5",
                        borderRadius: 6,
                        padding: "10px 14px",
                      }}
                    >
                      <div
                        style={{
                          fontSize: 12,
                          color: "#1f2937",
                          lineHeight: 1.5,
                        }}
                      >
                        {r.remark}
                      </div>
                      <div
                        style={{
                          fontSize: 10,
                          color: "#94a3b8",
                          marginTop: 6,
                          fontFamily: "'JetBrains Mono', monospace",
                        }}
                      >
                        User #{r.user_id} · {formatDate(r.created_at)}
                      </div>
                    </div>
                  ))}
                </div>
              )}
              <Field label="Add new remark">
                <textarea
                  value={newRemark}
                  onChange={(e) => setNewRemark(e.target.value)}
                  placeholder="Type a new internal remark — added when you click Save…"
                  rows={3}
                  style={{
                    ...inputStyle(),
                    height: "auto",
                    paddingTop: 9,
                    fontFamily: "inherit",
                    resize: "vertical",
                    lineHeight: 1.5,
                  }}
                />
              </Field>
              {newRemark.trim() && (
                <div
                  style={{
                    marginTop: 8,
                    padding: "8px 12px",
                    background: "#f0fdf4",
                    border: "1px solid #86efac",
                    borderRadius: 6,
                    fontSize: 12,
                    color: "#166534",
                    display: "flex",
                    alignItems: "center",
                    gap: 6,
                  }}
                >
                  <FiPlus size={12} />
                  This remark will be added when you click Save.
                </div>
              )}
            </div>
          </SectionCard>
        )}

        {/* ═══ 🆕 PHASE 2A — FINAL CLOSURE & VERIFICATION ═══ */}
        {/*    (replaces the previous Phase 2 placeholder) */}
        {!isCreate && showField("section.final_closure") && (
          <ClosurePanel
            source={source}
            ncId={id}
            entries={entries}
            onFinalized={() => {
              // After finalize, refresh the page data so updated finding statuses appear
              fetchData();
            }}
          />
        )}
      </div>

      {/* ════════════════════════════════════════════════════════════════
          STICKY FOOTER
      ════════════════════════════════════════════════════════════════ */}
      <div
        style={{
          position: "sticky",
          bottom: 0,
          background: "#fff",
          borderTop: "1px solid #e2e8f0",
          padding: "12px 24px",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          flexWrap: "wrap",
          gap: 10,
          boxShadow: "0 -4px 12px rgba(15,23,42,0.04)",
          zIndex: 40,
        }}
      >
        <div
          style={{
            fontSize: 12,
            color: "#64748b",
            display: "flex",
            alignItems: "center",
            gap: 6,
          }}
        >
          {dirtyCount > 0 || draftCount > 0 ? (
            <>
              <FiCircle fill="#d97706" color="#d97706" size={10} />
              <span style={{ color: "#d97706", fontWeight: 600 }}>
                {dirtyCount > 0 && `${dirtyCount} modified`}
                {dirtyCount > 0 && draftCount > 0 && " · "}
                {draftCount > 0 && `${draftCount} draft`}
              </span>
              {newRemark.trim() ? " · 1 new remark" : ""}
            </>
          ) : newRemark.trim() ? (
            <>
              <FiCheck color="#16a34a" size={12} />1 new remark ready
            </>
          ) : (
            <>
              <FiCheck color="#94a3b8" size={12} />
              No pending changes
            </>
          )}
          <span
            style={{
              marginLeft: 14,
              fontSize: 10,
              color: "#94a3b8",
              fontFamily: "'JetBrains Mono', monospace",
            }}
          >
            ↑ / ↓ to switch findings
          </span>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button onClick={() => router.back()} style={btnStyle("secondary")}>
            Discard
          </button>
          <button
            onClick={handleSave}
            disabled={saving}
            style={btnStyle("primary", saving)}
          >
            <FiSave size={13} />
            {saving ? (isCreate ? "Raising…" : "Saving…") : isCreate ? "Raise NC" : "Save all"}
          </button>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// Helpers
// ═══════════════════════════════════════════════════════════════════════

function StatusPill({ status }: { status: string }) {
  const isOpen = status === "open";
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 5,
        padding: "3px 9px",
        background: isOpen ? "#FCEBEB" : "#E1F5EE",
        borderRadius: 6,
        fontSize: 10,
        fontWeight: 700,
        color: isOpen ? "#A32D2D" : "#0F6E56",
        letterSpacing: "0.06em",
      }}
    >
      <span
        style={{
          width: 6,
          height: 6,
          background: isOpen ? "#dc2626" : "#16a34a",
          borderRadius: 50,
        }}
      />
      {(status || "open").toUpperCase()}
    </span>
  );
}

function NcTypePill({ type }: { type?: string }) {
  const t = (type || "").toLowerCase();
  let label = type || "";
  let color = "#475569";
  let bg = "#f1f5f9";
  if (t.includes("major")) {
    label = "MAJOR";
    color = "#A32D2D";
    bg = "#FCEBEB";
  } else if (t.includes("minor")) {
    label = "MINOR";
    color = "#854F0B";
    bg = "#FAEEDA";
  } else if (t.includes("observ")) {
    label = "OBSERVATION";
    color = "#0C447C";
    bg = "#E6F1FB";
  }
  if (!label) return null;
  return (
    <span
      style={{
        fontSize: 10,
        padding: "3px 9px",
        background: bg,
        color,
        borderRadius: 6,
        fontWeight: 700,
        letterSpacing: "0.06em",
      }}
    >
      {label}
    </span>
  );
}

function MetaBit({
  icon,
  label,
  value,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
}) {
  return (
    <div
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 5,
        minWidth: 0,
      }}
    >
      {icon}
      <span
        style={{
          color: "#94a3b8",
          fontSize: 10,
          fontWeight: 600,
          letterSpacing: "0.04em",
          textTransform: "uppercase",
        }}
      >
        {label}
      </span>
      <span
        style={{
          color: "#0b1220",
          fontWeight: 600,
          overflow: "hidden",
          textOverflow: "ellipsis",
          whiteSpace: "nowrap",
          maxWidth: 260,
        }}
        title={value}
      >
        {value}
      </span>
    </div>
  );
}

function Sep() {
  return (
    <span
      style={{
        width: 3,
        height: 3,
        background: "#cbd5e1",
        borderRadius: 50,
        flexShrink: 0,
      }}
    />
  );
}

function SectionCard({
  icon,
  iconBg = "#f1f5f9",
  title,
  subtitle,
  open,
  onToggle,
  children,
}: {
  icon: React.ReactNode;
  iconBg?: string;
  title: string;
  subtitle?: string;
  open: boolean;
  onToggle: () => void;
  children: React.ReactNode;
}) {
  return (
    <div
      style={{
        background: "#fff",
        border: "1px solid #e2e8f0",
        borderRadius: 12,
        marginBottom: 12,
        overflow: "hidden",
      }}
    >
      <button
        onClick={onToggle}
        style={{
          width: "100%",
          padding: "13px 18px",
          background: "transparent",
          border: "none",
          borderBottom: open ? "1px solid #e2e8f0" : "none",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          cursor: "pointer",
          textAlign: "left",
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
          <div
            style={{
              width: 28,
              height: 28,
              background: iconBg,
              borderRadius: 7,
              display: "inline-flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            {icon}
          </div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 600, color: "#0b1220" }}>
              {title}
            </div>
            {subtitle && (
              <div style={{ fontSize: 10, color: "#94a3b8", marginTop: 1 }}>
                {subtitle}
              </div>
            )}
          </div>
        </div>
        {open ? (
          <FiChevronDown size={14} color="#94a3b8" />
        ) : (
          <FiChevronRight size={14} color="#94a3b8" />
        )}
      </button>
      {open && children}
    </div>
  );
}

function Field({
  label,
  readOnly,
  children,
}: {
  label: string;
  readOnly?: boolean;
  children: React.ReactNode;
}) {
  return (
    <div>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 6,
          marginBottom: 5,
        }}
      >
        <div
          style={{
            fontSize: 10,
            fontWeight: 700,
            color: "#64748b",
            textTransform: "uppercase",
            letterSpacing: "0.08em",
          }}
        >
          {label}
        </div>
        {readOnly && (
          <span
            style={{
              fontSize: 8,
              padding: "1px 5px",
              background: "#f1f5f9",
              color: "#94a3b8",
              borderRadius: 4,
              fontWeight: 700,
              letterSpacing: "0.04em",
            }}
          >
            AUTO
          </span>
        )}
      </div>
      {children}
    </div>
  );
}

function ReadOnlyValue({ value }: { value: string }) {
  return (
    <div
      style={{
        width: "100%",
        background: "#fafbfc",
        border: "1px solid #f1f5f9",
        borderRadius: 7,
        padding: "8px 11px",
        fontSize: 13,
        fontWeight: 500,
        color: "#475569",
        height: 36,
        display: "flex",
        alignItems: "center",
        boxSizing: "border-box",
      }}
    >
      {value}
    </div>
  );
}

function inputStyle(): React.CSSProperties {
  return {
    width: "100%",
    background: "#fff",
    border: "1px solid #e2e8f0",
    borderRadius: 7,
    padding: "8px 11px",
    fontSize: 13,
    fontWeight: 500,
    color: "#0b1220",
    height: 36,
    outline: "none",
    transition: "border-color 0.12s",
    fontFamily: "inherit",
    boxSizing: "border-box",
  };
}

function btnStyle(
  variant: "primary" | "secondary",
  disabled = false,
): React.CSSProperties {
  if (variant === "primary") {
    return {
      background: "#0b1220",
      color: "#fff",
      border: "none",
      padding: "7px 14px",
      borderRadius: 7,
      fontSize: 11,
      fontWeight: 600,
      cursor: disabled ? "wait" : "pointer",
      display: "inline-flex",
      alignItems: "center",
      gap: 5,
      opacity: disabled ? 0.7 : 1,
      letterSpacing: "0.01em",
    };
  }
  return {
    background: "#fff",
    color: "#475569",
    border: "1px solid #e2e8f0",
    padding: "7px 12px",
    borderRadius: 7,
    fontSize: 11,
    fontWeight: 500,
    cursor: "pointer",
    display: "inline-flex",
    alignItems: "center",
    gap: 5,
    letterSpacing: "0.01em",
  };
}

function formatDate(d?: string | Date | null): string {
  if (!d) return "—";
  const dt = typeof d === "string" ? new Date(d) : d;
  if (isNaN(dt.getTime())) return "—";
  return dt.toLocaleDateString("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
}

// Convert ISO/date string to YYYY-MM-DD for <input type="date">
function toDateInput(d?: string | Date | null): string {
  if (!d) return "";
  const dt = typeof d === "string" ? new Date(d) : d;
  if (isNaN(dt.getTime())) return "";
  const y = dt.getFullYear();
  const m = String(dt.getMonth() + 1).padStart(2, "0");
  const day = String(dt.getDate()).padStart(2, "0");
  return `${y}-${m}-${day}`;
}

// ═══════════════════════════════════════════════════════════════════════
// StandardBadge — colored badge per ISO standard family
// ═══════════════════════════════════════════════════════════════════════

const STANDARD_COLORS: Record<
  string,
  { bg: string; color: string; border: string; label: string }
> = {
  "9001": {
    bg: "#E6F1FB",
    color: "#0C447C",
    border: "#85B7EB",
    label: "Quality Mgmt",
  },
  "14001": {
    bg: "#E1F5EE",
    color: "#0F6E56",
    border: "#5DCAA5",
    label: "Environment",
  },
  "45001": {
    bg: "#FAEEDA",
    color: "#854F0B",
    border: "#EF9F27",
    label: "Occupational H&S",
  },
  "22000": {
    bg: "#E1F5EE",
    color: "#0F6E56",
    border: "#5DCAA5",
    label: "Food Safety",
  },
  "27001": {
    bg: "#EEEDFE",
    color: "#3C3489",
    border: "#AFA9EC",
    label: "Info Security",
  },
  "13485": {
    bg: "#FBEAF0",
    color: "#72243E",
    border: "#ED93B1",
    label: "Medical Devices",
  },
  "17025": {
    bg: "#EEEDFE",
    color: "#3C3489",
    border: "#AFA9EC",
    label: "Lab Calibration",
  },
  "50001": {
    bg: "#FAEEDA",
    color: "#854F0B",
    border: "#EF9F27",
    label: "Energy Mgmt",
  },
  "37001": {
    bg: "#F1EFE8",
    color: "#444441",
    border: "#B4B2A9",
    label: "Anti-Bribery",
  },
  "20000": {
    bg: "#E6F1FB",
    color: "#0C447C",
    border: "#85B7EB",
    label: "IT Service Mgmt",
  },
  "21001": {
    bg: "#FAECE7",
    color: "#993C1D",
    border: "#F0997B",
    label: "Education",
  },
  "28000": {
    bg: "#FCEBEB",
    color: "#A32D2D",
    border: "#F09595",
    label: "Supply Chain Security",
  },
  "55001": {
    bg: "#F1EFE8",
    color: "#444441",
    border: "#B4B2A9",
    label: "Asset Mgmt",
  },
};

function StandardBadge({ standard }: { standard: string }) {
  // Extract the ISO number (e.g. "9001:2015" → "9001" or "ISO 9001" → "9001")
  const match = standard.match(/(\d{4,5})/);
  const num = match ? match[1] : null;
  const c =
    num && STANDARD_COLORS[num]
      ? STANDARD_COLORS[num]
      : {
        bg: "#f1f5f9",
        color: "#475569",
        border: "#cbd5e1",
        label: "Standard",
      };

  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 8,
        padding: "6px 12px",
        background: c.bg,
        color: c.color,
        borderRadius: 7,
        border: `1px solid ${c.border}`,
        fontSize: 11,
        fontWeight: 600,
        lineHeight: 1.2,
      }}
    >
      <span
        style={{
          width: 6,
          height: 6,
          background: c.color,
          borderRadius: 50,
          flexShrink: 0,
        }}
      />
      <span
        style={{
          fontFamily: "'JetBrains Mono', monospace",
          fontWeight: 700,
          letterSpacing: "0.02em",
        }}
      >
        ISO {standard}
      </span>
      <span
        style={{
          width: 1,
          height: 11,
          background: c.color,
          opacity: 0.25,
        }}
      />
      <span
        style={{
          fontSize: 10,
          opacity: 0.85,
          fontWeight: 500,
        }}
      >
        {c.label}
      </span>
    </span>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// statusBtn — segmented Status button (Open / Closed)
// ═══════════════════════════════════════════════════════════════════════

function statusBtn(
  active: boolean,
  color: string,
  bg: string,
  dot: string,
): React.CSSProperties {
  return {
    flex: 1,
    padding: "7px 10px",
    fontSize: 11,
    background: active ? bg : "#fff",
    color: active ? color : "#475569",
    border: `1px solid ${active ? color : "#e2e8f0"}`,
    borderRadius: 6,
    fontWeight: active ? 700 : 500,
    cursor: "pointer",
    transition: "all 0.12s",
    boxShadow: active ? `0 0 0 2px ${color}15` : "none",
    display: "inline-flex",
    alignItems: "center",
    justifyContent: "center",
    gap: 5,
    height: 36,
    boxSizing: "border-box",
  };
}