// Tool modal — chrome + registry lookup.
//
// Each tool lives in its own file under tools/ and registers a component on
// window.TOOL_HANDLERS[tool.id] (see tools/_shared.jsx). If no handler exists,
// we fall back to window.ComingSoonTool.

function ToolModal({ tool, onClose, onFavorite, isFavorite }) {
  const [, t] = window.useI18n();
  const modalRef = React.useRef(null);

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') { onClose(); return; }
      // Focus trap: cycle Tab within the modal
      if (e.key === 'Tab' && modalRef.current) {
        const focusable = modalRef.current.querySelectorAll(
          'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
        );
        if (focusable.length === 0) return;
        const first = focusable[0];
        const last = focusable[focusable.length - 1];
        if (e.shiftKey) {
          if (document.activeElement === first) { e.preventDefault(); last.focus(); }
        } else {
          if (document.activeElement === last) { e.preventDefault(); first.focus(); }
        }
      }
    };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    // Auto-focus close button on mount for keyboard users
    const close = modalRef.current?.querySelector('.mh-close');
    if (close) close.focus();
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [onClose]);

  if (!tool) return null;
  const cat = window.CATEGORIES.find(c => c.id === tool.cat);
  const Handler = (window.TOOL_HANDLERS && window.TOOL_HANDLERS[tool.id]) || window.ComingSoonTool;

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" ref={modalRef} role="dialog" aria-modal="true" aria-label={window.tTool(tool, 'name')} onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div className="mh-icon" style={{ background: cat.soft, color: cat.tint }}>
            <Icon name={tool.icon} size={22} />
          </div>
          <div style={{ flex: 1 }}>
            <div className="mh-name">{window.tTool(tool, 'name')}</div>
            <div className="mh-desc">{window.tTool(tool, 'desc')}</div>
          </div>
          <button className={`mh-fav ${isFavorite ? 'active' : ''}`} onClick={() => onFavorite(tool.id)} aria-label={t('modal.favorite')}>
            <Icon name="sparkle" size={16} strokeWidth={isFavorite ? 2 : 1.75} />
          </button>
          <button className="mh-close" onClick={onClose} aria-label={t('modal.close')}>
            <Icon name="x" size={18} />
          </button>
        </div>
        <div className="modal-body">
          {window.MMErrorBoundary
            ? <window.MMErrorBoundary scope={`tool:${tool.id}`}
                fallback={(err, reset) => (
                  <window.ToolError error={err} onRetry={reset} />
                )}>
                <Handler tool={tool} cat={cat} />
              </window.MMErrorBoundary>
            : <Handler tool={tool} cat={cat} />}
          {/* Ad slot: post-action in modal */}
          {window.AdSlot && <window.AdSlot slot="modal" style={{ marginTop: 16 }} />}
        </div>
      </div>
    </div>
  );
}

window.ToolModal = ToolModal;
