import { useState } from 'react';

const Home: React.FC = () => {
  const [fileContent, setFileContent] = useState<string>('');
  const [previewHtml, setPreviewHtml] = useState<string>('');

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const xmlString = e.target?.result as string;
        setFileContent(xmlString);
        // Преобразование XML в HTML
        const htmlString = convertXmlToHtml(xmlString);
        setPreviewHtml(htmlString);
      };
      reader.readAsText(file);
    }
  };

  const convertXmlToHtml = (xml: string): string => {
    // Простой пример преобразования XML в HTML
    return xml.replace(/<(\w+)>(.*?)<\/\1>/g, '<div><strong>$1:</strong> $2</div>');
  };

  const handleDownload = () => {
    const blob = new Blob([previewHtml], { type: 'text/html' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'converted.html';
    link.click();
  };

  return (
    <div>
      <h1>Конвертер XML в HTML</h1>
      <input type="file" accept=".xml" onChange={handleFileChange} />
      <br />
      <button onClick={handleDownload} disabled={!previewHtml}>
        Скачать HTML
      </button>

      <h2>Предварительный просмотр:</h2>
      <div dangerouslySetInnerHTML={{ __html: previewHtml }} />
    </div>
  );
};

export default Home;