import type { AppLocale } from "./config";

export type WizardLocale = AppLocale;

type LabelTree = {
  [key: string]: string | LabelTree;
};

const labels: Record<WizardLocale, LabelTree> = {
  uz: {
    steps: {
      ACCOUNT: "Hisob",
      CONSENT: "Rozilik",
      KYC: "Shaxs",
      FARM_PROFILE: "Profil",
      LAND_SKETCH: "Yer",
      GIS_MAPPING: "GIS xarita",
      CROP_PLAN: "Ekinlar",
      FARM_ASSETS: "Aktivlar",
      DOCUMENTS: "Hujjatlar",
      FINANCE_REQUEST: "Moliya",
      REVIEW: "Tekshiruv",
      SCORING: "Baholash",
      RESULT: "Natija",
    },
    common: {
      saveContinue: "Saqlash va davom etish",
      saving: "Saqlanmoqda...",
      select: "Tanlang",
      required: "Majburiy",
      optional: "Ixtiyoriy",
      addAnother: "Yana qo'shish",
      skip: "O'tkazib yuborish",
      complete: "Tugallangan",
      pending: "Kutilmoqda",
    },
    consent: {
      title: "Rozilik va oshkor qilish",
      subtitle: "Ariza uchun quyidagi roziliklarni ko'rib chiqing va qabul qiling.",
      privacyNote:
        "Ma'lumotlaringiz himoyalangan va faqat quyida ko'rsatilgan maqsadlarda ishlatiladi. Rozilikni istalgan vaqtda bekor qilishingiz mumkin.",
      localeLabel: "Rozilik tili",
      acceptContinue: "Qabul qilish va davom etish",
    },
    kyc: {
      finishLater: "Keyinroq tugatish — kirish sahifasiga",
      finishLaterHint: "Qolgan qadamlarni kirish sahifasidan davom ettirishingiz mumkin.",
    },
    farmProfile: {
      title: "Ferma profili",
      subtitle: "O'zingiz haqingizda ma'lumot bering. Bu sizga mos moliyaviy mahsulotlarni tanlashga yordam beradi.",
      fullName: "To'liq ism",
      fullNamePlaceholder: "To'liq ismingiz",
      dateOfBirth: "Tug'ilgan sana",
      gender: "Jins",
      region: "Viloyat",
      district: "Tuman",
      selectRegion: "Viloyatni tanlang",
      selectDistrict: "Tumanni tanlang",
      householdSize: "Oiladagi odamlar soni",
      education: "Ma'lumot",
      yearsFarming: "Fermerlik tajribasi (yil)",
      farmerType: "Fermer turi",
      primaryLanguage: "Asosiy til",
      completeRequiredHint: "Davom etish uchun quyidagi maydonlarni to'ldiring:",
      loadingDistricts: "Tumanlar yuklanmoqda...",
    },
    landSketch: {
      title: "Yer ma'lumotlari",
      subtitle: "Asosiy dehqonchilik yeringiz haqida ma'lumot bering.",
      agentNote:
        "Kadastr yoki e-Ijara raqamingiz bo'lsa, kiriting. Aks holda AGNET maydon agenti GIS xaritalashda yordam beradi.",
      parcel: "Yer uchastkasi",
      primaryParcel: "Asosiy uchastka",
      district: "Tuman",
      village: "Qishloq",
      areaHa: "Maydon (gektar)",
      tenureType: "Egalik turi",
      landUseType: "Yer foydalanish turi",
      irrigationSource: "Sug'orish manbai",
      registryRef: "Kadastr raqami (ixtiyoriy)",
    },
    gisMapping: {
      title: "GIS uchastka xaritasi",
      subtitle:
        "Sun'iy yo'ldosh tahlili uchun koordinatalarni kiriting yoki maydon agenti keyinroq chegaralarni belgilaydi.",
      coordinates: "Ferma koordinatalari",
      coordinatesHint: "Hosildorlik prognozi va kredit baholash uchun ishlatiladi",
      useLocation: "Joriy joylashuvni ishlatish",
      detecting: "Joylashuv aniqlanmoqda...",
      latitude: "Kenglik",
      longitude: "Uzunlik",
      accuracy: "Aniqlik",
      parcelLink: "Bog'langan uchastka",
      captured: "Koordinatalar qabul qilindi — baholash vaqtida tahlil qilinadi",
      skipAgent: "O'tkazish (agent keyinroq xaritalaydi)",
    },
    cropPlan: {
      title: "Ekin va mavsum rejasi",
      subtitle: "Joriy yoki kelgusi mavsum uchun rejalashtirilgan ekinlarni qo'shing.",
      crop: "Ekin",
      season: "Mavsum",
      areaHa: "Maydon (gektar)",
      expectedYield: "Kutilayotgan hosil (tonna)",
      areaWarning: "Ekin maydonlari jami e'lon qilingan yerdan oshib ketdi",
      areaRemaining: "Qolgan maydon",
      completeRequiredHint: "Davom etish uchun quyidagi maydonlarni to'ldiring:",
      reduceAreaHint: "Ekin maydonlari e'lon qilingan yerdan oshib ketdi — maydonlarni kamaytiring.",
    },
    finance: {
      title: "Moliyaviy so'rov",
      subtitle: "Moliyalashtirish ehtiyojingiz haqida ma'lumot bering.",
      purpose: "Moliyalashtirish maqsadi",
      amountUzs: "So'ralayotgan summa (so'm)",
      monthlyIncomeUzs: "Oylik daromad (so'm)",
      existingLoansUzs: "Mavjud kreditlar (so'm)",
      termMonths: "Muddat (oy)",
      repaymentHistory: "Oldingi kredit to'lovlari",
      fxSnapshot: "Valyuta kursi",
      fxNote: "USD institut hisobotlari uchun hisoblanadi",
      prefilled: "Ba'zi maydonlar yuklangan hujjatlardan to'ldirildi",
      autoFilled: "avto-to'ldirilgan",
    },
    review: {
      title: "Ko'rib chiqish va yuborish",
      subtitle: "Baholashga yuborishdan oldin arizangizni tekshiring.",
      identity: "Shaxsiy ma'lumotlar",
      land: "Yer",
      crops: "Ekinlar",
      assets: "Aktivlar",
      finance: "Moliya",
      documents: "Hujjatlar",
      attestation:
        "Men taqdim etilgan ma'lumotlar to'g'ri ekanligini tasdiqlayman va AGNET ularni kredit baholash va moliyalashtirish uchun ishlatishiga roziman.",
      submit: "Arizani yuborish",
      submitting: "Yuborilmoqda...",
    },
    scoring: {
      processing: "Arizangiz qayta ishlanmoqda...",
      complete: "Baholash tugallandi!",
      processingHint:
        "Sun'iy yo'ldosh tahlili, hujjatlar tekshiruvi va kredit baholash o'tkazilmoqda.",
      completeHint: "Natijalar tayyor. Keyingi bosqichga o'tilmoqda...",
      keyFactors: "Asosiy omillar",
      phaseGeo: "Sun'iy yo'ldosh tahlili (Prithvi)",
      phaseDocuments: "Hujjatlar tekshiruvi",
      phaseScoring: "Kredit baholash",
      satellitePreview: "Sun'iy yo'ldosh tasvirlari",
      explanationPreview: "Sizning baholashingiz haqida",
      showExplanation: "Batafsil ko'rish",
      hideExplanation: "Yashirish",
      failed: "Baholash muvaffaqiyatsiz tugadi",
      failedHint: "Texnik xatolik yuz berdi. Qayta urinib ko'ring yoki qo'llab-quvvatlash bilan bog'laning.",
      timeout: "Baholash vaqti tugadi",
      timeoutHint: "Tahlil kutilganidan uzoqroq davom etmoqda. Qayta urinib ko'ring.",
      retry: "Qayta urinish",
      baselPd: "Standartlashtirilgan PD",
      riskRating: "Xavf reytingi",
      ifrs9Stage: "IFRS 9 bosqichi",
      cbuClass: "KBU sinfi",
    },
    result: {
      eligible: "Siz mos kelasiz!",
      conditional: "Shartli moslik",
      notEligible: "Mos emas",
      eligibleHint:
        "Tabriklaymiz! Ferma ma'lumotlaringiz va GEO baholash asosida AGNET moliyalashtirish pilotiga mos kelasiz.",
      conditionalHint:
        "Arizangiz uchun qo'shimcha hujjatlar kerak. Maydon agenti siz bilan bog'lanadi.",
      notEligibleHint: "Afsuski, arizangiz joriy moslik mezonlariga javob bermaydi.",
      creditScore: "Kredit balli",
      financeCase: "Moliya arizasi raqami",
      caseStatus: "Holat",
      requirements: "Kerakli harakatlar",
      goDashboard: "Boshqaruv paneliga",
      goLogin: "Kirish sahifasiga",
      finishing: "Yakunlanmoqda...",
      farmerExplanation: "Nima uchun bu ball?",
      scoreGaugeLabel: "Kredit balli ko'rsatkichi",
    },
    enums: {
      gender: {
        male: "Erkak",
        female: "Ayol",
        prefer_not_to_say: "Aytishni xohlamayman",
      },
      farmerType: {
        owner: "Yer egasi",
        tenant: "Ijarachi",
        family_farm: "Oilaviy ferma",
        cooperative_member: "Kooperativ a'zosi",
      },
      education: {
        none: "Yo'q",
        primary: "Boshlang'ich",
        secondary: "O'rta",
        vocational: "Kasb-hunar",
        university: "Oliy",
      },
      tenureType: {
        owned: "Egasiga tegishli",
        leased: "Ijara",
        sharecrop: "Ulushdor",
        communal: "Jamoat",
        inheritance: "Meros",
      },
      landUseType: {
        irrigated_cropland: "Sug'oriladigan ekinzor",
        rainfed: "Yomg'irli ekinzor",
        orchard: "Bog'",
        pasture: "Yaylov",
        greenhouse: "Issiqxona",
      },
      irrigationSource: {
        canal: "Kanal",
        well: "Quduq",
        drip: "Tomchilatib sug'orish",
        rainfed: "Yomg'ir",
        mixed: "Aralash",
      },
      repaymentHistory: {
        none: "Oldingi kreditlar yo'q",
        good: "Yaxshi (vaqtida to'langan)",
        fair: "O'rtacha (kechikishlar bo'lgan)",
        poor: "Yomon (to'lanmagan)",
      },
      season: {
        spring: "Bahor",
        summer: "Yoz",
        autumn: "Kuz",
        winter: "Qish",
      },
      financeCaseStatus: {
        pending: "Kutilmoqda",
        under_review: "Ko'rib chiqilmoqda",
        approved: "Tasdiqlangan",
        rejected: "Rad etilgan",
      },
    },
  },
  ru: {
    steps: {
      ACCOUNT: "Аккаунт",
      CONSENT: "Согласие",
      KYC: "Личность",
      FARM_PROFILE: "Профиль",
      LAND_SKETCH: "Земля",
      GIS_MAPPING: "GIS карта",
      CROP_PLAN: "Культуры",
      FARM_ASSETS: "Активы",
      DOCUMENTS: "Документы",
      FINANCE_REQUEST: "Финансы",
      REVIEW: "Проверка",
      SCORING: "Оценка",
      RESULT: "Результат",
    },
    common: {
      saveContinue: "Сохранить и продолжить",
      saving: "Сохранение...",
      select: "Выберите",
      required: "Обязательно",
      optional: "Необязательно",
      addAnother: "Добавить ещё",
      skip: "Пропустить",
      complete: "Готово",
      pending: "Ожидает",
    },
    consent: {
      title: "Согласие и раскрытие информации",
      subtitle: "Просмотрите и примите следующие согласия для продолжения заявки.",
      privacyNote:
        "Ваши данные защищены и используются только в указанных ниже целях. Вы можете отозвать согласие в любое время.",
      localeLabel: "Язык согласия",
      acceptContinue: "Принять и продолжить",
    },
    kyc: {
      finishLater: "Завершить позже — на страницу входа",
      finishLaterHint: "Остальные шаги можно пройти со страницы входа.",
    },
    farmProfile: {
      title: "Профиль фермера",
      subtitle: "Расскажите о себе. Это поможет подобрать подходящие финансовые продукты.",
      fullName: "Полное имя",
      fullNamePlaceholder: "Ваше полное имя",
      dateOfBirth: "Дата рождения",
      gender: "Пол",
      region: "Область",
      district: "Район",
      selectRegion: "Выберите область",
      selectDistrict: "Выберите район",
      householdSize: "Размер домохозяйства",
      education: "Образование",
      yearsFarming: "Стаж фермерства (лет)",
      farmerType: "Тип фермера",
      primaryLanguage: "Основной язык",
      completeRequiredHint: "Заполните следующие поля, чтобы продолжить:",
      loadingDistricts: "Загрузка районов...",
    },
    landSketch: {
      title: "Информация о земле",
      subtitle: "Укажите данные об основной сельхозземле.",
      agentNote:
        "Если есть кадастровый или e-Ijara номер, введите его. Иначе полевой агент AGNET поможет с GIS-картированием.",
      parcel: "Земельный участок",
      primaryParcel: "Основной участок",
      district: "Район",
      village: "Село",
      areaHa: "Площадь (га)",
      tenureType: "Тип владения",
      landUseType: "Тип использования",
      irrigationSource: "Источник орошения",
      registryRef: "Кадастровый номер (необяз.)",
    },
    gisMapping: {
      title: "GIS-картирование участка",
      subtitle:
        "Укажите координаты для спутникового анализа или пропустите — границы отметит полевой агент.",
      coordinates: "Координаты фермы",
      coordinatesHint: "Используются для прогноза урожайности и кредитной оценки",
      useLocation: "Использовать текущее местоположение",
      detecting: "Определение местоположения...",
      latitude: "Широта",
      longitude: "Долгота",
      accuracy: "Точность",
      parcelLink: "Связанный участок",
      captured: "Координаты получены — анализ выполнится при оценке",
      skipAgent: "Пропустить (агент сделает позже)",
    },
    cropPlan: {
      title: "План культур и сезона",
      subtitle: "Добавьте планируемые культуры на текущий или следующий сезон.",
      crop: "Культура",
      season: "Сезон",
      areaHa: "Площадь (га)",
      expectedYield: "Ожидаемый урожай (т)",
      areaWarning: "Сумма площадей культур превышает заявленную землю",
      areaRemaining: "Остаток площади",
      completeRequiredHint: "Заполните следующие поля, чтобы продолжить:",
      reduceAreaHint: "Площади культур превышают заявленную землю — уменьшите значения.",
    },
    finance: {
      title: "Финансовый запрос",
      subtitle: "Расскажите о ваших потребностях в финансировании.",
      purpose: "Цель финансирования",
      amountUzs: "Запрашиваемая сумма (сум)",
      monthlyIncomeUzs: "Ежемесячный доход (сум)",
      existingLoansUzs: "Существующие кредиты (сум)",
      termMonths: "Срок (мес.)",
      repaymentHistory: "История погашения кредитов",
      fxSnapshot: "Курс валюты",
      fxNote: "USD рассчитывается для отчётности институтов",
      prefilled: "Некоторые поля заполнены из загруженных документов",
      autoFilled: "авто-заполнено",
    },
    review: {
      title: "Проверка и отправка",
      subtitle: "Проверьте заявку перед отправкой на оценку.",
      identity: "Личные данные",
      land: "Земля",
      crops: "Культуры",
      assets: "Активы",
      finance: "Финансы",
      documents: "Документы",
      attestation:
        "Я подтверждаю, что предоставленные данные верны, и согласен на их использование AGNET для кредитной оценки и финансирования.",
      submit: "Отправить заявку",
      submitting: "Отправка...",
    },
    scoring: {
      processing: "Обработка заявки...",
      complete: "Оценка завершена!",
      processingHint:
        "Выполняется спутниковый анализ, проверка документов и кредитная оценка.",
      completeHint: "Результаты готовы. Переход к следующему шагу...",
      keyFactors: "Ключевые факторы",
      phaseGeo: "Спутниковый анализ (Prithvi)",
      phaseDocuments: "Проверка документов",
      phaseScoring: "Кредитная оценка",
      satellitePreview: "Спутниковые снимки",
      explanationPreview: "О вашей оценке",
      showExplanation: "Подробнее",
      hideExplanation: "Скрыть",
      failed: "Оценка не выполнена",
      failedHint: "Произошла техническая ошибка. Повторите попытку или обратитесь в поддержку.",
      timeout: "Время оценки истекло",
      timeoutHint: "Анализ занимает больше обычного. Попробуйте ещё раз.",
      retry: "Повторить",
      baselPd: "Стандартизированный PD",
      riskRating: "Рейтинг риска",
      ifrs9Stage: "Стадия IFRS 9",
      cbuClass: "Класс КБУ",
    },
    result: {
      eligible: "Вы подходите!",
      conditional: "Условная пригодность",
      notEligible: "Не подходите",
      eligibleHint:
        "Поздравляем! По данным фермы и GEO-оценке вы соответствуете пилоту финансирования AGNET.",
      conditionalHint:
        "Для заявки нужны дополнительные документы. С вами свяжется полевой агент.",
      notEligibleHint: "К сожалению, заявка не соответствует текущим критериям.",
      creditScore: "Кредитный балл",
      financeCase: "Номер финансового дела",
      caseStatus: "Статус",
      requirements: "Необходимые действия",
      goDashboard: "В панель управления",
      goLogin: "На страницу входа",
      finishing: "Завершение...",
      farmerExplanation: "Почему такой балл?",
      scoreGaugeLabel: "Индикатор кредитного балла",
    },
    enums: {
      gender: {
        male: "Мужской",
        female: "Женский",
        prefer_not_to_say: "Предпочитаю не указывать",
      },
      farmerType: {
        owner: "Владелец земли",
        tenant: "Арендатор",
        family_farm: "Семейная ферма",
        cooperative_member: "Член кооператива",
      },
      education: {
        none: "Нет",
        primary: "Начальное",
        secondary: "Среднее",
        vocational: "Профессиональное",
        university: "Высшее",
      },
      tenureType: {
        owned: "В собственности",
        leased: "Аренда",
        sharecrop: "На долевых условиях",
        communal: "Общинная",
        inheritance: "Наследство",
      },
      landUseType: {
        irrigated_cropland: "Орошаемые поля",
        rainfed: "Богарные поля",
        orchard: "Сад",
        pasture: "Пастбище",
        greenhouse: "Теплица",
      },
      irrigationSource: {
        canal: "Канал",
        well: "Скважина",
        drip: "Капельное орошение",
        rainfed: "Дождевая",
        mixed: "Смешанное",
      },
      repaymentHistory: {
        none: "Кредитов не было",
        good: "Хорошая (вовремя)",
        fair: "Удовлетворительная (задержки)",
        poor: "Плохая (просрочки)",
      },
      season: {
        spring: "Весна",
        summer: "Лето",
        autumn: "Осень",
        winter: "Зима",
      },
      financeCaseStatus: {
        pending: "Ожидает",
        under_review: "На рассмотрении",
        approved: "Одобрено",
        rejected: "Отклонено",
      },
    },
  },
  en: {
    common: {
      saveContinue: "Save & continue",
      saving: "Saving...",
      select: "Select",
      required: "Required",
      optional: "Optional",
      addAnother: "Add another",
      skip: "Skip",
      complete: "Complete",
      pending: "Pending",
    },
    steps: {
      ACCOUNT: "Account",
      CONSENT: "Consent",
      KYC: "Identity",
      FARM_PROFILE: "Profile",
      LAND_SKETCH: "Land",
      GIS_MAPPING: "GIS Map",
      CROP_PLAN: "Crops",
      FARM_ASSETS: "Assets",
      DOCUMENTS: "Documents",
      FINANCE_REQUEST: "Finance",
      REVIEW: "Review",
      SCORING: "Scoring",
      RESULT: "Result",
    },
    consent: {
      title: "Consent & Disclosure",
      subtitle: "Review and accept the following consents to proceed with your application.",
      privacyNote:
        "Your data is protected and used only for the purposes shown below. You may withdraw consent at any time.",
      localeLabel: "Consent language",
      acceptContinue: "Accept & continue",
    },
    kyc: {
      finishLater: "Finish later — go to login",
      finishLaterHint: "You can complete the rest from the login page.",
    },
    farmProfile: {
      title: "Farm Profile",
      subtitle: "Tell us about yourself. This helps match you with suitable financial products.",
      fullName: "Full name",
      fullNamePlaceholder: "Your full name",
      dateOfBirth: "Date of birth",
      gender: "Gender",
      region: "Region",
      district: "District",
      selectRegion: "Select region",
      selectDistrict: "Select district",
      householdSize: "Household size",
      education: "Education",
      yearsFarming: "Years farming",
      farmerType: "Farmer type",
      primaryLanguage: "Primary language",
      completeRequiredHint: "Complete the following fields to continue:",
      loadingDistricts: "Loading districts...",
    },
    landSketch: {
      title: "Land Information",
      subtitle: "Provide details about your primary farming land.",
      agentNote:
        "If you have a cadastral or e-Ijara reference, enter it. Otherwise an AGNET field agent will assist with GIS mapping.",
      parcel: "Parcel",
      primaryParcel: "Primary parcel",
      district: "District",
      village: "Village",
      areaHa: "Area (ha)",
      tenureType: "Tenure type",
      landUseType: "Land use type",
      irrigationSource: "Irrigation source",
      registryRef: "Cadastral ref (optional)",
    },
    gisMapping: {
      title: "GIS Parcel Map",
      subtitle:
        "Enter coordinates for satellite analysis or skip — a field agent will map boundaries later.",
      coordinates: "Farm coordinates",
      coordinatesHint: "Used for yield forecasting and credit assessment",
      useLocation: "Use current location",
      detecting: "Detecting location...",
      latitude: "Latitude",
      longitude: "Longitude",
      accuracy: "Accuracy",
      parcelLink: "Linked parcel",
      captured: "Coordinates captured — analysis will run during scoring",
      skipAgent: "Skip (agent will map later)",
    },
    cropPlan: {
      title: "Crop & Season Plan",
      subtitle: "Add crops planned for the current or upcoming season.",
      crop: "Crop",
      season: "Season",
      areaHa: "Area (ha)",
      expectedYield: "Expected yield (tonnes)",
      areaWarning: "Total crop area exceeds declared land",
      areaRemaining: "Remaining area",
      completeRequiredHint: "Complete the following fields to continue:",
      reduceAreaHint: "Crop areas exceed declared land — reduce values.",
    },
    finance: {
      title: "Finance Request",
      subtitle: "Tell us about your financing needs.",
      purpose: "Financing purpose",
      amountUzs: "Requested amount (UZS)",
      monthlyIncomeUzs: "Monthly income (UZS)",
      existingLoansUzs: "Existing loans (UZS)",
      termMonths: "Term (months)",
      repaymentHistory: "Prior loan repayment",
      fxSnapshot: "Exchange rate",
      fxNote: "USD calculated for institutional reporting",
      prefilled: "Some fields were pre-filled from uploaded documents",
      autoFilled: "auto-filled",
    },
    review: {
      title: "Review & Submit",
      subtitle: "Check your application before submitting for scoring.",
      identity: "Personal information",
      land: "Land",
      crops: "Crops",
      assets: "Assets",
      finance: "Finance",
      documents: "Documents",
      attestation:
        "I confirm the information provided is correct and consent to AGNET using it for credit scoring and financing.",
      submit: "Submit application",
      submitting: "Submitting...",
    },
    scoring: {
      processing: "Processing your application...",
      complete: "Scoring complete!",
      processingHint:
        "Running satellite analysis, document verification, and credit scoring.",
      completeHint: "Results are ready. Proceeding to the next step...",
      keyFactors: "Key factors",
      phaseGeo: "Satellite analysis (Prithvi)",
      phaseDocuments: "Document verification",
      phaseScoring: "Credit scoring",
      satellitePreview: "Satellite imagery",
      explanationPreview: "About your assessment",
      showExplanation: "Show details",
      hideExplanation: "Hide",
      failed: "Scoring failed",
      failedHint: "A technical error occurred. Please retry or contact support.",
      timeout: "Scoring timed out",
      timeoutHint: "Analysis is taking longer than expected. Please retry.",
      retry: "Retry",
      baselPd: "Standardized PD",
      riskRating: "Risk rating",
      ifrs9Stage: "IFRS 9 stage",
      cbuClass: "CBU class",
    },
    result: {
      eligible: "You are eligible!",
      conditional: "Conditional eligibility",
      notEligible: "Not eligible",
      eligibleHint:
        "Congratulations! Based on your farm data and GEO assessment, you qualify for the AGNET financing pilot.",
      conditionalHint:
        "Additional documents are required for your application. A field agent will contact you.",
      notEligibleHint: "Unfortunately your application does not meet the current eligibility criteria.",
      creditScore: "Credit score",
      financeCase: "Finance case number",
      caseStatus: "Status",
      requirements: "Required actions",
      goDashboard: "Go to dashboard",
      goLogin: "Go to login",
      finishing: "Finishing...",
      farmerExplanation: "Why this score?",
      scoreGaugeLabel: "Credit score gauge",
    },
    enums: {
      gender: {
        male: "Male",
        female: "Female",
        prefer_not_to_say: "Prefer not to say",
      },
      farmerType: {
        owner: "Land owner",
        tenant: "Tenant",
        family_farm: "Family farm",
        cooperative_member: "Cooperative member",
      },
      education: {
        none: "None",
        primary: "Primary",
        secondary: "Secondary",
        vocational: "Vocational",
        university: "University",
      },
      tenureType: {
        owned: "Owned",
        leased: "Leased",
        sharecrop: "Sharecrop",
        communal: "Communal",
        inheritance: "Inheritance",
      },
      landUseType: {
        irrigated_cropland: "Irrigated cropland",
        rainfed: "Rainfed",
        orchard: "Orchard",
        pasture: "Pasture",
        greenhouse: "Greenhouse",
      },
      irrigationSource: {
        canal: "Canal",
        well: "Well",
        drip: "Drip irrigation",
        rainfed: "Rainfed",
        mixed: "Mixed",
      },
      repaymentHistory: {
        none: "No prior loans",
        good: "Good (on time)",
        fair: "Fair (some delays)",
        poor: "Poor (defaults)",
      },
      season: {
        spring: "Spring",
        summer: "Summer",
        autumn: "Autumn",
        winter: "Winter",
      },
      financeCaseStatus: {
        pending: "Pending",
        under_review: "Under review",
        approved: "Approved",
        rejected: "Rejected",
      },
    },
  },
};

