// Nordbank — apply-wizard state. Single reducer, persisted to localStorage.

const STORAGE_KEY = 'nordbank.application';

const INITIAL_APPLICATION = {
  step: 1,
  country: 'NO',
  currency: 'NOK',
  amount: 150000,
  termYears: 5,
  personal: {
    name: '', dob: '', ssn: '',
    email: '', phone: '',
    address: '', postcode: '', city: '',
  },
  employment: {
    status: '', employer: '', startDate: '',
    income: 0, otherDebts: 0, housing: '',
  },
  bankIdVerified: false,
  insuranceSelected: false,
  insurancePremium: 0,
  insuranceQuoteId: null,
  insuranceProductId: null,
  insurancePaid: false,
  insurancePolicyId: null,
  insuranceCheckoutSessionId: null,
  signed: false,
  termsAccepted: false,
  confirmationNumber: null,
  applicationId: null,
  accountCreated: false,
};

function loadApplication() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return { ...INITIAL_APPLICATION };
    const parsed = JSON.parse(raw);
    return { ...INITIAL_APPLICATION, ...parsed,
      personal:   { ...INITIAL_APPLICATION.personal,   ...(parsed.personal   || {}) },
      employment: { ...INITIAL_APPLICATION.employment, ...(parsed.employment || {}) },
    };
  } catch (e) {
    return { ...INITIAL_APPLICATION };
  }
}

function persistApplication(app) {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(app)); } catch (e) {}
}

function applicationReducer(state, action) {
  switch (action.type) {
    case 'SET_STEP':
      return { ...state, step: action.step };
    case 'NEXT_STEP':
      return { ...state, step: Math.min(6, state.step + 1) };
    case 'PREV_STEP':
      return { ...state, step: Math.max(1, state.step - 1) };
    case 'SET_COUNTRY': {
      const currency = COUNTRY_CURRENCY[action.country] || 'NOK';
      // Rescale loan amount when currency changes so 150 000 NOK becomes
      // ~15 000 EUR rather than an unchanged 150 000 EUR.
      const converted = convertAmount(state.amount, state.currency, currency);
      const amount = snapAmount(converted, currency);
      return { ...state, country: action.country, currency, amount };
    }
    case 'SET_AMOUNT':
      return { ...state, amount: action.amount };
    case 'SET_TERM':
      return { ...state, termYears: action.termYears };
    case 'SET_PERSONAL':
      return { ...state, personal: { ...state.personal, ...action.patch } };
    case 'SET_EMPLOYMENT':
      return { ...state, employment: { ...state.employment, ...action.patch } };
    case 'SET_BANKID_VERIFIED':
      return { ...state, bankIdVerified: !!action.value };
    case 'SET_INSURANCE': {
      // shape: { selected, premium, quoteId, productId }
      return {
        ...state,
        insuranceSelected: !!action.selected,
        insurancePremium: action.premium ?? 0,
        insuranceQuoteId: action.quoteId ?? null,
        insuranceProductId: action.productId ?? null,
        // If they toggle back to "no", clear any paid state too.
        insurancePaid: action.selected ? state.insurancePaid : false,
        insurancePolicyId: action.selected ? state.insurancePolicyId : null,
        insuranceCheckoutSessionId: action.selected ? state.insuranceCheckoutSessionId : null,
      };
    }
    case 'SET_INSURANCE_CHECKOUT':
      return {
        ...state,
        insuranceCheckoutSessionId: action.embedCheckoutSessionId,
        insurancePolicyId: action.policyId,
      };
    case 'SET_INSURANCE_PAID':
      return {
        ...state,
        insurancePaid: true,
        insurancePolicyId: action.policyId || state.insurancePolicyId,
      };
    case 'SET_TERMS':
      return { ...state, termsAccepted: !!action.value };
    case 'SET_SIGNED':
      return {
        ...state,
        signed: !!action.value,
        confirmationNumber: action.value ? (action.confirmationNumber || makeConfirmationNumber()) : null,
      };
    case 'SET_SIGNED_WITH':
      return {
        ...state,
        signed: true,
        confirmationNumber: action.confirmationNumber,
        applicationId: action.applicationId,
      };
    case 'SET_APPLICATION_ID':
      return { ...state, applicationId: action.id };
    case 'SET_ACCOUNT_CREATED':
      return { ...state, accountCreated: !!action.value };
    case 'RESET':
      return { ...INITIAL_APPLICATION };
    case 'HYDRATE':
      return { ...state, ...action.state };
    default:
      return state;
  }
}

// Hook: returns [state, dispatch], persists every change.
function useApplication() {
  const [state, dispatch] = React.useReducer(applicationReducer, null, loadApplication);
  React.useEffect(() => { persistApplication(state); }, [state]);
  return [state, dispatch];
}

Object.assign(window, {
  STORAGE_KEY,
  INITIAL_APPLICATION,
  loadApplication,
  persistApplication,
  applicationReducer,
  useApplication,
});
