import storageAvailable from 'storage-available';

const TEN_MINUTES_MS = 600000;

export type UnexpiredPromptResult =
  | { hasUnexpiredPrompt: true; prompt: string }
  | { hasUnexpiredPrompt: false; prompt: null };

/**
 * Utility function to check if there's an unexpired prompt from the quickbox in localStorage
 * A prompt is considered unexpired if:
 * - It exists in localStorage
 * - It was saved less than 10 minutes ago
 * - Its source was 'quickbox'
 *
 * Returns both the boolean check and the prompt value (if unexpired).
 * This can be used directly in effects or other non-hook contexts.
 */
export function getUnexpiredPrompt(): UnexpiredPromptResult {
  if (typeof window === 'undefined' || !storageAvailable('localStorage')) {
    return {
      hasUnexpiredPrompt: false,
      prompt: null,
    };
  }

  const prompt = localStorage.getItem('prompt');
  const promptSavedAt = localStorage.getItem('prompt_saved_at');
  const promptSource = localStorage.getItem('prompt_source');

  const isUnexpired =
    !!prompt &&
    Date.now() - (parseInt(promptSavedAt || '') || 0) < TEN_MINUTES_MS &&
    promptSource === 'quickbox';

  if (isUnexpired) {
    return {
      hasUnexpiredPrompt: true,
      prompt: prompt,
    };
  }

  return {
    hasUnexpiredPrompt: false,
    prompt: null,
  };
}

/**
 * Hook version that returns the full result object with type discrimination
 * Use this in React components at the component level
 */

// note: this is kinda dumb. it only checks on render. this is ok for now but should probably rearchitect to use `useLocalStorage` for instant propagation when prompt stuff changes.
export function useHasUnexpiredPrompt(): UnexpiredPromptResult {
  return getUnexpiredPrompt();
}

/**
 * Exported constant for other uses
 */
export const PROMPT_EXPIRY_MS = TEN_MINUTES_MS;
