import React, { createContext, useContext, useState, useEffect, useCallback, useMemo } from 'react';
import { usePlatform } from '../platform';

const SearchContext = createContext(null);

export function SearchProvider({ children }) {
  const { searchDB, features } = usePlatform();
  const [isReady, setIsReady] = useState(false);
  const [initSignal, setInitSignal] = useState(0);

  const initialize = useCallback(() => {
    setInitSignal(s => s + 1);
  }, []);

  useEffect(() => {
    if (!features?.hasSearch || !searchDB) return;

    // Already open from a previous run
    if (searchDB.isOpen()) {
      setIsReady(true);
      return;
    }

    const dbKey = sessionStorage.getItem('searchDbKey');
    const userId = localStorage.getItem('userId');
    if (!dbKey || !userId) return;

    searchDB.open(dbKey, userId)
      .then(() => {
        setIsReady(true);
        console.log('Search DB initialized');
      })
      .catch(err => {
        console.error('Search DB init failed:', err);
      });

    const handleBeforeUnload = () => {
      if (searchDB.isOpen()) {
        searchDB.save();
      }
    };
    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => window.removeEventListener('beforeunload', handleBeforeUnload);
  }, [searchDB, features?.hasSearch, initSignal]);

  const indexMessages = useCallback((messages) => {
    if (!searchDB?.isOpen() || !messages?.length) return;
    searchDB.indexMessages(messages);
  }, [searchDB]);

  const search = useCallback((params) => {
    if (!searchDB?.isOpen()) return [];
    return searchDB.search(params);
  }, [searchDB]);

  const save = useCallback(async () => {
    if (searchDB?.isOpen()) {
      await searchDB.save();
    }
  }, [searchDB]);

  const value = useMemo(() => (
    { isReady, indexMessages, search, save, searchDB, initialize }
  ), [isReady, indexMessages, search, save, searchDB, initialize]);

  return (
    <SearchContext.Provider value={value}>
      {children}
    </SearchContext.Provider>
  );
}

export function useSearch() {
  return useContext(SearchContext);
}
