// dialog.jsx — кастомные confirm / alert / choice / pick в стиле сайта

let setDialogState = null;

const DialogBody = ({ dialog, onClose }) => {
  const {
    type,
    title,
    message,
    confirmLabel,
    cancelLabel,
    yesLabel,
    noLabel,
    danger,
    icon,
    items = [],
  } = dialog;

  const [pickId, setPickId] = React.useState(items[0]?.id ?? null);
  const [query, setQuery] = React.useState('');

  React.useEffect(() => {
    setPickId(items[0]?.id ?? null);
    setQuery('');
  }, [dialog, items]);

  const filtered = items.filter((item) => {
    if (!query.trim()) return true;
    const q = query.toLowerCase();
    return (item.label || '').toLowerCase().includes(q) || (item.hint || '').toLowerCase().includes(q);
  });

  if (type === 'pick') {
    return (
      <div className="ui-dialog ui-dialog--pick" role="dialog" aria-modal="true" onClick={(e) => e.stopPropagation()}>
        <div className={`ui-dialog-icon ui-dialog-icon--info`}>
          <Icon name={icon || 'quiz'} size={22} />
        </div>
        <h2 className="ui-dialog-title">{title}</h2>
        {message && <p className="ui-dialog-message">{message}</p>}
        {items.length > 8 && (
          <input
            className="ui-dialog-search"
            placeholder="Поиск статьи…"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
        )}
        <div className="ui-dialog-pick-list">
          {!filtered.length ? (
            <p className="ui-dialog-pick-empty">Ничего не найдено</p>
          ) : filtered.map((item) => (
            <button
              key={item.id}
              type="button"
              className={`ui-dialog-pick-item${pickId === item.id ? ' is-selected' : ''}`}
              onClick={() => setPickId(item.id)}
            >
              <span className="ui-dialog-pick-label">{item.label}</span>
              {item.hint && <span className="ui-dialog-pick-hint">{item.hint}</span>}
            </button>
          ))}
        </div>
        <div className="ui-dialog-actions">
          <button type="button" className="btn btn-ghost" onClick={() => onClose(null)}>
            {cancelLabel || 'Отмена'}
          </button>
          <button type="button" className="btn btn-primary" disabled={!pickId} onClick={() => onClose(pickId)}>
            {confirmLabel || 'Выбрать'}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="ui-dialog" role="dialog" aria-modal="true" onClick={(e) => e.stopPropagation()}>
      <div className={`ui-dialog-icon${danger ? ' ui-dialog-icon--danger' : ' ui-dialog-icon--info'}`}>
        <Icon name={icon || (danger ? 'trash' : 'info')} size={22} />
      </div>
      <h2 className="ui-dialog-title">{title}</h2>
      {message && <p className="ui-dialog-message">{message}</p>}
      <div className="ui-dialog-actions">
        {type === 'confirm' && (
          <button type="button" className="btn btn-ghost" onClick={() => onClose(false)}>
            {cancelLabel || 'Отмена'}
          </button>
        )}
        {type === 'choice' && (
          <button type="button" className="btn btn-ghost" onClick={() => onClose(false)}>
            {noLabel || 'Нет'}
          </button>
        )}
        {type === 'choice' ? (
          <button type="button" className="btn btn-primary" onClick={() => onClose(true)} autoFocus>
            {yesLabel || 'Да'}
          </button>
        ) : (
          <button
            type="button"
            className={`btn ${danger ? 'ui-dialog-btn-danger' : 'btn-primary'}`}
            onClick={() => onClose(type === 'confirm' ? true : undefined)}
            autoFocus
          >
            {confirmLabel || 'OK'}
          </button>
        )}
      </div>
    </div>
  );
};

const DialogHost = () => {
  const [dialog, setDialog] = React.useState(null);

  React.useEffect(() => {
    setDialogState = setDialog;
    return () => { setDialogState = null; };
  }, []);

  if (!dialog) return null;

  const close = (result) => {
    setDialog(null);
    dialog.resolve(result);
  };

  const dismissible = dialog.type === 'confirm' || dialog.type === 'choice' || dialog.type === 'pick';

  return (
    <div className="modal-overlay ui-dialog-overlay" onClick={() => dismissible && close(dialog.type === 'pick' ? null : false)}>
      <DialogBody dialog={dialog} onClose={close} />
    </div>
  );
};

const openDialog = (opts) => new Promise((resolve) => {
  if (!setDialogState) {
    if (opts.type === 'confirm' || opts.type === 'choice') {
      resolve(window.confirm(opts.message || opts.title));
      return;
    }
    if (opts.type === 'pick') {
      resolve(null);
      return;
    }
    window.alert(opts.message || opts.title);
    resolve(undefined);
    return;
  }
  setDialogState({ ...opts, resolve });
});

window.UI = {
  confirm(messageOrOpts) {
    const opts = typeof messageOrOpts === 'string'
      ? { message: messageOrOpts }
      : { ...messageOrOpts };
    return openDialog({
      type: 'confirm',
      title: opts.title || 'Подтверждение',
      message: opts.message || '',
      confirmLabel: opts.confirmLabel || opts.confirmText || 'OK',
      cancelLabel: opts.cancelLabel || opts.cancelText || 'Отмена',
      danger: opts.danger ?? false,
      icon: opts.icon,
    });
  },

  choice(messageOrOpts) {
    const opts = typeof messageOrOpts === 'string'
      ? { message: messageOrOpts }
      : { ...messageOrOpts };
    return openDialog({
      type: 'choice',
      title: opts.title || 'Выберите',
      message: opts.message || '',
      yesLabel: opts.yesLabel || 'Да',
      noLabel: opts.noLabel || 'Нет',
      icon: opts.icon || 'quiz',
    });
  },

  pick(messageOrOpts) {
    const opts = typeof messageOrOpts === 'string'
      ? { message: messageOrOpts }
      : { ...messageOrOpts };
    return openDialog({
      type: 'pick',
      title: opts.title || 'Выберите',
      message: opts.message || '',
      items: opts.items || [],
      confirmLabel: opts.confirmLabel || 'Выбрать',
      cancelLabel: opts.cancelLabel || 'Отмена',
      icon: opts.icon || 'quiz',
    });
  },

  alert(messageOrOpts) {
    const opts = typeof messageOrOpts === 'string'
      ? { message: messageOrOpts }
      : { ...messageOrOpts };
    return openDialog({
      type: 'alert',
      title: opts.title || 'Сообщение',
      message: opts.message || '',
      confirmLabel: opts.confirmLabel || opts.okLabel || 'OK',
      danger: false,
      icon: opts.icon || 'info',
    });
  },
};

window.DialogHost = DialogHost;
