"use strict";

import { useCallback, useEffect, useRef, useState } from 'react';
import { createPlatformStorage } from '../utils/storageHelpers';
import { extractErrorMessage } from '../utils/errorHandlers';
const DEFAULT_ERROR_CODE = 'STORAGE_INIT_ERROR';

/**
 * React hook that exposes a platform-agnostic storage reference.
 * Handles initialization, error propagation, and lazy re-initialization.
 *
 * @param options - Optional configuration for error reporting and logging
 */
export const useStorage = ({
  onError,
  logger,
  errorCode = DEFAULT_ERROR_CODE
} = {}) => {
  const [storage, setStorage] = useState(null);
  const [error, setError] = useState(null);
  const initializingRef = useRef(null);
  const notifyError = useCallback(err => {
    const message = extractErrorMessage(err, 'Failed to initialize storage');
    setError(message);
    if (logger) {
      logger(message, err);
    }
    onError?.({
      message,
      code: errorCode,
      status: 500
    });
  }, [errorCode, logger, onError]);
  const createStorageInstance = useCallback(async () => {
    try {
      const platformStorage = await createPlatformStorage();
      setStorage(platformStorage);
      setError(null);
      return platformStorage;
    } catch (err) {
      notifyError(err);
      setStorage(null);
      return null;
    }
  }, [notifyError]);
  const refresh = useCallback(async () => {
    if (!initializingRef.current) {
      initializingRef.current = createStorageInstance().finally(() => {
        initializingRef.current = null;
      });
    }
    return initializingRef.current;
  }, [createStorageInstance]);
  useEffect(() => {
    refresh().catch(err => {
      notifyError(err);
    });
  }, [refresh, notifyError]);
  const withStorage = useCallback(async callback => {
    const resolvedStorage = storage ?? (await refresh());
    if (!resolvedStorage) {
      return null;
    }
    return callback(resolvedStorage);
  }, [refresh, storage]);
  return {
    storage,
    isReady: Boolean(storage) && !error,
    error,
    refresh,
    withStorage
  };
};
//# sourceMappingURL=useStorage.js.map