'use client';

/**
 * Zustand store for configurable currency.
 *
 * Persists the selected currency to localStorage so it survives page refreshes.
 * Used by the Super Admin settings page to configure which currency is displayed
 * across all financial charts and KPIs in the dashboard.
 */

import { create } from 'zustand';

export interface CurrencyOption {
  code: string;   // ISO 4217 code: 'USD', 'EUR', 'GBP', etc.
  symbol: string; // '$', '€', '£', etc.
  name: string;   // 'US Dollar', 'Euro', 'British Pound', etc.
}

export const CURRENCY_OPTIONS: CurrencyOption[] = [
  { code: 'USD', symbol: '$', name: 'US Dollar' },
  { code: 'EUR', symbol: '€', name: 'Euro' },
  { code: 'GBP', symbol: '£', name: 'British Pound' },
  { code: 'CLP', symbol: 'CLP', name: 'Chilean Peso' },
  { code: 'BRL', symbol: 'R$', name: 'Brazilian Real' },
  { code: 'MXN', symbol: 'MX$', name: 'Mexican Peso' },
  { code: 'ARS', symbol: 'AR$', name: 'Argentine Peso' },
  { code: 'COP', symbol: 'COL$', name: 'Colombian Peso' },
  { code: 'PEN', symbol: 'S/', name: 'Peruvian Sol' },
  { code: 'JPY', symbol: '¥', name: 'Japanese Yen' },
];

export interface CurrencyState {
  currency: CurrencyOption;
  setCurrency: (currency: CurrencyOption) => void;
}

function getInitialCurrency(): CurrencyOption {
  if (typeof window !== 'undefined') {
    try {
      const stored = localStorage.getItem('divisi-currency');
      if (stored) {
        const parsed = JSON.parse(stored);
        const found = CURRENCY_OPTIONS.find((c) => c.code === parsed.code);
        if (found) return found;
      }
    } catch { /* ignore */ }
  }
  return CURRENCY_OPTIONS[0]; // USD default
}

export const useCurrencyStore = create<CurrencyState>()((set) => ({
  currency: getInitialCurrency(),
  setCurrency: (currency) => {
    if (typeof window !== 'undefined') {
      try {
        localStorage.setItem('divisi-currency', JSON.stringify(currency));
      } catch { /* ignore */ }
    }
    set({ currency });
  },
}));
