popraw mi ten plik uwzględniając wszystkie 5 punktów które podałeś: import { createContext, useContext, useState, useCallback, useEffect, type ChangeEvent, type FormEvent } from 'react';
import type { GoalItem, GoalField } from '../components/goals/types';
import type { ExtendedProfileState } from '../components/profile-user/types.ts';
import type { GoalFieldErrors } from "../types/forms.ts";
import { useFetchCountries, normalizeLocale } from '../hooks/useFetchCountries'; // dostosuj ścieżkę

type CalculationContextType = {
    // Profile
    state: ExtendedProfileState;
    setState: (state: ExtendedProfileState) => void;

    // Profile form handlers
    handleProfileChange: (field: string, e: ChangeEvent<any>) => void;
    handleProfileSubmit: (e: FormEvent<any>) => void;

    // Countries data
    loadingCountries: boolean;
    userCountryCode?: string;

    // User & Calculation ID
    user: string;
    setUser: (val: string) => void;
    calcNumber: string;
    setCalcNumber: (val: string) => void;

    // Financial summaries
    goals: GoalItem[];
    setGoals: (goals: GoalItem[]) => void;
    addRow: () => void;
    deleteRow: (id: string) => void;
    updateField: (id: string, field: GoalField, value: string) => void;
    totalGoalsMonthly: number;
    setTotalGoalsMonthly: (val: number) => void;
    totalIncomesMonthly: number;
    setTotalIncomesMonthly: (val: number) => void;
    totalExpensesMonthly: number;
    setTotalExpensesMonthly: (val: number) => void;

    // Locale/currency
    currency: string;
    locale: string;
    setCurrency: (val: string) => void;
    setLocale: (val: string) => void;

    // Reset function
    resetCalculationData: () => void;
};

export const CalculationContext = createContext<CalculationContextType | undefined>(undefined);

type Props = {
    children: React.ReactNode;
};

