import React, { useState, useEffect } from 'react';
import ReactMarkdown from 'react-markdown';
import rehypeRaw from 'rehype-raw';

export default function ContextualHelp({ keyword, lang = 'en', onClose }) {
  const [help, setHelp] = useState(null);

  // Load help content for keyword
  useEffect(() => {
    if (!keyword) return;

    fetch(`http://localhost:8080/api/help?lang=${lang}`)
        .then(res => res.json())
        .then(data => setHelp(data[keyword]))
        .catch(err => {
          console.error('Failed to fetch help content', err);
          setHelp(null);
        });
  }, [keyword, lang]);

  // ESC key to close
  useEffect(() => {
    const handleEsc = (e) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', handleEsc);
    return () => window.removeEventListener('keydown', handleEsc);
  }, [onClose]);

  if (!help) return null;

  return (
      <div style={modalStyle} onClick={onClose}>
        <div style={modalContentStyle} onClick={(e) => e.stopPropagation()}>
          <button style={closeButtonStyle} onClick={onClose}>×</button>
          <h2>{help.title}</h2>
          <ReactMarkdown
              rehypePlugins={[rehypeRaw]}
              components={{
                a: ({ node, ...props }) => (
                    <a {...props} target="_blank" rel="noopener noreferrer" />
                )
              }}
          >
            {help.text}
          </ReactMarkdown>
        </div>
      </div>
  );
}

// 🎨 Modal Styles
const modalStyle = {
  position: 'fixed',
  top: 0,
  left: 0,
  width: '100vw',
  height: '100vh',
  background: 'rgba(0, 0, 0, 0.5)',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  zIndex: 1000,
};

const modalContentStyle = {
  background: '#fff',
  padding: '20px',
  borderRadius: '8px',
  minWidth: '320px',
  maxWidth: '600px',
  position: 'relative',
  overflowY: 'auto',
  maxHeight: '80vh',
};

const closeButtonStyle = {
  position: 'absolute',
  top: '10px',
  right: '15px',
  fontSize: '20px',
  background: 'none',
  border: 'none',
  cursor: 'pointer',
};
