import { useEffect, useState } from 'react';
import { getPlatformAccessToken } from '../lib/authSession';
import { tradingRuntime } from '../lib/runtime';
import { createRequestId } from '../../../shared/request-id.js';
import type { TabFeatureFlags, TradingFeatureFlagsResponse } from '../../../shared/feature-flags.js';

const DEFAULT_FLAGS: TabFeatureFlags = {
  marketplace: true,
  membership: true,
};

const CACHE_TTL_MS = 30_000;
let cachedFlags: TabFeatureFlags | null = null;
let cachedAt = 0;

export function resetTabFeatureFlagsCacheForTests(): void {
  cachedFlags = null;
  cachedAt = 0;
}

async function loadTabFlags(): Promise<TabFeatureFlags> {
  const now = Date.now();
  if (cachedFlags && now - cachedAt < CACHE_TTL_MS) {
    return cachedFlags;
  }

  const accessToken = await getPlatformAccessToken().catch(() => null);
  if (!accessToken) return DEFAULT_FLAGS;

  const response = await fetch(`${tradingRuntime.tradingApiUrl}/api/feature-flags`, {
    headers: {
      Authorization: `Bearer ${accessToken}`,
      'x-request-id': createRequestId('web-tab-flags'),
    },
  });
  if (!response.ok) return DEFAULT_FLAGS;

  const body = (await response.json().catch(() => null)) as TradingFeatureFlagsResponse | null;
  const flags: TabFeatureFlags = {
    marketplace: body?.tabs?.marketplace ?? true,
    membership: body?.tabs?.membership ?? true,
  };

  cachedFlags = flags;
  cachedAt = Date.now();
  return flags;
}

export interface UseTabFeatureFlagsResult {
  flags: TabFeatureFlags;
  loading: boolean;
}

export function useTabFeatureFlags(): UseTabFeatureFlagsResult {
  const [flags, setFlags] = useState<TabFeatureFlags>(DEFAULT_FLAGS);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    loadTabFlags()
      .then((f) => { if (!cancelled) setFlags(f); })
      .catch(() => { if (!cancelled) setFlags(DEFAULT_FLAGS); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, []);

  return { flags, loading };
}
