"use client";

import { useState, useEffect, useMemo } from "react";
import {
  retrieveRawInitData,
  retrieveLaunchParams,
} from "@telegram-apps/sdk-react";
import { getStartParamFromUrl } from "@/lib/launch-params";

/**
 * Whether the app is running on localhost (dev without Telegram).
 */
export function isLocalhost(): boolean {
  if (typeof window === "undefined") return false;
  const h = window.location.hostname;
  return h === "localhost" || h === "127.0.0.1" || h === "";
}

/**
 * Telegram auth and launch context for API and deep links.
 * Replaces webapp/js/auth.js getInitData, isLocalhost, and startParam detection.
 *
 * Uses imperative retrieveRawInitData/retrieveLaunchParams in useEffect so that
 * non-Telegram environments (e.g. browser) do not throw during render.
 * start_param is also read from URL (search/hash) as fallback when SDK is delayed.
 *
 * - initDataRaw: string for X-Telegram-Init-Data header (undefined when not in TWA)
 * - startParam: deep link param (e.g. "duty" for current duty view)
 * - isLocalhost: true when hostname is localhost/127.0.0.1 for dev without Telegram
 */
export function useTelegramAuth(): {
  initDataRaw: string | undefined;
  startParam: string | undefined;
  isLocalhost: boolean;
} {
  const urlStartParam = useMemo(() => getStartParamFromUrl(), []);
  const [initDataRaw, setInitDataRaw] = useState<string | undefined>(undefined);
  const [startParam, setStartParam] = useState<string | undefined>(urlStartParam);

  const localhost = useMemo(() => isLocalhost(), []);

  useEffect(() => {
    try {
      const raw = retrieveRawInitData();
      setInitDataRaw(raw ?? undefined);
      const lp = retrieveLaunchParams();
      const param =
        typeof lp.start_param === "string" ? lp.start_param : urlStartParam;
      setStartParam(param ?? urlStartParam ?? undefined);
    } catch {
      setInitDataRaw(undefined);
      setStartParam(urlStartParam ?? undefined);
    }
  }, [urlStartParam]);

  return {
    initDataRaw,
    startParam,
    isLocalhost: localhost,
  };
}
