import React, { useEffect, useMemo, useState } from 'react';
import { api } from '../api.js';

export function ConfigViewer({ open, onClose }) {
  const [config, setConfig] = useState(null);
  const [error, setError] = useState('');
  const [search, setSearch] = useState('');

  useEffect(() => {
    if (!open) return;
    let cancelled = false;
    setConfig(null);
    setError('');
    api.config()
      .then((data) => { if (!cancelled) setConfig(data.config); })
      .catch((err) => { if (!cancelled) setError(err.message); });
    return () => { cancelled = true; };
  }, [open]);

  const text = useMemo(() => (config ? JSON.stringify(config, null, 2) : ''), [config]);

  const highlighted = useMemo(() => {
    if (!search || !text) return text;
    try {
      const re = new RegExp(search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
      return text.split(re);
    } catch {
      return text;
    }
  }, [text, search]);

  if (!open) return null;

  function copy() { navigator.clipboard?.writeText(text).catch(() => {}); }
  function download() {
    const blob = new Blob([text], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'sing-box-config.json';
    a.click();
    URL.revokeObjectURL(url);
  }

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal lg" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <h3>sing-box config</h3>
            <small className="muted">Автогенерируемый, перезаписывается при apply</small>
          </div>
          <div className="btn-group">
            <input
              className="input"
              placeholder="Поиск…"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              style={{ width: 160 }}
            />
            <button className="btn btn-ghost sm" disabled={!config} onClick={copy}>Копировать</button>
            <button className="btn btn-ghost sm" disabled={!config} onClick={download}>Скачать</button>
            <button className="btn btn-secondary sm" onClick={onClose}>Закрыть</button>
          </div>
        </div>
        <div className="modal-body">
          {error && <div className="conflict-banner danger">{error}</div>}
          {!error && !config && <p className="muted">Конфиг ещё не сгенерирован.</p>}
          {config && (
            <pre className="config-view">
              {Array.isArray(highlighted)
                ? highlighted.map((part, i) => (
                    <React.Fragment key={i}>
                      {part}
                      {i < highlighted.length - 1 && <mark style={{ background: 'var(--warning-dim)', color: 'var(--warning)' }}>{search}</mark>}
                    </React.Fragment>
                  ))
                : text}
            </pre>
          )}
        </div>
      </div>
    </div>
  );
}
