"use client";

import React, { useState, useRef, useEffect } from "react";
import toast from "react-hot-toast";
import styles from "../../modules/commonstyle/dattabale.module.css";
import {
  FiEye,
  FiEdit,
  FiTrash2,
  FiPrinter,
  FiSend,
  FiXCircle,
  FiChevronRight,
  FiChevronDown,
  FiRefreshCw,
} from "react-icons/fi";
import { ScheduleStatusBadge, RowStatusBadge } from "./components/AuditBadges";
import { formatDate } from "@/lib/api/mappers/audit-schedule.mappers";
import { ROW_STATUS_META } from "@/lib/api/mappers/audit-schedule.mappers";
import { updateAuditRow, deleteAuditRow } from "@/lib/api/audit-schedule.api";
import AuditRowEditModal from "./Modals/AuditRowEditModal";
import type {
  AuditScheduleRow as AuditScheduleRowType,
  AuditSchedule,
  AuditRow,
  RowStatus,
} from "@/lib/api/types/audit-schedule.types";

interface Props {
  row: AuditScheduleRowType;
  isSelected: boolean;
  handleRowSelect: (sno: number, checked: boolean) => void;
  onEdit: (row: AuditScheduleRowType) => void;
  onDelete: (row: AuditScheduleRowType) => void;
  onView: (row: AuditScheduleRowType) => void;
  onPublish: (row: AuditScheduleRowType) => void;
  onBulkCancel: (row: AuditScheduleRowType) => void;
  onPrint: (row: AuditScheduleRowType) => void;
  canDelete: boolean;

  isExpanded: boolean;
  expandedSchedule: AuditSchedule | null;
  expandedLoading: boolean;
  onToggleExpand: (row: AuditScheduleRowType) => void;
  onCancelAuditRow: (schedule: AuditSchedule, auditRow: AuditRow) => void;
  onRescheduleAuditRow: (schedule: AuditSchedule, auditRow: AuditRow) => void;

  permittedActions: Set<string>;
}

