const { useState, useEffect, useRef } = React;

const QUICK_LINKS = [
  { name: 'Яндекс Почта', icon: 'mail', url: 'https://mail.yandex.ru', color: 'from-amber-500 to-red-500' },
  { name: 'Кинопоиск', icon: 'film', url: 'https://kinopoisk.ru', color: 'from-orange-500 to-amber-600' },
  { name: 'Хабр', icon: 'code', url: 'https://habr.com', color: 'from-blue-500 to-cyan-500' },
  { name: 'GitHub', icon: 'github', url: 'https://github.com', color: 'from-purple-500 to-indigo-600' },
  { name: 'VC.ru', icon: 'newspaper', url: 'https://vc.ru', color: 'from-emerald-400 to-teal-600' },
  { name: 'Музыка', icon: 'music', url: 'https://music.yandex.ru', color: 'from-yellow-400 to-orange-500' },
];

function AsanalindexApp() {
  const [query, setQuery] = useState('');
  const [activeSearch, setActiveSearch] = useState('');
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const [hasSearched, setHasSearched] = useState(false);
  const [viewMode, setViewMode] = useState('native'); // 'native' или 'frame'
  const inputRef = useRef(null);

  useEffect(() => {
    if (window.lucide) {
      window.lucide.createIcons();
    }
  }, [hasSearched, loading, results, viewMode]);

  // Выполнение живого поиска
  const executeSearch = async (searchQuery) => {
    const clean = searchQuery.trim();
    if (!clean) return;

    setActiveSearch(clean);
    setHasSearched(true);
    setLoading(true);

    try {
      // Запрашиваем реальную HTML выдачу через бесплатный прокси
      const proxyUrl = 'https://api.allorigins.win/get?url=';
      const targetUrl = `https://html.duckduckgo.com/html/?q=${encodeURIComponent(clean)}`;

      const res = await fetch(`${proxyUrl}${encodeURIComponent(targetUrl)}`);
      const data = await res.json();

      if (data && data.contents) {
        const parser = new DOMParser();
        const doc = parser.parseFromString(data.contents, 'text/html');
        const searchResults = doc.querySelectorAll('.result');

        const parsed = [];

        searchResults.forEach((item, index) => {
          if (index >= 8) return; // Берем первые 8 сайтов

          const titleEl = item.querySelector('.result__title a');
          const snippetEl = item.querySelector('.result__snippet');

          if (titleEl) {
            let rawUrl = titleEl.getAttribute('href') || '';
            
            // Чистим URL от внутренних редиректов
            if (rawUrl.includes('uddg=')) {
              rawUrl = decodeURIComponent(rawUrl.split('uddg=')[1].split('&')[0]);
            }

            let domainName = 'web';
            try {
              domainName = new URL(rawUrl).hostname.replace('www.', '');
            } catch (e) {}

            parsed.push({
              title: titleEl.textContent.trim(),
              url: rawUrl,
              domain: domainName,
              snippet: snippetEl ? snippetEl.textContent.trim() : 'Описание страницы отсутствует'
            });
          }
        });

        if (parsed.length > 0) {
          setResults(parsed);
          setLoading(false);
          return;
        }
      }

      throw new Error('Пустая выдача');
    } catch (error) {
      console.error('Ошибка загрузки результатов:', error);

      // Богатый резервный вариант, если сети/прокси не ответили
      setResults([
        {
          title: `${clean} — Википедия (Свободная энциклопедия)`,
          url: `https://ru.wikipedia.org/wiki/Special:Search?search=${encodeURIComponent(clean)}`,
          domain: 'wikipedia.org',
          snippet: `Материалы, термины и подробная справочная информация по запросу «${clean}».`
        },
        {
          title: `Результаты поиска «${clean}» в Яндексе`,
          url: `https://yandex.ru/search/?text=${encodeURIComponent(clean)}`,
          domain: 'yandex.ru',
          snippet: `Смотреть прямую выдачу Яндекса, картинки и сервисы.`
        },
        {
          title: `Обсуждения и код «${clean}» на Хабре`,
          url: `https://habr.com/ru/search/?q=${encodeURIComponent(clean)}`,
          domain: 'habr.com',
          snippet: `Статьи разработчиков, туториалы и разборы кода по запросу «${clean}».`
        },
        {
          title: `Репозитории и проекты «${clean}» на GitHub`,
          url: `https://github.com/search?q=${encodeURIComponent(clean)}`,
          domain: 'github.com',
          snippet: `Исходный код, библиотеки и opensource проекты связанные с «${clean}».`
        }
      ]);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    executeSearch(query);
  };

  const resetToHome = () => {
    setHasSearched(false);
    setActiveSearch('');
    setQuery('');
  };

  const getYandexFrameUrl = () => {
    return `https://yandex.ru/search/?text=${encodeURIComponent(activeSearch)}`;
  };

  return (
    <div className="flex-1 flex flex-col justify-between max-w-6xl w-full mx-auto px-4 py-6">
      
      {/* Header */}
      <header className="flex items-center justify-between py-4 border-b border-white/5">
        <div 
          onClick={resetToHome} 
          className="flex items-center space-x-3 cursor-pointer group"
        >
          <div className="w-10 h-10 rounded-xl bg-gradient-to-tr from-indigo-500 via-purple-500 to-cyan-500 flex items-center justify-center font-extrabold text-xl text-white shadow-lg shadow-indigo-500/30 group-hover:scale-105 transition-transform">
            A
          </div>
          <span className="font-extrabold text-2xl tracking-wider bg-clip-text text-transparent bg-gradient-to-r from-white via-gray-200 to-gray-400">
            ASANALINDEX
          </span>
        </div>

        {hasSearched && (
          <div className="flex items-center space-x-2 bg-white/5 p-1 rounded-xl border border-white/10">
            <button
              onClick={() => setViewMode('native')}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-all ${
                viewMode === 'native' ? 'bg-indigo-600 text-white shadow-md' : 'text-gray-400 hover:text-white'
              }`}
            >
              Живой Поиск
            </button>
            <button
              onClick={() => setViewMode('frame')}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-all ${
                viewMode === 'frame' ? 'bg-amber-400 text-black font-semibold shadow-md' : 'text-gray-400 hover:text-white'
              }`}
            >
              Яндекс Веб
            </button>
          </div>
        )}
      </header>

      {/* Main Search Body */}
      {!hasSearched ? (
        <main className="flex-1 flex flex-col items-center justify-center my-12">
          <div className="text-center mb-8 relative">
            <h1 className="text-5xl sm:text-7xl font-extrabold tracking-tight bg-clip-text text-transparent bg-gradient-to-r from-white via-indigo-100 to-purple-200">
              Asanalindex
            </h1>
            <p className="mt-3 text-sm sm:text-base text-gray-400 font-light">
              Быстрый поиск с реальной веб-выдачей
            </p>
          </div>

          <div className="w-full max-w-3xl">
            <form onSubmit={handleSubmit} className="relative z-20">
              <div className="glass-input rounded-2xl p-2 flex items-center shadow-2xl">
                <div className="pl-4 pr-2 text-gray-400">
                  <i data-lucide="search" className="w-5 h-5 text-purple-400"></i>
                </div>

                <input
                  ref={inputRef}
                  type="text"
                  value={query}
                  onChange={(e) => setQuery(e.target.value)}
                  placeholder="Введите запрос..."
                  className="w-full bg-transparent text-white placeholder-gray-500 text-base sm:text-lg focus:outline-none px-2 py-2"
                  autoFocus
                />

                <button
                  type="submit"
                  className="bg-gradient-to-r from-indigo-500 to-purple-600 hover:opacity-90 text-white font-medium px-6 py-3 rounded-xl transition-all shadow-md shrink-0"
                >
                  Искать
                </button>
              </div>
            </form>

            <div className="mt-12">
              <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-3">
                {QUICK_LINKS.map((link, i) => (
                  <a
                    key={i}
                    href={link.url}
                    target="_blank"
                    rel="noreferrer"
                    className="glass-card p-3 rounded-2xl flex flex-col items-center justify-center hover:scale-105 transition-all group"
                  >
                    <div className={`w-10 h-10 rounded-xl bg-gradient-to-br ${link.color} flex items-center justify-center text-white mb-2 shadow-md`}>
                      <i data-lucide={link.icon} className="w-5 h-5"></i>
                    </div>
                    <span className="text-xs font-medium text-gray-300 group-hover:text-white truncate w-full text-center">
                      {link.name}
                    </span>
                  </a>
                ))}
              </div>
            </div>
          </div>
        </main>
      ) : (
        /* Results View */
        <main className="flex-1 my-6 flex flex-col">
          <div className="mb-6 max-w-3xl">
            <form onSubmit={handleSubmit} className="flex gap-2">
              <div className="glass-input flex-1 rounded-xl p-1.5 flex items-center">
                <i data-lucide="search" className="w-4 h-4 text-purple-400 ml-3 mr-2"></i>
                <input
                  type="text"
                  value={query}
                  onChange={(e) => setQuery(e.target.value)}
                  className="w-full bg-transparent text-white focus:outline-none text-sm"
                />
              </div>
              <button type="submit" className="bg-indigo-600 hover:bg-indigo-700 text-white px-5 py-2 rounded-xl text-sm font-medium transition-all">
                Искать
              </button>
            </form>
          </div>

          {loading ? (
            <div className="flex-1 flex flex-col items-center justify-center py-20 space-y-4">
              <div className="w-10 h-10 border-4 border-purple-500 border-t-transparent rounded-full animate-spin"></div>
              <p className="text-gray-400 text-sm">Ищем информацию в сети...</p>
            </div>
          ) : viewMode === 'native' ? (
            <div className="max-w-3xl space-y-4 animate-fadeIn">
              <p className="text-xs text-gray-500 mb-2">
                Результаты поиска по запросу: <span className="text-white font-medium">«{activeSearch}»</span>
              </p>

              {results.map((res, idx) => (
                <div key={idx} className="glass-card p-5 rounded-2xl hover:border-white/20 transition-all">
                  <div className="flex items-center space-x-2 text-xs text-gray-400 mb-1">
                    <span className="bg-white/10 text-cyan-400 px-2 py-0.5 rounded font-mono">{res.domain}</span>
                    <span className="truncate">{res.url}</span>
                  </div>
                  <a 
                    href={res.url} 
                    target="_blank" 
                    rel="noreferrer"
                    className="text-lg font-semibold text-indigo-300 hover:text-indigo-200 transition-colors block mb-2"
                  >
                    {res.title}
                  </a>
                  <p className="text-sm text-gray-300 leading-relaxed">
                    {res.snippet}
                  </p>
                </div>
              ))}

              <div className="p-4 rounded-2xl bg-gradient-to-r from-amber-500/10 to-orange-500/10 border border-amber-500/20 flex items-center justify-between mt-8">
                <div>
                  <h4 className="text-sm font-semibold text-amber-300">Открыть в Яндексе?</h4>
                  <p className="text-xs text-gray-400">Перейти к выдаче Яндекса для получения региональных сервисов</p>
                </div>
                <a
                  href={getYandexFrameUrl()}
                  target="_blank"
                  rel="noreferrer"
                  className="px-4 py-2 bg-amber-400 text-black font-semibold text-xs rounded-xl hover:opacity-90 transition-opacity"
                >
                  Яндекс ↗
                </a>
              </div>
            </div>
          ) : (
            <div className="flex-1 w-full min-h-[650px] rounded-2xl overflow-hidden border border-white/10 glass-card">
              <iframe
                src={getYandexFrameUrl()}
                className="w-full h-full min-h-[650px]"
                title="Yandex Search"
              ></iframe>
            </div>
          )}
        </main>
      )}

      {/* Footer */}
      <footer className="py-4 border-t border-white/5 text-xs text-gray-500 flex justify-between items-center">
        <span>Asanalindex Search Engine</span>
        <span>Real Web API Integrated</span>
      </footer>

    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<AsanalindexApp />);