  const { useState, useEffect } = React;

    const App = () => {
      const [searchQuery, setSearchQuery] = useState('');
      const [data, setData] = useState([]);
      const [filteredData, setFilteredData] = useState([]);
      const [isActive, setIsActive] = useState(false);
      const [isLoading, setIsLoading]= useState(true)


      // this code is for fetching the fake API
      useEffect(() => {
         let isMounted = true;
        fetch('https://acapulcowomen.com/dev/fake-api.json')
          .then(response => response.json())
          .then(data => {
            setData(data);
            setFilteredData(data);
            setIsLoading(false);
          })
          .catch(error => console.error('Error fetching data:', error));
           setIsLoading(false);
     
      }, []);

        // This code is for filtering the keywords from input
      const handleSearchChange = (event) => {
        const value = event.target.value;
        setSearchQuery(value);


        const keywords = value.toLowerCase().split(' ');
        const filtered = data.filter(post =>
          keywords.every(keyword =>
            post.keywords.toLowerCase().includes(keyword)
          )
        );
        setFilteredData(filtered);
      };

      // This Code is for seting active when the search input is clicked
       useEffect(() => {
    const handleClickOutside = (event) => {
      if (!event.target.closest('#searchInput')) {
        setIsActive(false);
      }
    };

    document.addEventListener('click', handleClickOutside);

    return () => {
      document.removeEventListener('click', handleClickOutside);
    };
  }, []);

    const handleClick = () => {
    setIsActive(!isActive);
     document.getElementsByClassName('searchTerm')[1].focus();
  };

  const handleClose = () =>{
   setSearchQuery('');
  }



    const searchClicked = document.getElementById('click');

      return (
        <div  id="searchGlobalWrapper" className={isActive ? 'active' : ''} onClick={handleClick}>
         <div id="searchInput" >
          <input
            type="text"
            value={searchQuery}
            onChange={handleSearchChange}
            placeholder="Search..."
            className="searchTerm"
           
          />
          <button type="submit" className="searchButtonGlobal" >
          <i className="fa fa-search"></i>
     </button>
   
      </div>
      
 



     {searchQuery.length > 0 ?(
 <div id="searchResults" className="shadow">
  <div className="closeButton col-12" onClick={handleClose} >
    <button>close X</button>
    </div>
{isLoading ? (
  <div>Loading...</div>
) : (
  filteredData.length > 0 ? (
    filteredData.map(post => (
      <div key={post.title} className="searchResultItem">
        <a target="_blank" href={post.link} className="d-flex">
          <div className="resultItemImg">
            <img src={post.img} alt="" className="img-fluid"/>
          </div>
          <div className="resultTitle">
            <h4>{post.title}</h4>
            <p>{post.description}</p>
          </div>
        </a>
      </div>
    ))
  ) : (
    <div id="noResultFound">
      "{searchQuery}" <span>Sorry No results Found</span>
    </div>
  )
)}
 </div>
): (<div></div>)}

        </div>
      );
    };


    //this function is to check if login or not
