'use client';

import { useEffect, useRef } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { cn } from '@/lib/utils/cn';

/** Design `dialog.mtg-drawer` with showModal() / close(). */
export function MtgDrawer({
  open,
  onClose,
  title,
  titleId,
  users,
  foot,
  children,
  className,
}: {
  open: boolean;
  onClose: () => void;
  title: React.ReactNode;
  titleId: string;
  users?: boolean;
  foot?: React.ReactNode;
  children: React.ReactNode;
  className?: string;
}) {
  const ref = useRef<HTMLDialogElement>(null);

  useEffect(() => {
    const d = ref.current;
    if (!d) return;
    if (open && !d.open) d.showModal();
    else if (!open && d.open) d.close();
  }, [open]);

  // The browser's own Escape does not always reach a dialog opened this way (QA go-live: Meetings 1047).
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Escape' || e.defaultPrevented) return;
      e.preventDefault();
      onClose();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  return (
    <dialog
      ref={ref}
      className={cn('mtg-drawer', users && 'mtg-drawer--users', className)}
      aria-labelledby={titleId}
      onClose={onClose}
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div className="mtg-drawer__form">
        <header className="mtg-drawer__head">
          <h2 id={titleId}>{title}</h2>
          <button
            type="button"
            className="mtg-close crm-modal-close"
            aria-label="Close"
            onClick={onClose}
          >
            <CrmIcon name="x" className="iconSize-16" />
          </button>
        </header>
        <div className="mtg-drawer__body">{children}</div>
        {foot ? <footer className="mtg-drawer__foot">{foot}</footer> : null}
      </div>
    </dialog>
  );
}

export function GripIcon() {
  return (
    <svg viewBox="0 0 16 16" width="15" height="15" aria-hidden focusable="false">
      <circle cx="5" cy="3" r="1.15" fill="currentColor" />
      <circle cx="11" cy="3" r="1.15" fill="currentColor" />
      <circle cx="5" cy="8" r="1.15" fill="currentColor" />
      <circle cx="11" cy="8" r="1.15" fill="currentColor" />
      <circle cx="5" cy="13" r="1.15" fill="currentColor" />
      <circle cx="11" cy="13" r="1.15" fill="currentColor" />
    </svg>
  );
}

export function TrashIcon() {
  return (
    <svg viewBox="0 0 24 24" width="17" height="17" aria-hidden focusable="false">
      <path
        d="M4 7h16M9 7V4h6v3m-9 0 1 13h10l1-13M10 11v5m4-5v5"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.7"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}
