'use client';

import { useEffect, useState } from 'react';

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

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

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 useResidentialProjectsFlag(): boolean {
  const [enabled, setEnabled] = useState<boolean>(readEnvDefault());

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

  return enabled;
}

// NOTE: The server-side helper lives in `@/lib/feature-flags/residential-projects`
// to avoid making it a client-only export (this file has `'use client'`).
