import React, { useEffect, useMemo, useRef, useState } from 'react';
import { OpChanClient } from '@opchan/core';
import { localDatabase, messageManager } from '@opchan/core';
import { AuthProvider } from '../contexts/AuthContext';
import { ForumProvider } from '../contexts/ForumContext';
import { ModerationProvider } from '../contexts/ModerationContext';

export interface OpChanProviderProps {
  ordiscanApiKey: string;
  debug?: boolean;
  children: React.ReactNode;
}

export const OpChanProvider: React.FC<OpChanProviderProps> = ({
  ordiscanApiKey,
  debug,
  children,
}) => {
  const [isReady, setIsReady] = useState(false);
  const clientRef = useRef<OpChanClient | null>(null);

  useEffect(() => {
    let cancelled = false;

    const init = async () => {
      if (typeof window === 'undefined') return; // SSR guard

      // Configure environment and create client
      const client = new OpChanClient({
        ordiscanApiKey,
        debug: !!debug,
        isDevelopment: !!debug,
      });
      clientRef.current = client;

      // Open local DB early for warm cache
      await localDatabase.open().catch(console.error);


      if (!cancelled) setIsReady(true);
    };

    init();
    return () => {
      cancelled = true;
    };
  }, [ordiscanApiKey, debug]);

  const providers = useMemo(() => {
    if (!isReady || !clientRef.current) return null;
    return (
      <AuthProvider client={clientRef.current}>
        <ModerationProvider>
          <ForumProvider client={clientRef.current}>{children}</ForumProvider>
        </ModerationProvider>
      </AuthProvider>
    );
  }, [isReady, children]);

  return providers || null;
};