export function AuditScheduleRow({
  row,
  isSelected,
  handleRowSelect,
  onEdit,
  onDelete,
  onView,
  onPublish,
  onBulkCancel,
  onPrint,
  canDelete,
  isExpanded,
  expandedSchedule,
  expandedLoading,
  onToggleExpand,
  onCancelAuditRow,
  onRescheduleAuditRow,
  permittedActions,
}: Props) {
  const isDraft = row.status === "DRAFT";
  const isPublished = row.status === "PUBLISHED";
  const isCancelled = row.status === "CANCELLED";
  const isCompleted = row.status === "COMPLETED";

  const canEdit = permittedActions.has("edit");
  const canPublish = permittedActions.has("publish");
  const canBulkCancel = permittedActions.has("bulk-cancel");
  const canDeleteAction = permittedActions.has("delete");
  const canCancelRow = permittedActions.has("cancel");
  const canRescheduleRow = permittedActions.has("reschedule");

  const showDelete = canDeleteAction && !isCompleted;

  // ✅ NEW — inline status dropdown + edit modal state
  const [statusMenuOpenFor, setStatusMenuOpenFor] = useState<number | null>(
    null,
  );
  const [savingStatusFor, setSavingStatusFor] = useState<number | null>(null);
  const [editTarget, setEditTarget] = useState<AuditRow | null>(null);
  const [deletingRowId, setDeletingRowId] = useState<number | null>(null);
  const [menuPos, setMenuPos] = useState<{ top: number; left: number } | null>(
    null,
  );

  // Inline status save — used by the dropdown in the accordion
  const handleInlineStatusChange = async (
    auditRow: AuditRow,
    newStatus: RowStatus,
  ) => {
    if (!expandedSchedule) return;
    if (auditRow.status === newStatus) {
      setStatusMenuOpenFor(null);
      return;
    }
    setSavingStatusFor(auditRow.id);
    setStatusMenuOpenFor(null);
    try {
      await updateAuditRow(expandedSchedule.id, auditRow.id, {
        status: newStatus,
      } as any);
      toast.success(
        `Status updated to ${ROW_STATUS_META[newStatus]?.label ?? newStatus}`,
      );
      // Refresh accordion by toggling closed then open (re-fetches the rows)
      onToggleExpand(row);
      setTimeout(() => onToggleExpand(row), 50);
    } catch (err: any) {
      toast.error(err?.message || "Failed to update status");
    } finally {
      setSavingStatusFor(null);
    }
  };

  // 🆕 Delete a single audit row (permanent — different from Cancel, which
  // keeps the row and its audit_code so it can be rescheduled later).
  const handleDeleteAuditRow = async (auditRow: AuditRow) => {
    if (!expandedSchedule) return;
    const ok = window.confirm(
      `Permanently delete audit ${auditRow.audit_code}? This cannot be undone — use Cancel instead if you may need to reschedule it.`,
    );
    if (!ok) return;
    setDeletingRowId(auditRow.id);
    try {
      await deleteAuditRow(expandedSchedule.id, auditRow.id);
      toast.success(`Audit ${auditRow.audit_code} deleted.`);
      onToggleExpand(row);
      setTimeout(() => onToggleExpand(row), 50);
    } catch (err: any) {
      toast.error(err?.message || "Failed to delete audit row");
    } finally {
      setDeletingRowId(null);
    }
  };

  // Visual hint for date proximity
  // 🛠 FIX: `new Date(row.schedule_date)` parses a date-only "YYYY-MM-DD"
  // string as UTC midnight, then gets compared against `today` (local
  // midnight) — off by a day for anyone west of UTC. Parse schedule_date
  // from its Y/M/D components into a LOCAL date instead, so "Today" /
  // "Tomorrow" always matches the viewer's actual calendar day.
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const [sdY, sdM, sdD] = row.schedule_date.split("-").map(Number);
  const sd = new Date(sdY, (sdM || 1) - 1, sdD || 1);
  const dayDiff = Math.round((sd.getTime() - today.getTime()) / 86_400_000);
  const dateHint =
    dayDiff === 0
      ? "🔥 Today"
      : dayDiff === 1
        ? "📍 Tomorrow"
        : dayDiff > 0 && dayDiff <= 7
          ? `🗓️ in ${dayDiff}d`
          : dayDiff < 0
            ? `🕰️ ${Math.abs(dayDiff)}d ago`
            : "";

  return (
    <>
      <tr
        className={`${styles.tableRow} ${isSelected ? styles.selectedRow : ""}`}
      >
        <td style={{ textAlign: "center", padding: "10px 8px" }}>
          <input
            type="checkbox"
            className={styles.checkbox}
            checked={isSelected}
            onChange={(e) => handleRowSelect(row.sno, e.target.checked)}
          />
        </td>

        <td className={styles.nameCell}>
          <div style={{ fontWeight: 700, fontSize: 13, color: "#0f172a" }}>
            {formatDate(row.schedule_date)}
          </div>
          {dateHint && (
            <div style={{ fontSize: 11, color: "#9ca3af", marginTop: 2 }}>
              {dateHint}
            </div>
          )}
        </td>

        <td className={styles.nameCell}>
          <div style={{ fontWeight: 600, fontSize: 13 }}>{row.title}</div>
        </td>

        <td className={styles.nameCell}>
          <span
            style={{
              padding: "3px 8px",
              borderRadius: 12,
              fontSize: 11,
              fontWeight: 700,
              color: row.client_group === "QRS" ? "#6d28d9" : "#1e40af",
              backgroundColor:
                row.client_group === "QRS" ? "#ede9fe" : "#dbeafe",
            }}
          >
            {row.client_group}
          </span>
        </td>

        <td className={styles.nameCell}>
          <button
            onClick={() => onToggleExpand(row)}
            style={{
              padding: "4px 10px",
              borderRadius: 12,
              border: "1px solid #14b8a6",
              background: isExpanded ? "#14b8a6" : "#f0fdfa",
              color: isExpanded ? "#ffffff" : "#0f766e",
              fontSize: 12,
              fontWeight: 700,
              cursor: "pointer",
              display: "inline-flex",
              alignItems: "center",
              gap: 4,
            }}
            title={
              isExpanded
                ? "Collapse audit rows"
                : "Click to expand the audit rows for this schedule"
            }
          >
            {isExpanded ? (
              <FiChevronDown size={12} />
            ) : (
              <FiChevronRight size={12} />
            )}
            <strong style={{ fontFamily: "'IBM Plex Mono', monospace" }}>
              {row.row_count}
            </strong>{" "}
            audit{row.row_count !== 1 ? "s" : ""}
          </button>
        </td>

        <td className={styles.nameCell}>
          <div style={{ fontWeight: 500, fontSize: 13 }}>
            {row.coordinator_name}
          </div>
          <div style={{ fontSize: 11, color: "#9ca3af" }}>
            {row.coordinator_email}
          </div>
        </td>

        <td className={styles.nameCell}>
          <ScheduleStatusBadge status={row.status} />
        </td>

        <td className={styles.actionsCell}>
          <div className={styles.actionGroup}>
            <button
              className={styles.actionBtnView}
              onClick={() => onView(row)}
              title="View schedule details (print/email format)"
            >
              <FiEye size={14} />
            </button>

            {canPublish && isDraft && (
              <button
                className={styles.actionBtnView}
                onClick={() => onPublish(row)}
                title="Publish Schedule (sends notifications)"
                style={{
                  background: "#dcfce7",
                  borderColor: "#86efac",
                  color: "#166534",
                }}
              >
                <FiSend size={14} />
              </button>
            )}

            {!isDraft && (
              <button
                className={styles.actionBtnView}
                onClick={() => onPrint(row)}
                title="Print day schedule"
                style={{
                  background: "#eff6ff",
                  borderColor: "#93c5fd",
                  color: "#1e40af",
                }}
              >
                <FiPrinter size={14} />
              </button>
            )}

            {canBulkCancel && isPublished && (
              <button
                className={styles.actionBtnView}
                onClick={() => onBulkCancel(row)}
                title="Cancel ALL audits in this schedule"
                style={{
                  background: "#fef2f2",
                  borderColor: "#fca5a5",
                  color: "#b91c1c",
                }}
              >
                <FiXCircle size={14} />
              </button>
            )}

            {canEdit && !isCancelled && !isCompleted && (
              <button
                className={styles.actionBtnEdit}
                onClick={() => onEdit(row)}
                title="Edit schedule"
              >
                <FiEdit size={14} />
              </button>
            )}

            {showDelete && (
              <button
                className={styles.actionBtnDelete}
                onClick={() => onDelete(row)}
                title={
                  isDraft
                    ? "Delete this draft schedule"
                    : "Delete this schedule (also deletes its audit rows)"
                }
              >
                <FiTrash2 size={14} />
              </button>
            )}
          </div>
        </td>
      </tr>

      {isExpanded && (
        <tr>
          <td colSpan={8} style={{ padding: 0, background: "#f8fafc" }}>
           <div style={{ padding: "2px 4px" }}>
              {expandedLoading ? (
                <div
                  style={{
                    padding: "24px",
                    textAlign: "center",
                    color: "#9ca3af",
                    fontSize: 13,
                  }}
                >
                  <div
                    style={{
                      display: "inline-block",
                      width: 22,
                      height: 22,
                      border: "3px solid #e5e7eb",
                      borderTopColor: "#14b8a6",
                      borderRadius: "50%",
                      animation: "spin 0.7s linear infinite",
                      marginRight: 8,
                      verticalAlign: "middle",
                    }}
                  />
                  Loading audit rows...
                </div>
              ) : !expandedSchedule ? (
                <div
                  style={{
                    padding: "20px",
                    textAlign: "center",
                    color: "#9ca3af",
                    fontSize: 13,
                  }}
                >
                  Could not load audit rows.
                </div>
              ) : (expandedSchedule.rows ?? []).length === 0 ? (
                <div
                  style={{
                    padding: "20px",
                    textAlign: "center",
                    color: "#9ca3af",
                    fontSize: 13,
                  }}
                >
                  No audit rows in this schedule yet. Use Edit to add audits.
                </div>
              ) : (
                <div style={{ overflowX: "auto" }}>
                  <table
                    style={{
                      width: "100%",
                      borderCollapse: "collapse",
                      fontSize: 12,
                      background: "#fff",
                      border: "1px solid #e2e8f0",
                      borderRadius: 8,
                      overflow: "hidden",
                    }}
                  >
                    <thead>
                      <tr style={{ background: "#f1f5f9" }}>
                        <th style={subThStyle}>S#</th>
                        <th style={subThStyle}>Audit Code</th>
                        <th style={subThStyle}>Category</th>
                        <th style={subThStyle}>Company</th>
                        <th style={subThStyle}>Standards</th>
                        <th style={subThStyle}>Coordinator</th>
                        <th style={subThStyle}>Lead Auditor</th>
                        <th style={subThStyle}>Co-Auditor(s)</th>
                        <th style={subThStyle}>Time</th>
                        <th style={subThStyle}>Status</th>
                        {(canEdit || canDeleteAction || canCancelRow || canRescheduleRow) && (
                          <th style={subThStyle}>Actions</th>
                        )}
                      </tr>
                    </thead>
                    <tbody>
                      {(expandedSchedule.rows ?? []).map((auditRow, i) => {
                        const rowCancelled = auditRow.status === "CANCELLED";
                        const rowCompleted = auditRow.status === "COMPLETED";
                        const rowClosed = rowCancelled || rowCompleted;

                        return (
                          <tr
                            key={auditRow.id}
                            style={{
                              background: rowCancelled ? "#fef2f2" : "#fff",
                              borderTop: "1px solid #e2e8f0",
                            }}
                          >
                            <td style={subTdStyle}>
                              {auditRow.row_no || i + 1}
                            </td>
                            <td
                              style={{
                                ...subTdStyle,
                                fontFamily: "'IBM Plex Mono', monospace",
                                fontSize: 11,
                                fontWeight: 600,
                              }}
                            >
                              <a
                                href={`/modules/previous-nc/raise?audit_id=${auditRow.id}`}
                              >
                                {auditRow.audit_code}
                              </a>
                            </td>
                            <td style={subTdStyle}>{auditRow.audit_type}</td>
                            <td style={{ ...subTdStyle, fontWeight: 500 }}>
                              {auditRow.company?.name ?? "—"}
                            </td>
                            <td style={subTdStyle}>
                              <StandardsBadges
                                standards={auditRow.standards ?? []}
                              />
                            </td>
                            <td style={subTdStyle}>
                              {expandedSchedule?.coordinator
                                ? `${expandedSchedule.coordinator.firstName ?? ""} ${expandedSchedule.coordinator.lastName ?? ""}`
                                    .trim()
                                    .toUpperCase() || "—"
                                : "—"}
                            </td>
                            <td style={subTdStyle}>
                              {auditRow.lead_auditor
                                ? `${auditRow.lead_auditor.firstName ?? ""} ${auditRow.lead_auditor.lastName ?? ""}`
                                    .trim()
                                    .toUpperCase() || "—"
                                : "—"}
                            </td>
                            <td style={subTdStyle}>
                              <CoAuditorChips
                                coAuditors={auditRow.co_auditors ?? []}
                              />
                            </td>
                            <td style={subTdStyle}>
                              {auditRow.audit_time_label ??
                                auditRow.audit_time ??
                                "—"}
                            </td>

                            {/* ✅ Inline status dropdown */}
                            <td style={subTdStyle}>
                              {canEdit && !rowCompleted ? (
                                <div
                                  style={{
                                    position: "relative",
                                    display: "inline-block",
                                  }}
                                >
                                  <button
                                    type="button"
                                    onClick={(e) => {
                                      if (statusMenuOpenFor === auditRow.id) {
                                        setStatusMenuOpenFor(null);
                                        setMenuPos(null);
                                        return;
                                      }
                                      const rect = (
                                        e.currentTarget as HTMLButtonElement
                                      ).getBoundingClientRect();
                                      setMenuPos({
                                        top: rect.bottom + 4,
                                        left: rect.left,
                                      });
                                      setStatusMenuOpenFor(auditRow.id);
                                    }}
                                    disabled={savingStatusFor === auditRow.id}
                                    style={{
                                      display: "inline-flex",
                                      alignItems: "center",
                                      gap: 4,
                                      padding: "3px 10px",
                                      borderRadius: 12,
                                      fontSize: 11,
                                      fontWeight: 700,
                                      cursor:
                                        savingStatusFor === auditRow.id
                                          ? "wait"
                                          : "pointer",
                                      backgroundColor:
                                        ROW_STATUS_META[auditRow.status]?.bg ??
                                        "#f1f5f9",
                                      color:
                                        ROW_STATUS_META[auditRow.status]
                                          ?.color ?? "#475569",
                                      border: "none",
                                    }}
                                    title="Click to change status"
                                  >
                                    {savingStatusFor === auditRow.id
                                      ? "Saving..."
                                      : (ROW_STATUS_META[auditRow.status]
                                          ?.label ?? auditRow.status)}
                                    <span style={{ fontSize: 9 }}>▾</span>
                                  </button>
                                  {statusMenuOpenFor === auditRow.id && (
                                    <>
                                      <div
                                        onClick={() => {
                                          setStatusMenuOpenFor(null);
                                          setMenuPos(null);
                                        }}
                                        style={{
                                          position: "fixed",
                                          inset: 0,
                                          zIndex: 9998,
                                        }}
                                      />
                                      <div
                                        style={{
                                          position: "fixed",
                                          top: menuPos?.top ?? 0,
                                          left: menuPos?.left ?? 0,
                                          background: "#fff",
                                          border: "1px solid #cbd5e1",
                                          borderRadius: 6,
                                          padding: 4,
                                          minWidth: 130,
                                          zIndex: 9999,
                                          boxShadow:
                                            "0 6px 16px rgba(0,0,0,0.12)",
                                        }}
                                      >
                                        {(
                                          [
                                            "PENDING",
                                            "CONFIRMED",
                                            "IN_PROGRESS",
                                            "COMPLETED",
                                            "CANCELLED",
                                            "RESCHEDULED",
                                          ] as RowStatus[]
                                        ).map((s) => (
                                          <div
                                            key={s}
                                            onClick={() =>
                                              handleInlineStatusChange(
                                                auditRow,
                                                s,
                                              )
                                            }
                                            style={{
                                              padding: "6px 10px",
                                              borderRadius: 4,
                                              fontSize: 12,
                                              cursor: "pointer",
                                              color:
                                                auditRow.status === s
                                                  ? ROW_STATUS_META[s]?.color
                                                  : "#0f172a",
                                              fontWeight:
                                                auditRow.status === s
                                                  ? 700
                                                  : 500,
                                              background:
                                                auditRow.status === s
                                                  ? "#f1f5f9"
                                                  : "transparent",
                                            }}
                                            onMouseEnter={(e) => {
                                              if (auditRow.status !== s)
                                                e.currentTarget.style.background =
                                                  "#f8fafc";
                                            }}
                                            onMouseLeave={(e) => {
                                              if (auditRow.status !== s)
                                                e.currentTarget.style.background =
                                                  "transparent";
                                            }}
                                          >
                                            {auditRow.status === s ? "✓ " : ""}
                                            {ROW_STATUS_META[s]?.label ?? s}
                                          </div>
                                        ))}
                                      </div>
                                    </>
                                  )}
                                </div>
                              ) : (
                                <RowStatusBadge status={auditRow.status} />
                              )}
                            </td>

                            {(canEdit || canDeleteAction || canCancelRow || canRescheduleRow) && (
                              <td style={{ ...subTdStyle, padding: 6 }}>
                                {rowCompleted ? (
                                  <span
                                    style={{ fontSize: 11, color: "#9ca3af" }}
                                  >
                                    ✓ Done
                                  </span>
                                ) : (
                                  <div
                                    style={{
                                      display: "flex",
                                      gap: 4,
                                      flexWrap: "wrap",
                                    }}
                                  >
                                    {canEdit && (
                                      <button
                                        onClick={() => setEditTarget(auditRow)}
                                        style={subActionEdit}
                                        title="Edit this audit row"
                                      >
                                        <FiEdit size={12} /> Edit
                                      </button>
                                    )}
                                    {/* 🆕 Per-row delete — same 'delete' permission as the
                                        schedule-level delete button (coordinator / super-admin
                                        by default via the roles & permissions matrix). */}
                                    {canDeleteAction && (
                                      <button
                                        onClick={() =>
                                          handleDeleteAuditRow(auditRow)
                                        }
                                        disabled={deletingRowId === auditRow.id}
                                        style={{
                                          ...subActionCancel,
                                          cursor:
                                            deletingRowId === auditRow.id
                                              ? "wait"
                                              : "pointer",
                                        }}
                                        title="Permanently delete this audit row"
                                      >
                                        <FiTrash2 size={12} />
                                        {deletingRowId === auditRow.id
                                          ? "Deleting..."
                                          : "Delete"}
                                      </button>
                                    )}
                                    {canCancelRow && !rowCancelled && (
                                      <button
                                        onClick={() =>
                                          onCancelAuditRow(
                                            expandedSchedule,
                                            auditRow,
                                          )
                                        }
                                        style={subActionCancel}
                                        title="Cancel this audit"
                                      >
                                        <FiXCircle size={12} /> Cancel
                                      </button>
                                    )}
                                    {canRescheduleRow && !rowClosed && (
                                      <button
                                        onClick={() =>
                                          onRescheduleAuditRow(
                                            expandedSchedule,
                                            auditRow,
                                          )
                                        }
                                        style={subActionReschedule}
                                        title="Reschedule this audit"
                                      >
                                        <FiRefreshCw size={12} />
                                      </button>
                                    )}
                                    {canRescheduleRow && rowCancelled && (
                                      <button
                                        onClick={() =>
                                          onRescheduleAuditRow(
                                            expandedSchedule,
                                            auditRow,
                                          )
                                        }
                                        style={subActionReschedule}
                                        title="Reschedule this audit"
                                      >
                                        <FiRefreshCw size={12} /> Reschedule
                                      </button>
                                    )}
                                  </div>
                                )}
                              </td>
                            )}
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          </td>
        </tr>
      )}

      {/* ✅ Edit Row modal */}
      <AuditRowEditModal
        isOpen={!!editTarget}
        onClose={() => setEditTarget(null)}
        scheduleId={expandedSchedule?.id ?? null}
        auditRow={editTarget}
        onSuccess={() => {
          setEditTarget(null);
          if (expandedSchedule) {
            onToggleExpand(row);
            setTimeout(() => onToggleExpand(row), 50);
          }
        }}
      />
    </>
  );
}

const subThStyle: React.CSSProperties = {
  textAlign: "left",
  padding: "7px 10px",
  fontSize: 10,
  fontWeight: 700,
  textTransform: "uppercase",
  letterSpacing: 0.4,
  color: "#475569",
  borderBottom: "1px solid #e2e8f0",
};

const subTdStyle: React.CSSProperties = {
  padding: "8px 10px",
  verticalAlign: "top",
  color: "#0f172a",
};

const subActionCancel: React.CSSProperties = {
  display: "inline-flex",
  alignItems: "center",
  gap: 3,
  padding: "3px 8px",
  background: "#fef2f2",
  border: "1px solid #fca5a5",
  color: "#b91c1c",
  borderRadius: 4,
  fontSize: 11,
  fontWeight: 600,
  cursor: "pointer",
};

const subActionReschedule: React.CSSProperties = {
  display: "inline-flex",
  alignItems: "center",
  gap: 3,
  padding: "3px 8px",
  background: "#fff7ed",
  border: "1px solid #fdba74",
  color: "#9a3412",
  borderRadius: 4,
  fontSize: 11,
  fontWeight: 600,
  cursor: "pointer",
};

const subActionEdit: React.CSSProperties = {
  display: "inline-flex",
  alignItems: "center",
  gap: 3,
  padding: "3px 8px",
  background: "#f5f3ff",
  border: "1px solid #c4b5fd",
  color: "#6d28d9",
  borderRadius: 4,
  fontSize: 11,
  fontWeight: 600,
  cursor: "pointer",
};
// ─── Co-Auditor chips ────────────────────────────────────────────────────
function CoAuditorChips({
  coAuditors,
}: {
  coAuditors: { id: number; firstName?: string; lastName?: string }[];
}) {
  if (!coAuditors || coAuditors.length === 0) {
    return <span style={{ color: "#9ca3af", fontSize: 12 }}>—</span>;
  }
  return (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
      {coAuditors.map((u) => {
        const name =
          `${u.firstName ?? ""} ${u.lastName ?? ""}`.trim().toUpperCase() ||
          "—";
        return (
          <span
            key={u.id}
            style={{
              padding: "2px 8px",
              borderRadius: 99,
              fontSize: 11,
              fontWeight: 600,
              background: "#eef2ff",
              color: "#4338ca",
              border: "1px solid #c7d2fe",
              whiteSpace: "nowrap",
            }}
          >
            {name}
          </span>
        );
      })}
    </div>
  );
}

// ─── Standards Badge Group (same UX as My Audits) ───────────────────────
function StandardsBadges({
  standards,
}: {
  standards: { id: number; name: string }[];
}) {
  const [open, setOpen] = useState(false);
  const [pos, setPos] = useState<{ top: number; left: number } | null>(null);
  const chipRef = useRef<HTMLButtonElement | null>(null);

  if (!standards || standards.length === 0) {
    return <span style={{ color: "#9ca3af", fontSize: 12 }}>—</span>;
  }

  const first = standards[0];
  const rest = standards.slice(1);

  const handleToggle = () => {
    if (!open && chipRef.current) {
      const rect = chipRef.current.getBoundingClientRect();
      setPos({ top: rect.bottom + 4, left: rect.left });
    } else {
      setPos(null);
    }
    setOpen(!open);
  };

  useEffect(() => {
    if (!open) return;
    const handler = (e: MouseEvent) => {
      if (chipRef.current && !chipRef.current.contains(e.target as Node)) {
        setOpen(false);
        setPos(null);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);

  return (
    <div
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 4,
        flexWrap: "nowrap",
        maxWidth: "100%",
      }}
    >
      <span
        style={{
          display: "inline-flex",
          alignItems: "center",
          padding: "3px 2px",
          borderRadius: 99,
          background: "#eef2ff",
          color: "#4338ca",
          fontSize: 11,
          fontWeight: 600,
          whiteSpace: "nowrap",
          border: "1px solid #c7d2fe",
        }}
      >
        {first.name}
      </span>

      {rest.length > 0 && (
        <>
          <button
            ref={chipRef}
            type="button"
            onClick={handleToggle}
            style={{
              display: "inline-flex",
              alignItems: "center",
              gap: 3,
              padding: "3px 8px",
              borderRadius: 99,
              background: "#f3f4f6",
              color: "#4b5563",
              fontSize: 11,
              fontWeight: 700,
              border: "1px solid #e5e7eb",
              cursor: "pointer",
              whiteSpace: "nowrap",
            }}
            title={rest.map((s) => s.name).join(", ")}
          >
            +{rest.length}
            <FiChevronDown
              size={10}
              style={{
                transform: open ? "rotate(180deg)" : "none",
                transition: "transform 0.15s",
              }}
            />
          </button>

          {open && pos && (
            <>
              <div
                onClick={() => {
                  setOpen(false);
                  setPos(null);
                }}
                style={{ position: "fixed", inset: 0, zIndex: 9998 }}
              />
              <div
                style={{
                  position: "fixed",
                  top: pos.top,
                  left: pos.left,
                  zIndex: 9999,
                  background: "#fff",
                  border: "1px solid #e5e7eb",
                  borderRadius: 8,
                  boxShadow: "0 10px 30px rgba(0,0,0,0.12)",
                  padding: "6px",
                  minWidth: 200,
                  maxHeight: 240,
                  overflowY: "auto",
                }}
              >
                <div
                  style={{
                    padding: "4px 8px",
                    fontSize: 10,
                    fontWeight: 700,
                    color: "#6b7280",
                    textTransform: "uppercase",
                    letterSpacing: "0.05em",
                  }}
                >
                  All Standards ({standards.length})
                </div>
                {standards.map((s) => (
                  <div
                    key={s.id}
                    style={{
                      padding: "6px 8px",
                      fontSize: 12,
                      color: "#374151",
                      borderRadius: 4,
                      display: "flex",
                      alignItems: "center",
                      gap: 6,
                    }}
                  >
                    <span
                      style={{
                        width: 6,
                        height: 6,
                        borderRadius: "50%",
                        background: "#4338ca",
                        flexShrink: 0,
                      }}
                    />
                    {s.name}
                  </div>
                ))}
              </div>
            </>
          )}
        </>
      )}
    </div>
  );
}