export const CalculationProvider = ({ children }: Props) => {
    // Pobieranie danych krajów
    const {
        loading: loadingCountries,
        countries,
        currencyOptions,
        countryToLocale,
        currenciesMap,
        userCountryCode,
    } = useFetchCountries(normalizeLocale);

    // Profile state
    const [state, setState] = useState<ExtendedProfileState>({
        name: '',
        calcNumber: '',
        country: '',
        currency: '',
        errors: {},
        countriesList: [],
        currenciesMap: {},
        countryToLocale: {},
        currencyOptions: [],
    });

    // Identity
    const [user, setUser] = useState('');
    const [calcNumber, setCalcNumber] = useState('');

    // Financial data
    const [goals, setGoals] = useState<GoalItem[]>([]);
    const [totalGoalsMonthly, setTotalGoalsMonthly] = useState(0);
    const [totalIncomesMonthly, setTotalIncomesMonthly] = useState(0);
    const [totalExpensesMonthly, setTotalExpensesMonthly] = useState(0);

    // Currency and locale
    const [currency, setCurrency] = useState('');
    const [locale, setLocale] = useState('');

    // Aktualizacja stanu profilu gdy dane krajów się załadują
    useEffect(() => {
        if (!loadingCountries) {
            setState(prev => ({
                ...prev,
                countriesList: countries,
                currencyOptions,
                countryToLocale,
                currenciesMap,
            }));

            // Automatyczne ustawienie kraju użytkownika jeśli został wykryty
            if (userCountryCode && !prev.country) {
                setState(prev => ({
                    ...prev,
                    country: userCountryCode,
                }));

                // Automatyczne ustawienie waluty na podstawie kraju
                const detectedCurrency = currenciesMap[userCountryCode];
                if (detectedCurrency && !prev.currency) {
                    setState(prev => ({
                        ...prev,
                        currency: detectedCurrency,
                    }));
                    setCurrency(detectedCurrency);
                }

                // Automatyczne ustawienie locale na podstawie kraju
                const detectedLocale = countryToLocale[userCountryCode];
                if (detectedLocale) {
                    setLocale(detectedLocale);
                }
            }
        }
    }, [loadingCountries, countries, currencyOptions, countryToLocale, currenciesMap, userCountryCode]);

    // Profile form handlers
    const handleProfileChange = useCallback((field: string, e: ChangeEvent<any>) => {
        const value = e.target.value;

        setState(prev => {
            const newState = {
                ...prev,
                [field]: value,
                errors: {
                    ...prev.errors,
                    [field]: '' // Wyczyść błąd dla tego pola
                }
            };

            // Automatyczne ustawienie locale gdy zmienia się kraj
            if (field === 'country' && value) {
                const newLocale = prev.countryToLocale[value];
                if (newLocale) {
                    setLocale(newLocale);
                }

                // Automatyczne ustawienie waluty na podstawie kraju
                const countryCurrency = prev.currenciesMap[value];
                if (countryCurrency) {
                    newState.currency = countryCurrency;
                    setCurrency(countryCurrency);
                }
            }

            // Aktualizacja globalnej waluty gdy zmienia się waluta w profilu
            if (field === 'currency' && value) {
                setCurrency(value);
            }

            return newState;
        });
    }, []);

    const handleProfileSubmit = useCallback((e: FormEvent<any>) => {
        e.preventDefault();

        // Walidacja
        const errors: Record<string, string> = {};

        if (!state.name.trim()) {
            errors.name = 'Name is required';
        }
        if (!state.calcNumber) {
            errors.calcNumber = 'Calculation number is required';
        }
        if (!state.country) {
            errors.country = 'Country is required';
        }
        if (!state.currency) {
            errors.currency = 'Currency is required';
        }

        if (Object.keys(errors).length > 0) {
            setState(prev => ({ ...prev, errors }));
            return;
        }

        // Aktualizacja głównych wartości kontekstu
        setUser(state.name);
        setCalcNumber(state.calcNumber);
        setCurrency(state.currency);

        // Ustawienie locale na podstawie kraju
        const selectedLocale = state.countryToLocale[state.country];
        if (selectedLocale) {
            setLocale(selectedLocale);
        }

        console.log('Profile submitted successfully:', {
            name: state.name,
            calcNumber: state.calcNumber,
            country: state.country,
            currency: state.currency,
            locale: selectedLocale
        });

        // Tutaj możesz dodać dodatkową logikę po udanym submicie
        // np. przekierowanie, pokazanie powiadomienia, itp.
    }, [state]);

    // Add a new empty goal row
    const addRow = () => {
        setGoals(prev => [
            ...prev,
            {
                id: crypto.randomUUID(),
                goal: '',
                year: '',
                amount: '',
                errors: {
                    name: '',
                    year: '',
                    amount: '',
                },
            },
        ]);
    };

    // Delete a goal by id
    const deleteRow = (id: string) => {
        setGoals(prev => prev.filter(goal => goal.id !== id));
    };

    // Update a specific field in a goal by id
    const updateField = (id: string, field: GoalField, value: string | GoalFieldErrors) => {
        setGoals(prevGoals =>
            prevGoals.map(goal => {
                if (goal.id !== id) return goal;

                if (field === 'errors') {
                    return { ...goal, errors: value as GoalFieldErrors };
                }
                return { ...goal, [field]: value as string};
            })
        );
    };

    // Reset function
    const resetCalculationData = () => {
        setTotalGoalsMonthly(0);
        setTotalIncomesMonthly(0);
        setTotalExpensesMonthly(0);
        setUser('');
        setCalcNumber('');
        setGoals([]);
        setCurrency('');
        setLocale('');

        // Reset profilu do stanu początkowego (zachowując dane krajów)
        setState(prev => ({
            ...prev,
            name: '',
            calcNumber: '',
            country: userCountryCode || '',
            currency: userCountryCode ? prev.currenciesMap[userCountryCode] || '' : '',
            errors: {},
        }));
    };

    const value: CalculationContextType = {
        state,
        setState,
        handleProfileChange,
        handleProfileSubmit,
        loadingCountries,
        userCountryCode,
        user,
        setUser,
        calcNumber,
        setCalcNumber,
        goals,
        setGoals,
        addRow,
        deleteRow,
        updateField,
        totalGoalsMonthly,
        setTotalGoalsMonthly,
        totalIncomesMonthly,
        setTotalIncomesMonthly,
        totalExpensesMonthly,
        setTotalExpensesMonthly,
        currency,
        locale,
        setCurrency,
        setLocale,
        resetCalculationData,
    };

    return (
        <CalculationContext.Provider value={value}>
            {children}
        </CalculationContext.Provider>
    );
};

export const useCalculationContext = () => {
    const context = useContext(CalculationContext);
    if (!context) {
        throw new Error('useCalculationContext must be used within a CalculationProvider');
    }
    return context;
};