'use client';

import { useEffect, useState } from 'react';

const LOCAL_STORAGE_KEY = 'goodgo:avm_v2';
const QUERY_PARAM = 'avm_v2';

function readEnvDefault(): boolean {
  const raw = process.env['NEXT_PUBLIC_FEATURE_AVM_V2'];
  if (!raw) return false;
  return raw === '1' || raw.toLowerCase() === 'true';
}

function readOverride(): boolean | null {
  if (typeof window === 'undefined') return null;

  const params = new URLSearchParams(window.location.search);
  const qp = params.get(QUERY_PARAM);
  if (qp === '1' || qp === 'true') {
    try {
      window.localStorage.setItem(LOCAL_STORAGE_KEY, '1');
    } catch {
      // localStorage may be blocked — ignore
    }
    return true;
  }
  if (qp === '0' || qp === 'false') {
    try {
      window.localStorage.setItem(LOCAL_STORAGE_KEY, '0');
    } catch {
      // localStorage may be blocked — ignore
    }
    return false;
  }

  try {
    const stored = window.localStorage.getItem(LOCAL_STORAGE_KEY);
    if (stored === '1') return true;
    if (stored === '0') return false;
  } catch {
    // ignore
  }
  return null;
}

export function useAvmV2Flag(): boolean {
  const [enabled, setEnabled] = useState<boolean>(readEnvDefault());

  useEffect(() => {
    const override = readOverride();
    setEnabled(override ?? readEnvDefault());
  }, []);

  return enabled;
}