const CheckCredentials = () => {
  const [islogin, setIsLogin] = useState(0);
  const [isMessageCount, setIsMessageCount] = useState('');


useEffect(() => {
     fetch('https://acapulcowomen.com/members/mailbox')
 .then(response => response.text())
 .then(html => {
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, 'text/html');
  const badge = doc.querySelector('.badge-danger');
  setIsMessageCount(badge.textContent);
  setIsLogin(1);
  console.log(badge.textContent);
 })
 .catch(error => console.error('Error fetching data:', error));

      }, []);


  return (
   <div>
{islogin > 0 ? (
 <div className="list-group list-group-horizontal" >
    <li className="list-group-item border-0">
      <a target="_blank" href="/women/poltava-women/poltava-women.htm" className="fw-b2 nav-link rounded-pill border text-dark py-2 my-2 px-2 my-sm-0">
        <i className="fa-solid fa-address-card"></i>&nbsp;&nbsp;All Ladies Profiles
      </a>
    </li>
    <li className="list-group-item border-0">
     {isMessageCount && <div className="messageCount">{isMessageCount}</div>}
      <a href="/members/mailbox?folder=received" className="fw-b2 nav-link rounded-pill border text-dark py-2 my-2 px-2 my-sm-0" id="messageButton" type="button">
        <i className="fa-solid fas fa-comment-dots"></i>&nbsp;&nbsp;Messages
      </a>
    </li>
    <li className="list-group-item border-0 register-free-modal" >
      <a href="/members/home" className="fw-b2 nav-link rounded-pill border text-white bg-success border-warning py-2 my-2 px-2 my-sm-0" type="button" >
        <i className="fa-solid fa-user"></i>&nbsp;&nbsp;My Account
      </a>
    </li>
  </div>
) : (
  <div className="list-group list-group-horizontal">
    <li className="list-group-item border-0">
      <a target="_blank" href="/women/poltava-women/poltava-women.htm" className="fw-b2 nav-link rounded-pill border text-dark py-2 my-2 px-2 my-sm-0">
        <i className="fa-solid fa-address-card"></i>&nbsp;&nbsp;All Ladies Profiles
      </a>
    </li>
      <li className="list-group-item border-0 register-free-modal">
      <a href="/members/login/" className="fw-b2 nav-link rounded-pill border text-white bg-success border-warning py-2 my-2 px-2 my-sm-0" type="button" >     <i className="fa-solid fa-user"></i>&nbsp;&nbsp;Members Login
      </a>
    </li>
    <li className="list-group-item border-0 register-free-modal" >
      <a href="#" className="fw-b2 nav-link rounded-pill border text-white bg-success border-warning py-2 my-2 px-2 my-sm-0" type="button" data-toggle="modal" data-target=".poltava-women-modal">
        <i className="fa-solid fa-right-to-bracket"></i>&nbsp;&nbsp;Sign-up for FREE
      </a>
    </li>
 
  </div>
)}


    </div>
  )

};



//this funtion handle popUpMessage 
const PopMessage = () =>{
 const [messageCount, setMessageCount] = useState(0);
  const [newMailElements, setNewMailElements] = useState([]);
  const [currentElementIndex, setCurrentElementIndex] = useState(0);
  const [sendReplyHref, setSendReplyHref] = useState('');
    const [showElement, setShowElement] = useState(false);
 

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('https://acapulcowomen.com/members/mailbox');
        const html = await response.text();
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, 'text/html');
        const newMailElements = Array.from(doc.querySelectorAll('.mail-list-item')).map((element) => {
          return {
            element: element,
            outerHTML: element.outerHTML,
            textContent: element.textContent
          };
        });

        setMessageCount(newMailElements.length);
        setNewMailElements(newMailElements);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []);

  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentElementIndex(() => Math.floor(Math.random() * messageCount));
    }, 180000);

    return () => {clearInterval(timer);
    };
  }, [messageCount]);


   useEffect(() => {
    setShowElement(true);
    const timer = setTimeout(() => {
      setShowElement(false);
    }, 300000);

    return () => clearTimeout(timer);
  }, [currentElementIndex]);

//this code is to extract the href value
   useEffect(() => {
    if (newMailElements[currentElementIndex]) {
      const confirmOpenElement = newMailElements[currentElementIndex].element.querySelector('.confirm_open');
      const confirmOpenElementHref = confirmOpenElement ? confirmOpenElement.getAttribute('href') : '';
 
      setSendReplyHref(confirmOpenElementHref);
    }
  }, [currentElementIndex, newMailElements]);

const handleCloseMessage = () =>{
 setShowElement(false);
}





  return (
    <div>
 
      <ul>
          {newMailElements[currentElementIndex] && (
          <li  id="overideMessage" className={`shadow ${showElement ? 'slide-in ' : ''}`}>
           <div className="closeMessage">
            <p className="new-message">(New Message)</p>
            <p className="closePopMessage text-underline" onClick={handleCloseMessage}>close</p>
            </div>
            <div  dangerouslySetInnerHTML={{ __html: newMailElements[currentElementIndex].outerHTML }} />
               <a href={sendReplyHref} id="sendReply"><i className="fa fa-paper-plane" aria-hidden="true"></i> Send Reply</a>
      </li>
          )}
     
      </ul>
    </div>
  );
};


 ReactDOM.render(<PopMessage />, document.getElementById('popUpMessage'));
    ReactDOM.render(<CheckCredentials />, document.getElementById('accountNav'));
    ReactDOM.render(<App />, document.getElementById('desktopSearch'));
    ReactDOM.render(<App />, document.getElementById('mobileSearch'));