"use client";

import { useEffect, useState } from "react";

import {
  selectTipSupportPrompt,
  TIP_SUPPORT_PROMPTS,
} from "@/lib/tip/tip_support_prompts";

const LAST_TIP_SUPPORT_PROMPT_INDEX_KEY =
  "cozsweet.tip.last_support_prompt_index";

export interface TipSupportPromptState {
  readonly prompt: string;
  readonly isReady: boolean;
}

export function useTipSupportPrompt(
  characterName = "this character",
): TipSupportPromptState {
  const [selection, setSelection] =
    useState<ReturnType<typeof selectTipSupportPrompt> | null>(null);

  useEffect(() => {
    const frameId = requestAnimationFrame(() => {
      const nextSelection = selectTipSupportPrompt(
        readPreviousIndex(),
        Math.random,
        characterName,
      );
      writePreviousIndex(nextSelection.index);
      setSelection(nextSelection);
    });

    return () => cancelAnimationFrame(frameId);
  }, [characterName]);

  return {
    prompt:
      selection?.prompt ??
      TIP_SUPPORT_PROMPTS[0].replaceAll("this character", characterName),
    isReady: selection !== null,
  };
}

function readPreviousIndex(): number | null {
  try {
    const value = globalThis.sessionStorage.getItem(
      LAST_TIP_SUPPORT_PROMPT_INDEX_KEY,
    );
    if (value === null) return null;
    const index = Number(value);
    return Number.isInteger(index) ? index : null;
  } catch {
    return null;
  }
}

function writePreviousIndex(index: number): void {
  try {
    globalThis.sessionStorage.setItem(
      LAST_TIP_SUPPORT_PROMPT_INDEX_KEY,
      String(index),
    );
  } catch {
    // Random copy remains usable when storage is unavailable.
  }
}
