"use client";

import { useEffect, useState } from "react";

export default function PreloaderAndSearch() {
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    // Preloader'ı kapat
    const timer = setTimeout(() => {
      setIsLoaded(true);
    }, 500);

    // Search button click handler
    const searchButton = document.getElementById('searchButton');
    const searchClose = document.getElementById('searchClose');
    const searchOverlay = document.getElementById('searchOverlay');
    const searchPopup = document.querySelector('.search-form-popup');

    const openSearch = () => {
      searchOverlay?.classList.add('active');
      searchPopup?.classList.add('active');
      document.body.style.overflow = 'hidden';
    };

    const closeSearch = () => {
      searchOverlay?.classList.remove('active');
      searchPopup?.classList.remove('active');
      document.body.style.overflow = '';
    };

    searchButton?.addEventListener('click', openSearch);
    searchClose?.addEventListener('click', closeSearch);
    searchOverlay?.addEventListener('click', closeSearch);

    // Cleanup
    return () => {
      clearTimeout(timer);
      searchButton?.removeEventListener('click', openSearch);
      searchClose?.removeEventListener('click', closeSearch);
      searchOverlay?.removeEventListener('click', closeSearch);
    };
  }, []);

  return (
    <>
      {/* Preloader */}
      {!isLoaded && (
        <div className="preloader" id="preloader">
          <div className="spinner-grow" role="status">
            <span className="visually-hidden">Loading...</span>
          </div>
        </div>
      )}

      {/* Search Form Overlay */}
      <div className="search-bg-overlay" id="searchOverlay"></div>

      {/* Search Form Popup */}
      <div className="search-form-popup">
        <h2 className="mb-4">How can I help you, Today?</h2>
        <button type="button" className="close-btn" id="searchClose" aria-label="Close">
          <i className="ti ti-x"></i>
        </button>
        <form className="search-form">
          <input type="search" className="form-control" placeholder="Search..." />
          <button type="submit" className="btn btn-primary">
            <i className="ti ti-search"></i> Search
          </button>
        </form>
      </div>
    </>
  );
}