function resolvePath(tree: LabelTree, path: string): string | undefined {
  const parts = path.split(".");
  let node: string | LabelTree | undefined = tree;
  for (const part of parts) {
    if (!node || typeof node === "string") return undefined;
    node = node[part];
  }
  return typeof node === "string" ? node : undefined;
}

/** Translate a dot-path label key for the wizard UI. */
export function t(path: string, locale: WizardLocale = "uz"): string {
  const value = resolvePath(labels[locale], path) ?? resolvePath(labels.uz, path);
  return value ?? path;
}

/** Translate an onboarding step key (e.g. "ACCOUNT") into its locale label. */
export function stepLabel(stepKey: string, locale: WizardLocale = "uz"): string {
  return t(`steps.${stepKey}`, locale);
}

export function enumLabel(
  group: string,
  value: string,
  locale: WizardLocale = "uz",
): string {
  return t(`enums.${group}.${value}`, locale) || value;
}

export function resolveWizardLocale(stepData: Record<string, unknown>): WizardLocale {
  const consentLocale = (stepData.CONSENT as { locale?: WizardLocale } | undefined)?.locale;
  if (consentLocale === "uz" || consentLocale === "ru" || consentLocale === "en") return consentLocale;

  const profileLang = (stepData.FARM_PROFILE as { primaryLanguage?: string } | undefined)
    ?.primaryLanguage;
  if (profileLang === "ru") return "ru";
  if (profileLang === "en") return "en";
  return "uz";
}
