'use client';

import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';

export type Language = 'vi' | 'en';

type Messages = Record<string, string>;

const messages: Record<Language, Messages> = {
  vi: {
    'nav.home': 'Trang chủ',
    'nav.products': 'Sản phẩm',
    'nav.guides': 'Hướng dẫn',
    'nav.about': 'Giới thiệu',
    'nav.contact': 'Liên hệ',
    'header.productMenuEyebrow': 'Khám phá cửa hàng',
    'header.productMenuTitle': 'Tìm món vừa tay',
    'header.productMenuDescription': 'Bộ kit nhỏ, dụng cụ dễ chọn và len thân thiện cho từng bước học.',
    'header.productCategories': 'Danh mục sản phẩm',
    'header.viewAllProducts': 'Xem tất cả sản phẩm',
    'header.starterKits': 'Bộ kit cho người mới',
    'header.hooks': 'Kim móc',
    'header.yarn': 'Len sợi',
    'header.accessories': 'Phụ kiện',
    'header.guideMenuEyebrow': 'Học theo từng bước',
    'header.guideMenuTitle': 'Góc hướng dẫn',
    'header.guideMenuDescription': 'Từ chọn dụng cụ đến hoàn thành sản phẩm đầu tiên, bắt đầu thật nhẹ nhàng.',
    'header.guideCategories': 'Chọn chủ đề',
    'header.viewAllGuides': 'Xem toàn bộ hướng dẫn',
    'header.guideTools': 'Chọn dụng cụ',
    'header.guideTechniques': 'Học kỹ thuật',
    'header.guideProjects': 'Dự án đầu tiên',
    'header.guideToolBasics': 'Dụng cụ cho người mới',
    'header.guideHooks': 'Chọn kim móc',
    'header.guideYarn': 'Chọn len',
    'header.guideStitches': 'Các mũi cơ bản',
    'header.guideHolding': 'Cầm kim & giữ sợi',
    'header.guideMistakes': 'Lỗi thường gặp',
    'header.guideFlower': 'Móc hoa len',
    'header.guideCoaster': 'Móc đế lót ly',
    'announcement': 'Website demo học tập · Đơn thử nghiệm, chưa nhận thanh toán hay giao hàng',
    'search.label': 'Tìm kiếm',
    'search.placeholder': 'Tìm kiếm',
    'search.mobilePlaceholder': 'Tìm sản phẩm hoặc bài viết',
    'cart.label': 'Giỏ hàng, {count} sản phẩm',
    'cart.item': '{count} sản phẩm',
    'floatingContact.title': 'Liên hệ nhanh',
    'floatingContact.open': 'Mở {channel}',
    'mobile.open': 'Mở menu',
    'mobile.close': 'Đóng menu',
    'language.label': 'Ngôn ngữ',
    'language.vi': 'VI',
    'language.en': 'EN',
    'language.switchTo': 'Chuyển sang {language}',
    'footer.explore': 'Khám phá',
    'footer.information': 'Thông tin',
    'footer.contact': 'Liên hệ',
    'footer.brandDescription': 'Một góc nhỏ để chọn đúng dụng cụ, học theo từng bước và vui với sản phẩm đầu tiên.',
    'footer.tagline': 'Bắt đầu móc len từ những điều nhỏ xinh.',
    'footer.guides': 'Góc học móc len',
    'footer.about': 'Về MOCLEN STARTER',
    'footer.consult': 'Nhận tư vấn',
    'footer.quiz': 'Quiz chọn bộ kit',
    'footer.palette': 'Phối màu len',
    'footer.demoOrder': 'Đặt hàng demo',
    'footer.privacy': 'Dữ liệu & riêng tư',
    'footer.shipping': 'Giao hàng & đổi trả',
    'footer.emailPending': 'Email sẽ hiện sau khi cấu hình',
    'footer.demo': 'Bản demo phục vụ học tập.',
    'footer.noPayment': 'Không phát sinh thanh toán hoặc giao hàng thật.',
    'breadcrumb.home': 'Trang chủ',
    'breadcrumb.products': 'Sản phẩm',
    'breadcrumb.guides': 'Hướng dẫn',
    'breadcrumb.about': 'Giới thiệu',
    'breadcrumb.contact': 'Liên hệ',
    'breadcrumb.cart': 'Giỏ hàng',
    'breadcrumb.search': 'Tìm kiếm',
    'breadcrumb.category': 'Danh mục sản phẩm',
    'home.eyebrow': 'Một góc nhỏ để bắt đầu',
    'home.heroTitleLine1': 'Bắt đầu móc',
    'home.heroTitleLine2': 'len từ những',
    'home.heroTitleLine3': 'điều nhỏ xinh',
    'home.lead': 'Chọn dụng cụ vừa tay, học những mũi đầu tiên và tự làm một món nhỏ khiến bạn vui. MOCLEN STARTER gom các bộ kit dễ hiểu cùng bài hướng dẫn cho người mới.',
    'home.exploreKits': 'Khám phá bộ kit',
    'home.learnBasics': 'Học móc len cơ bản',
    'home.gentleTip': 'Gợi ý nhẹ nhàng:',
    'home.gentleTipText': 'bắt đầu bằng một dự án nhỏ, không cần vội.',
    'home.heroAlt': 'Bộ kit móc len cho người mới với len cotton, kim móc và phụ kiện',
    'home.heroTag': 'Bộ kit là dụng cụ + nguyên liệu để bạn tự làm, không phải thành phẩm có sẵn.',
    'home.heroStageLabel': 'Dự án đầu tiên',
    'home.heroStageTitle': 'Hoa len năm cánh',
    'home.heroStageMeta': '15 phút · Mới bắt đầu',
    'home.heroCarouselLabel': 'Các mẫu sản phẩm nổi bật',
    'home.heroCarouselSlide': 'Xem mẫu {name}',
    'home.startProject': 'Bắt đầu dự án',
    'home.visitStudio': 'Vào xưởng len',
    'home.handmadeNote': 'Làm bằng tay, học theo nhịp của bạn.',
    'home.benefit1.title': 'Dễ dàng bắt đầu',
    'home.benefit1.description': 'Nội dung ngắn, từ ngữ rõ và có bài tập nhỏ để bạn làm quen từng nhịp tay.',
    'home.benefit2.title': 'Đủ dụng cụ cần thiết',
    'home.benefit2.description': 'Bộ kit được ghép theo dự án, giúp bạn không phải đoán nên mua món nào trước.',
    'home.benefit3.title': 'Có hướng dẫn từng bước',
    'home.benefit3.description': 'Từ chọn kim, giữ sợi đến đếm mũi đều có ví dụ và liên kết đến dụng cụ phù hợp.',
    'home.exploreEyebrow': 'Khám phá theo nhu cầu',
    'home.whatLookingFor': 'Bạn đang tìm gì?',
    'home.categoryLead': 'Chọn một nhóm để bắt đầu thật gọn. Bạn luôn có thể quay lại xem thêm sau khi đã quen tay.',
    'home.viewCategory': 'Xem danh mục',
    'home.smallProject': 'Bắt đầu từ một dự án nhỏ',
    'home.starterKits': 'Bộ kit cho bước khởi đầu',
    'home.viewAllProducts': 'Xem tất cả sản phẩm',
    'home.readSlowly': 'Đọc chậm, làm từng bước',
    'home.learningCorner': 'Góc học móc len',
    'home.viewAllGuides': 'Xem toàn bộ hướng dẫn',
    'home.needAdvice': 'Cần một gợi ý vừa đủ?',
    'home.whereToStart': 'Chưa biết bắt đầu từ đâu?',
    'home.consultationLead': 'Nói cho MOCLEN STARTER biết bạn muốn làm gì. Nhóm sẽ xem yêu cầu trong khu vực quản trị của website demo và gợi ý hướng đi phù hợp.',
    'home.getAdvice': 'Nhận tư vấn',
    'home.atelierEyebrow': 'Bàn làm len của bạn',
    'home.atelierTitle': 'Chọn một cảm hứng để bắt đầu',
    'home.atelierLead': 'Không cần bắt đầu bằng một danh sách mua sắm. Bắt đầu bằng một cảm giác, một màu hoặc một món nhỏ bạn muốn làm.',
    'home.tableEyebrow': 'Trên bàn hôm nay',
    'home.tableTitle': 'Những dự án nhỏ, làm được thật',
    'home.tableLead': 'Mỗi bộ kit là một lộ trình ngắn: có dụng cụ, có nguyên liệu và có một thành phẩm để bạn cầm trên tay.',
    'home.projectLabel': 'DỰ ÁN',
    'home.categoriesEyebrow': 'Nguyên liệu & dụng cụ',
    'home.categoriesTitle': 'Mọi thứ trên một mặt bàn',
    'home.categoriesLead': 'Chọn đúng một món trước, rồi để đôi tay tự tìm thấy nhịp của mình.',
    'home.studioNotesEyebrow': 'Ghi chú trong xưởng',
    'home.studioNotesTitle': 'Đọc một chút, làm một chút',
    'home.studioNotesLead': 'Những hướng dẫn ngắn để bạn bớt đoán và có thêm tự tin khi bắt đầu.',
    'home.seeAllNotes': 'Xem tất cả ghi chú',
    'home.experiencesEyebrow': 'Khám phá theo cách của bạn',
    'home.experiencesTitle': 'Một bước khởi đầu có chủ đích',
    'home.experiencesLead': 'Chưa cần biết chính xác mình muốn mua gì. Hãy trả lời vài câu hỏi hoặc thử phối một bảng màu trước.',
    'home.quizCardTitle': 'Quiz chọn bộ kit',
    'home.quizCardDescription': 'Trả lời nhanh về trình độ, dự án và ngân sách để tìm bộ kit hợp với nhịp học của bạn.',
    'home.openQuiz': 'Làm quiz ngay',
    'home.paletteCardTitle': 'Phòng phối màu len',
    'home.paletteCardDescription': 'Chọn một bảng màu, tự tạo combo riêng và lưu lại cảm hứng cho dự án tiếp theo.',
    'home.openPalette': 'Thử phối màu',
    'quiz.eyebrow': 'Tư vấn bộ kit trong 60 giây',
    'quiz.title': 'Bạn nên bắt đầu với bộ kit nào?',
    'quiz.description': 'Chọn câu trả lời gần với bạn nhất. MOCLEN STARTER sẽ ghép một gợi ý vừa sức, vừa thời gian và vừa ngân sách.',
    'quiz.progress': 'Câu {current}/{total}',
    'quiz.previous': 'Quay lại',
    'quiz.next': 'Tiếp tục',
    'quiz.startOver': 'Làm lại quiz',
    'quiz.resultEyebrow': 'Gợi ý dành riêng cho bạn',
    'quiz.resultTitle': 'Đây là những bộ kit hợp với bước đầu của bạn',
    'quiz.resultDescription': 'Bạn không cần mua tất cả. Hãy chọn một dự án nhỏ khiến bạn muốn cầm kim lên hôm nay.',
    'quiz.addKit': 'Thêm bộ kit',
    'quiz.viewKit': 'Xem chi tiết',
    'quiz.noProducts': 'Chưa có sản phẩm phù hợp để gợi ý.',
    'quiz.question.experience': 'Bạn đang ở mức nào?',
    'quiz.option.experience.beginner': 'Mình hoàn toàn mới',
    'quiz.option.experience.some': 'Mình đã thử vài mũi',
    'quiz.question.project': 'Bạn muốn làm gì đầu tiên?',
    'quiz.option.project.flower': 'Một bông hoa nhỏ',
    'quiz.option.project.coaster': 'Đế lót ly dùng được',
    'quiz.option.project.keychain': 'Móc khóa thật xinh',
    'quiz.option.project.tools': 'Tập các mũi cơ bản',
    'quiz.question.pace': 'Bạn thích nhịp làm thế nào?',
    'quiz.option.pace.quick': 'Có kết quả nhanh trong 1–2 buổi',
    'quiz.option.pace.calm': 'Từ tốn, luyện tập nhiều hơn',
    'quiz.question.budget': 'Khoảng ngân sách của bạn?',
    'quiz.option.budget.low': 'Gọn nhẹ, dưới 200.000đ',
    'quiz.option.budget.standard': 'Thoải mái hơn, trên 200.000đ',
    'palette.eyebrow': 'Phòng phối màu len',
    'palette.title': 'Tạo một bảng màu có cảm xúc',
    'palette.description': 'Chọn một bảng màu gợi ý hoặc bấm vào từng màu để tạo combo riêng cho dự án của bạn.',
    'palette.presets': 'Bảng màu gợi ý',
    'palette.custom': 'Bảng màu của bạn',
    'palette.selected': '{count}/4 màu đã chọn',
    'palette.copy': 'Sao chép mã màu',
    'palette.copied': 'Đã sao chép',
    'palette.save': 'Lưu bảng màu',
    'palette.saved': 'Đã lưu bảng màu',
    'palette.remove': 'Bỏ màu',
    'palette.chooseColor': 'Chọn màu {name}',
    'palette.limit': 'Bạn có thể chọn tối đa 4 màu.',
    'palette.addYarn': 'Thêm len cotton',
    'palette.viewYarn': 'Xem len phù hợp',
    'palette.yarnNote': 'Len cotton thực hành có nhiều màu dễ nhìn, phù hợp để thử bảng phối đầu tiên.',
    'palette.preset.meadow.name': 'Sương mai',
    'palette.preset.meadow.description': 'Xanh sage, kem và terracotta cho cảm giác tự nhiên.',
    'palette.preset.bloom.name': 'Vườn hoa',
    'palette.preset.bloom.description': 'Hồng phấn và vàng bơ cho những món nhỏ vui mắt.',
    'palette.preset.cocoa.name': 'Cacao ấm',
    'palette.preset.cocoa.description': 'Nâu đất, caramel và xanh rêu cho một góc thủ công trầm.',
    'palette.preset.sky.name': 'Mây xanh',
    'palette.preset.sky.description': 'Xanh trời, xanh biển và trắng sữa thật dịu.',
    'card.demoPrice': 'giá minh họa',
    'card.makeLabel': 'Có thể làm',
    'card.add': 'Thêm',
    'cart.addToCart': 'Thêm vào giỏ',
    'cart.product': 'sản phẩm',
    'cart.added': 'Đã thêm',
    'cart.addedToCart': 'Đã thêm vào giỏ',
    'cart.saveError': 'Chưa lưu được giỏ hàng',
    'card.readGuide': 'Đọc hướng dẫn',
    'card.viewDetails': 'Xem chi tiết',
    'card.level.beginner': 'Mới bắt đầu',
    'card.level.all': 'Mọi trình độ',
    'products.eyebrow': 'Chọn dụng cụ vừa tay',
    'products.title': 'Sản phẩm & bộ kit móc len',
    'products.description': 'Giá chỉ mang tính minh họa cho bài tập lớn. Mỗi bộ kit ghi rõ những gì có trong hộp và bạn có thể tự làm được gì.',
    'products.filter': 'Lọc sản phẩm',
    'products.category': 'Danh mục',
    'products.allCategories': 'Tất cả danh mục',
    'products.level': 'Mức độ phù hợp',
    'products.allLevels': 'Tất cả mức độ',
    'products.priceFrom': 'Giá từ (đ)',
    'products.priceTo': 'Giá đến (đ)',
    'products.unlimited': 'Không giới hạn',
    'products.applyFilter': 'Áp dụng lọc',
    'products.clearFilter': 'Xóa lọc',
    'products.listLabel': 'Danh sách sản phẩm',
    'products.matching': '{count} sản phẩm phù hợp',
    'products.sortLabel': 'Sắp xếp',
    'products.sortDefault': 'Sắp xếp mặc định',
    'products.sortAsc': 'Giá thấp đến cao',
    'products.sortDesc': 'Giá cao đến thấp',
    'products.sortName': 'Tên A–Z',
    'products.apply': 'Áp dụng',
    'products.emptyTitle': 'Chưa có sản phẩm phù hợp',
    'products.emptyDescription': 'Thử bỏ bớt một điều kiện lọc hoặc xem toàn bộ bộ kit cho người mới.',
    'products.viewAll': 'Xem lại toàn bộ',
    'guides.eyebrow': 'Góc học móc len',
    'guides.title': 'Hướng dẫn cho những mũi đầu tiên',
    'guides.description': 'Đọc một bài, thử một thao tác, rồi quay lại khi bạn thấy sẵn sàng. Các thuật ngữ crochet tiếng Anh trong bài dùng hệ US và đều có giải thích.',
    'guides.toolsHeading': 'Chọn đúng món trước khi tập',
    'guides.learnHeading': 'Tạo nhịp tay thật thoải mái',
    'guides.firstHeading': 'Làm một món nhỏ có thể cầm trên tay',
    'detail.defaultCategory': 'Dụng cụ móc len',
    'detail.demoPrice': 'Giá minh họa',
    'detail.projectSheet': 'Project sheet · Dự án thủ công',
    'detail.level': 'Mức độ',
    'detail.projects': 'Thành phẩm gợi ý',
    'detail.ideas': '{count} ý tưởng',
    'detail.guides': 'Hướng dẫn kèm theo',
    'detail.articles': '{count} bài',
    'detail.includes': 'Bộ kit gồm những gì?',
    'detail.canMake': 'Bạn có thể tự làm',
    'detail.learnWithKit': 'Học cùng bộ kit',
    'detail.guidesHeading': 'Hướng dẫn đi kèm',
    'detail.readAtYourPace': 'Đọc trước, làm sau — theo nhịp của bạn.',
    'detail.openGuide': 'Mở bài hướng dẫn',
    'detail.relatedEyebrow': 'Có thể hợp với bạn',
    'detail.related': 'Sản phẩm liên quan',
    'article.tableOfContents': 'Mục lục',
    'article.shortRead': 'Bài viết ngắn, đọc theo dòng chảy.',
    'article.toolSuggestions': 'Gợi ý dụng cụ',
    'article.noRelatedProducts': 'Chưa có sản phẩm liên quan.',
    'article.inArticleTools': 'Dụng cụ trong bài',
    'article.youMayNeed': 'Bạn có thể cần',
    'article.continueReading': 'Đọc tiếp',
    'article.related': 'Bài liên quan',
    'category.emptyTitle': 'Danh mục đang được cập nhật',
    'category.emptyDescription': 'Hãy quay lại xem toàn bộ sản phẩm để tìm món phù hợp.',
    'category.viewProducts': 'Xem sản phẩm',
    'category.descriptionSuffix': 'Mỗi sản phẩm đều ghi rõ mức độ phù hợp và các hướng dẫn liên quan.',
    'search.eyebrow': 'Tìm đúng điều bạn cần',
    'search.resultsFor': 'Kết quả cho “{query}”',
    'search.title': 'Tìm kiếm sản phẩm và bài viết',
    'search.description': 'Thử một từ khóa có dấu hoặc không dấu. MOCLEN STARTER sẽ tìm trong tên, mô tả, tiêu đề và từ khóa liên quan.',
    'search.keyword': 'Từ khóa tìm kiếm',
    'search.example': 'Ví dụ: kim móc, hoa len, đế lót ly',
    'search.noResults': 'Chưa tìm thấy kết quả',
    'search.noResultsDescription': 'Thử từ khóa ngắn hơn hoặc xóa dấu, ví dụ “kim moc” thay vì một câu dài.',
    'search.clearQuery': 'Xóa truy vấn',
    'search.wantToFind': 'Bạn muốn tìm gì?',
    'search.wantToFindDescription': 'Nhập tên sản phẩm, mũi móc hoặc câu hỏi bạn đang có.',
    'search.products': 'Sản phẩm',
    'search.guides': 'Bài hướng dẫn',
    'search.resultsCount': '{count} kết quả',
    'about.eyebrow': 'Về MOCLEN STARTER',
    'about.title': 'Bắt đầu từ những điều nhỏ xinh',
    'about.description': 'Một thương hiệu thử nghiệm, một góc học móc len và một cửa hàng kit minh họa cho người mới.',
    'about.cardTitle': '5 bạn, 1 góc thủ công',
    'about.cardDescription': 'Website được làm cho mục đích học tập. Mỗi phần nội dung đều cố gắng giữ thông tin vừa đủ, dễ thay đổi và trung thực với trạng thái demo.',
    'about.contentTitle': 'Một website nhỏ cho những người mới bắt đầu',
    'about.content1': 'MOCLEN STARTER được xây dựng như một bài tập lớn SEO của một nhóm sinh viên năm người. Mục tiêu của website là biến câu hỏi “mình cần mua gì trước?” thành một lộ trình dễ đi hơn: chọn đúng dụng cụ, đọc một bài ngắn và thử một sản phẩm đầu tiên.',
    'about.priorityTitle': 'Điều chúng mình ưu tiên',
    'about.priority': 'Nội dung tiếng Việt tự nhiên, mô tả rõ bộ kit có gì và liên kết nội bộ có ngữ cảnh. Giá trong website chỉ là giá minh họa; sản phẩm, đơn hàng và yêu cầu tư vấn đều phục vụ mục đích trình diễn.',
    'about.rhythmTitle': 'Học theo nhịp của bạn',
    'about.rhythm': 'Không cần hoàn hảo từ mũi đầu tiên. Một vòng tròn hơi lệch, một hàng phải tháo ra hay một sợi bị tưa đều là phần bình thường của quá trình học. Hãy bắt đầu bằng một món nhỏ, ghi lại điều mình đã thử và quay lại bài hướng dẫn khi cần.',
    'contact.eyebrow': 'Mình cùng tìm một điểm bắt đầu',
    'contact.title': 'Liên hệ & nhận tư vấn',
    'contact.description': 'Chia sẻ điều bạn đang muốn làm hoặc phần đang khiến bạn bối rối. Form này chỉ lưu yêu cầu vào khu vực quản trị demo; chưa kết nối dịch vụ gửi email.',
    'contact.smallThings': 'Một vài điều nhỏ',
    'contact.smallThingsDescription': 'Nếu bạn chưa biết chọn kim hay sợi nào, hãy nói rõ bạn muốn làm sản phẩm gì và đã từng thử chưa.',
    'contact.response': 'Phản hồi',
    'contact.responseDescription': 'Được xem trong khu vực quản trị sau khi lưu thành công.',
    'contact.configuredInfo': 'Thông tin cấu hình',
    'contact.emailNotConfigured': 'Email liên hệ chưa được cấu hình.',
    'contact.socialTitle': 'Mạng xã hội',
    'contact.address': 'Địa chỉ',
    'contact.mapTitle': 'Bản đồ vị trí MOCLEN STARTER tại Ngũ Hành Sơn, Đà Nẵng',
    'contact.viewMap': 'Xem chỉ đường trên Google Maps',
    'contact.phone': 'Điện thoại',
    'contact.formTitle': 'Gửi yêu cầu tư vấn',
    'form.name': 'Tên của bạn',
    'form.email': 'Email',
    'form.message': 'Bạn muốn được tư vấn điều gì?',
    'form.saving': 'Đang lưu…',
    'form.saveConsultation': 'Lưu yêu cầu tư vấn',
    'form.saved': 'Đã lưu yêu cầu tư vấn. Nhóm sẽ xem trong khu vực quản trị; website chưa gửi email tự động.',
    'form.saveError': 'Chưa lưu được yêu cầu.',
    'form.sendError': 'Chưa gửi được yêu cầu.',
    'cart.eyebrow': 'Chỉ là bản thử nghiệm',
    'cart.title': 'Giỏ hàng của bạn',
    'cart.description': 'Bạn chỉ đang lưu một lựa chọn tạm thời trên trình duyệt. Khi bấm tạo đơn, hệ thống mới lưu một bản ghi demo ở máy chủ.',
    'cart.loading': 'Đang mở giỏ hàng…',
    'cart.emptyTitle': 'Giỏ hàng đang trống',
    'cart.emptyDescription': 'Chọn một bộ kit hoặc món dụng cụ nhỏ, rồi quay lại đây để tạo đơn thử nghiệm.',
    'cart.viewProducts': 'Xem sản phẩm',
    'cart.summary': 'Tóm tắt',
    'cart.quantity': 'Số lượng',
    'cart.total': 'Tổng tham chiếu',
    'cart.notice': 'Đơn thử nghiệm, không phát sinh thanh toán hoặc giao hàng. Giá được tính lại ở máy chủ khi lưu.',
    'cart.createOrder': 'Tạo đơn thử nghiệm',
    'cart.saving': 'Đang lưu…',
    'cart.remove': 'Xóa',
    'cart.decrease': 'Giảm {name}',
    'cart.increase': 'Tăng {name}',
    'cart.delete': 'Xóa {name} khỏi giỏ',
    'cart.priceNote': 'giá minh họa',
    'cart.orderSaved': 'Đã lưu đơn thử nghiệm {id}. Tổng tham chiếu: {total}.',
    'cart.orderError': 'Chưa tạo được đơn thử nghiệm.',
  },
  en: {
    'nav.home': 'Home',
    'nav.products': 'Shop',
    'nav.guides': 'Guides',
    'nav.about': 'About',
    'nav.contact': 'Contact',
    'header.productMenuEyebrow': 'Explore the shop',
    'header.productMenuTitle': 'Find your comfortable start',
    'header.productMenuDescription': 'Small kits, easy-to-choose tools and friendly yarn for each step of learning.',
    'header.productCategories': 'Product categories',
    'header.viewAllProducts': 'View all products',
    'header.starterKits': 'Beginner kits',
    'header.hooks': 'Crochet hooks',
    'header.yarn': 'Yarn',
    'header.accessories': 'Accessories',
    'header.guideMenuEyebrow': 'Learn one step at a time',
    'header.guideMenuTitle': 'Crochet guides',
    'header.guideMenuDescription': 'From choosing tools to finishing your first project, start gently and keep your rhythm.',
    'header.guideCategories': 'Choose a topic',
    'header.viewAllGuides': 'View all guides',
    'header.guideTools': 'Choose your tools',
    'header.guideTechniques': 'Learn techniques',
    'header.guideProjects': 'First projects',
    'header.guideToolBasics': 'Beginner tool basics',
    'header.guideHooks': 'Choosing a hook',
    'header.guideYarn': 'Choosing yarn',
    'header.guideStitches': 'Basic stitches',
    'header.guideHolding': 'Holding hook & yarn',
    'header.guideMistakes': 'Common mistakes',
    'header.guideFlower': 'Crochet a flower',
    'header.guideCoaster': 'Crochet a coaster',
    'announcement': 'Learning demo website · Test orders only, no payment or delivery',
    'search.label': 'Search',
    'search.placeholder': 'Search',
    'search.mobilePlaceholder': 'Search products or guides',
    'cart.label': 'Cart, {count} items',
    'cart.item': '{count} items',
    'floatingContact.title': 'Quick contact',
    'floatingContact.open': 'Open {channel}',
    'mobile.open': 'Open menu',
    'mobile.close': 'Close menu',
    'language.label': 'Language',
    'language.vi': 'VI',
    'language.en': 'EN',
    'language.switchTo': 'Switch to {language}',
    'footer.explore': 'Explore',
    'footer.information': 'Information',
    'footer.contact': 'Contact',
    'footer.brandDescription': 'A small place to choose the right tools, learn step by step and enjoy your first project.',
    'footer.tagline': 'Start crocheting with small, lovely things.',
    'footer.guides': 'Crochet learning corner',
    'footer.about': 'About MOCLEN STARTER',
    'footer.consult': 'Get advice',
    'footer.quiz': 'Kit finder quiz',
    'footer.palette': 'Yarn colour studio',
    'footer.demoOrder': 'Demo orders',
    'footer.privacy': 'Data & privacy',
    'footer.shipping': 'Shipping & returns',
    'footer.emailPending': 'Email will appear after configuration',
    'footer.demo': 'Learning demo only.',
    'footer.noPayment': 'No real payment or delivery is processed.',
    'breadcrumb.home': 'Home',
    'breadcrumb.products': 'Shop',
    'breadcrumb.guides': 'Guides',
    'breadcrumb.about': 'About',
    'breadcrumb.contact': 'Contact',
    'breadcrumb.cart': 'Cart',
    'breadcrumb.search': 'Search',
    'breadcrumb.category': 'Product category',
    'home.eyebrow': 'A small place to begin',
    'home.heroTitleLine1': 'Pick up a hook.',
    'home.heroTitleLine2': 'Begin something',
    'home.heroTitleLine3': 'small',
    'home.lead': 'Choose a comfortable tool, learn your first stitches and make a small project that makes you smile. MOCLEN STARTER brings together approachable kits and clear guides for beginners.',
    'home.exploreKits': 'Explore kits',
    'home.learnBasics': 'Learn crochet basics',
    'home.gentleTip': 'A gentle tip:',
    'home.gentleTipText': 'start with a small project; there is no need to rush.',
    'home.heroAlt': 'Beginner crochet kit with cotton yarn, crochet hook and accessories',
    'home.heroTag': 'A kit is a set of tools and materials for you to make something yourself, not a ready-made product.',
    'home.heroStageLabel': 'First project',
    'home.heroStageTitle': 'Five-petal flower',
    'home.heroStageMeta': '15 min · Beginner',
    'home.heroCarouselLabel': 'Featured product samples',
    'home.heroCarouselSlide': 'View {name} sample',
    'home.startProject': 'Start the project',
    'home.visitStudio': 'Enter the studio',
    'home.handmadeNote': 'Made by hand, learned at your own pace.',
    'home.benefit1.title': 'Easy to start',
    'home.benefit1.description': 'Short explanations, clear words and small exercises help you find a comfortable rhythm.',
    'home.benefit2.title': 'The essentials together',
    'home.benefit2.description': 'Each kit is built around a project, so you do not have to guess what to buy first.',
    'home.benefit3.title': 'Step-by-step guidance',
    'home.benefit3.description': 'From choosing a hook and holding yarn to counting stitches, every step comes with examples.',
    'home.exploreEyebrow': 'Explore by need',
    'home.whatLookingFor': 'What are you looking for?',
    'home.categoryLead': 'Choose one group and keep your first step simple. You can always come back for more once your hands feel familiar.',
    'home.viewCategory': 'View category',
    'home.smallProject': 'Start with a small project',
    'home.starterKits': 'Kits for your first steps',
    'home.viewAllProducts': 'View all products',
    'home.readSlowly': 'Read slowly, make one step at a time',
    'home.learningCorner': 'Crochet learning corner',
    'home.viewAllGuides': 'View all guides',
    'home.needAdvice': 'Need a little guidance?',
    'home.whereToStart': 'Not sure where to start?',
    'home.consultationLead': 'Tell MOCLEN STARTER what you would like to make. The team will review your request in the demo admin area and suggest a suitable direction.',
    'home.getAdvice': 'Get advice',
    'home.atelierEyebrow': 'Your crochet table',
    'home.atelierTitle': 'Choose a feeling to begin with',
    'home.atelierLead': 'You do not need to begin with a shopping list. Begin with a feeling, a colour or a small thing you would like to make.',
    'home.tableEyebrow': 'On the table today',
    'home.tableTitle': 'Small projects you can really make',
    'home.tableLead': 'Each kit is a short path: tools, materials and a finished piece you can hold in your hands.',
    'home.projectLabel': 'PROJECT',
    'home.categoriesEyebrow': 'Materials & tools',
    'home.categoriesTitle': 'Everything on one table',
    'home.categoriesLead': 'Choose one right thing first, then let your hands find their own rhythm.',
    'home.studioNotesEyebrow': 'Studio notes',
    'home.studioNotesTitle': 'Read a little, make a little',
    'home.studioNotesLead': 'Short guides to help you guess less and feel more confident when you begin.',
    'home.seeAllNotes': 'View all notes',
    'home.experiencesEyebrow': 'Explore in your own way',
    'home.experiencesTitle': 'A more intentional first step',
    'home.experiencesLead': 'You do not need to know exactly what to buy yet. Answer a few questions or try a colour palette first.',
    'home.quizCardTitle': 'Kit finder quiz',
    'home.quizCardDescription': 'Tell us about your level, project and budget to find a kit that matches your learning rhythm.',
    'home.openQuiz': 'Take the quiz',
    'home.paletteCardTitle': 'Yarn colour studio',
    'home.paletteCardDescription': 'Choose a palette, build your own combo and save inspiration for your next project.',
    'home.openPalette': 'Try the colour studio',
    'quiz.eyebrow': 'Kit advice in 60 seconds',
    'quiz.title': 'Which kit should you start with?',
    'quiz.description': 'Choose the answer that feels closest to you. MOCLEN STARTER will match a suggestion to your level, time and budget.',
    'quiz.progress': 'Question {current}/{total}',
    'quiz.previous': 'Back',
    'quiz.next': 'Continue',
    'quiz.startOver': 'Start over',
    'quiz.resultEyebrow': 'A suggestion for you',
    'quiz.resultTitle': 'These kits fit your first step',
    'quiz.resultDescription': 'You do not need to buy everything. Choose one small project that makes you want to pick up a hook today.',
    'quiz.addKit': 'Add kit',
    'quiz.viewKit': 'View details',
    'quiz.noProducts': 'There are no matching products to recommend yet.',
    'quiz.question.experience': 'Where are you right now?',
    'quiz.option.experience.beginner': 'I am completely new',
    'quiz.option.experience.some': 'I have tried a few stitches',
    'quiz.question.project': 'What would you like to make first?',
    'quiz.option.project.flower': 'A small flower',
    'quiz.option.project.coaster': 'A useful coaster',
    'quiz.option.project.keychain': 'A lovely keychain',
    'quiz.option.project.tools': 'Practise the basics',
    'quiz.question.pace': 'What kind of rhythm do you prefer?',
    'quiz.option.pace.quick': 'A result in one or two sessions',
    'quiz.option.pace.calm': 'Slower, with more practice',
    'quiz.question.budget': 'What is your budget?',
    'quiz.option.budget.low': 'Light, under 200,000 VND',
    'quiz.option.budget.standard': 'A little more room, over 200,000 VND',
    'palette.eyebrow': 'Yarn colour studio',
    'palette.title': 'Build a palette with a feeling',
    'palette.description': 'Choose a suggested palette or tap individual colours to build a combo for your project.',
    'palette.presets': 'Suggested palettes',
    'palette.custom': 'Your palette',
    'palette.selected': '{count}/4 colours selected',
    'palette.copy': 'Copy colour codes',
    'palette.copied': 'Copied',
    'palette.save': 'Save palette',
    'palette.saved': 'Palette saved',
    'palette.remove': 'Remove colour',
    'palette.chooseColor': 'Choose {name}',
    'palette.limit': 'You can choose up to four colours.',
    'palette.addYarn': 'Add cotton yarn',
    'palette.viewYarn': 'View matching yarn',
    'palette.yarnNote': 'Practice cotton yarn comes in easy-to-see colours, making it a friendly first palette.',
    'palette.preset.meadow.name': 'Morning meadow',
    'palette.preset.meadow.description': 'Sage, cream and terracotta for a natural feeling.',
    'palette.preset.bloom.name': 'Flower garden',
    'palette.preset.bloom.description': 'Blush pink and butter yellow for cheerful small projects.',
    'palette.preset.cocoa.name': 'Warm cocoa',
    'palette.preset.cocoa.description': 'Earth brown, caramel and moss for a cosy craft corner.',
    'palette.preset.sky.name': 'Blue cloud',
    'palette.preset.sky.description': 'Sky blue, ocean blue and milk white for a gentle mood.',
    'card.demoPrice': 'demo price',
    'card.makeLabel': 'You can make',
    'card.add': 'Add',
    'cart.addToCart': 'Add to cart',
    'cart.product': 'product',
    'cart.added': 'Added',
    'cart.addedToCart': 'Added to cart',
    'cart.saveError': 'Could not save the cart',
    'card.readGuide': 'Read guide',
    'card.viewDetails': 'View details',
    'card.level.beginner': 'Beginner',
    'card.level.all': 'All levels',
    'products.eyebrow': 'Choose a comfortable tool',
    'products.title': 'Crochet products & kits',
    'products.description': 'Prices are illustrative for the project. Each kit clearly lists what is inside and what you can make with it.',
    'products.filter': 'Filter products',
    'products.category': 'Category',
    'products.allCategories': 'All categories',
    'products.level': 'Suitable level',
    'products.allLevels': 'All levels',
    'products.priceFrom': 'Price from (VND)',
    'products.priceTo': 'Price to (VND)',
    'products.unlimited': 'No limit',
    'products.applyFilter': 'Apply filters',
    'products.clearFilter': 'Clear filters',
    'products.listLabel': 'Product list',
    'products.matching': '{count} matching products',
    'products.sortLabel': 'Sort',
    'products.sortDefault': 'Default order',
    'products.sortAsc': 'Price: low to high',
    'products.sortDesc': 'Price: high to low',
    'products.sortName': 'Name A–Z',
    'products.apply': 'Apply',
    'products.emptyTitle': 'No matching products',
    'products.emptyDescription': 'Try removing a filter or browse all beginner kits.',
    'products.viewAll': 'View everything',
    'guides.eyebrow': 'Crochet learning corner',
    'guides.title': 'Guides for your first stitches',
    'guides.description': 'Read one guide, try one action, then come back when you are ready. English crochet terms use US notation and are explained along the way.',
    'guides.toolsHeading': 'Choose the right tools first',
    'guides.learnHeading': 'Find a comfortable rhythm',
    'guides.firstHeading': 'Make a small project you can hold',
    'detail.defaultCategory': 'Crochet tools',
    'detail.demoPrice': 'Demo price',
    'detail.projectSheet': 'Project sheet · Handmade project',
    'detail.level': 'Level',
    'detail.projects': 'Suggested projects',
    'detail.ideas': '{count} ideas',
    'detail.guides': 'Included guides',
    'detail.articles': '{count} articles',
    'detail.includes': 'What is in the kit?',
    'detail.canMake': 'What you can make',
    'detail.learnWithKit': 'Learn with this kit',
    'detail.guidesHeading': 'Included guides',
    'detail.readAtYourPace': 'Read first, make later — at your own pace.',
    'detail.openGuide': 'Open guide',
    'detail.relatedEyebrow': 'You may also like',
    'detail.related': 'Related products',
    'article.tableOfContents': 'Table of contents',
    'article.shortRead': 'A short read, following the natural flow.',
    'article.toolSuggestions': 'Tool suggestions',
    'article.noRelatedProducts': 'No related products yet.',
    'article.inArticleTools': 'Tools in this guide',
    'article.youMayNeed': 'You may need',
    'article.continueReading': 'Continue reading',
    'article.related': 'Related guides',
    'category.emptyTitle': 'This category is being updated',
    'category.emptyDescription': 'Browse all products to find something suitable.',
    'category.viewProducts': 'View products',
    'category.descriptionSuffix': 'Every product shows its recommended level and related guides.',
    'search.eyebrow': 'Find what you need',
    'search.resultsFor': 'Results for “{query}”',
    'search.title': 'Search products and guides',
    'search.description': 'Try a keyword with or without accents. MOCLEN STARTER searches names, descriptions, titles and related keywords.',
    'search.keyword': 'Search keyword',
    'search.example': 'Example: crochet hook, flower, coaster',
    'search.noResults': 'No results found',
    'search.noResultsDescription': 'Try a shorter keyword or remove accents, such as “kim moc” instead of a long sentence.',
    'search.clearQuery': 'Clear query',
    'search.wantToFind': 'What would you like to find?',
    'search.wantToFindDescription': 'Enter a product name, stitch or question you have.',
    'search.products': 'Products',
    'search.guides': 'Guides',
    'search.resultsCount': '{count} results',
    'about.eyebrow': 'About MOCLEN STARTER',
    'about.title': 'Starting with small, lovely things',
    'about.description': 'An experimental brand, a crochet learning corner and an illustrative kit shop for beginners.',
    'about.cardTitle': '5 friends, 1 craft corner',
    'about.cardDescription': 'This website was made for learning. Each part aims to stay useful, easy to change and honest about its demo status.',
    'about.contentTitle': 'A small website for beginners',
    'about.content1': 'MOCLEN STARTER began as an SEO project by a group of five students. Its goal is to turn “what do I need to buy first?” into an easier path: choose the right tool, read a short guide and try a first project.',
    'about.priorityTitle': 'What we care about',
    'about.priority': 'Natural content, clear kit descriptions and links that make sense in context. Prices are illustrative; products, orders and consultation requests exist for demonstration only.',
    'about.rhythmTitle': 'Learn at your own pace',
    'about.rhythm': 'Your first stitch does not need to be perfect. A slightly uneven circle, a row you need to undo or a split strand are all normal parts of learning. Start small, note what you tried and return to a guide whenever you need it.',
    'contact.eyebrow': 'Let us find a starting point together',
    'contact.title': 'Contact & get advice',
    'contact.description': 'Tell us what you would like to make or what is confusing you. This form only saves a request in the demo admin area; it is not connected to email.',
    'contact.smallThings': 'A few small things',
    'contact.smallThingsDescription': 'If you are unsure which hook or yarn to choose, tell us what you want to make and whether you have tried before.',
    'contact.response': 'Response',
    'contact.responseDescription': 'It will be visible in the admin area after it is saved.',
    'contact.configuredInfo': 'Contact details',
    'contact.emailNotConfigured': 'Contact email is not configured.',
    'contact.socialTitle': 'Social channels',
    'contact.address': 'Address',
    'contact.mapTitle': 'MOCLEN STARTER location map in Ngu Hanh Son, Da Nang',
    'contact.viewMap': 'Get directions on Google Maps',
    'contact.phone': 'Phone',
    'contact.formTitle': 'Send a consultation request',
    'form.name': 'Your name',
    'form.email': 'Email',
    'form.message': 'What would you like advice about?',
    'form.saving': 'Saving…',
    'form.saveConsultation': 'Save consultation request',
    'form.saved': 'Your request was saved. The team will review it in the admin area; no automatic email was sent.',
    'form.saveError': 'Could not save the request.',
    'form.sendError': 'Could not send the request.',
    'cart.eyebrow': 'Demo only',
    'cart.title': 'Your cart',
    'cart.description': 'You are only saving a temporary selection in this browser. The server creates a demo record when you create an order.',
    'cart.loading': 'Opening cart…',
    'cart.emptyTitle': 'Your cart is empty',
    'cart.emptyDescription': 'Choose a kit or a small tool, then come back to create a demo order.',
    'cart.viewProducts': 'View products',
    'cart.summary': 'Summary',
    'cart.quantity': 'Quantity',
    'cart.total': 'Reference total',
    'cart.notice': 'Demo order only; no payment or delivery. The server recalculates the price when saving.',
    'cart.createOrder': 'Create demo order',
    'cart.saving': 'Saving…',
    'cart.remove': 'Remove',
    'cart.decrease': 'Decrease {name}',
    'cart.increase': 'Increase {name}',
    'cart.delete': 'Remove {name} from cart',
    'cart.priceNote': 'demo price',
    'cart.orderSaved': 'Demo order {id} saved. Reference total: {total}.',
    'cart.orderError': 'Could not create the demo order.',
  },
};

type I18nContextValue = {
  language: Language;
  setLanguage: (language: Language) => void;
  t: (key: string, values?: Record<string, string | number>) => string;
};

const I18nContext = createContext<I18nContextValue | null>(null);

function interpolate(value: string, values?: Record<string, string | number>) {
  if (!values) return value;
  return value.replace(/\{(\w+)\}/g, (_, key: string) => String(values[key] ?? `{${key}}`));
}

export function I18nProvider({ children }: { children: ReactNode }) {
  const [language, setLanguageState] = useState<Language>('vi');
  const [ready, setReady] = useState(false);

  useEffect(() => {
    const frame = window.requestAnimationFrame(() => {
      const urlLanguage = new URLSearchParams(window.location.search).get('lang') ?? '';
      let stored = '';
      try {
        stored = window.localStorage.getItem('moc-len-language') ?? '';
      } catch {
        stored = '';
      }
      if (!stored) {
        stored = document.cookie.split('; ').find((item) => item.startsWith('moc-len-language='))?.split('=')[1] ?? '';
      }
      const browserLanguage = window.navigator.language.toLowerCase().startsWith('en') ? 'en' : 'vi';
      setLanguageState(urlLanguage === 'en' || urlLanguage === 'vi' ? urlLanguage : stored === 'en' || stored === 'vi' ? stored : browserLanguage);
      setReady(true);
    });
    return () => window.cancelAnimationFrame(frame);
  }, []);

  useEffect(() => {
    document.documentElement.lang = language;
    document.cookie = `moc-len-language=${language}; max-age=31536000; path=/; SameSite=Lax`;
    try {
      window.localStorage.setItem('moc-len-language', language);
    } catch {
      // Cookies remain as the fallback when localStorage is unavailable.
    }
  }, [language]);

  useEffect(() => {
    const preserveLanguage = (event: MouseEvent) => {
      const target = event.target as Element | null;
      const anchor = target?.closest('a');
      if (!anchor || anchor.target === '_blank' || !anchor.href) return;
      const url = new URL(anchor.href, window.location.href);
      if (url.origin !== window.location.origin) return;
      url.searchParams.set('lang', language);
      anchor.href = `${url.pathname}${url.search}${url.hash}`;
    };
    document.addEventListener('click', preserveLanguage);
    return () => document.removeEventListener('click', preserveLanguage);
  }, [language]);

  const value = useMemo<I18nContextValue>(() => ({
    language,
    setLanguage: (nextLanguage) => {
      setLanguageState(nextLanguage);
      if (typeof window !== 'undefined') {
        const url = new URL(window.location.href);
        url.searchParams.set('lang', nextLanguage);
        window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`);
      }
    },
    t: (key, values) => interpolate(messages[language][key] ?? messages.vi[key] ?? key, values),
  }), [language]);

  return <I18nContext.Provider value={value}><div className={`language-shell${ready ? ' is-ready' : ''}`}>{children}</div></I18nContext.Provider>;
}

export function useI18n() {
  const value = useContext(I18nContext);
  if (!value) throw new Error('useI18n must be used inside I18nProvider');
  return value;
}

export function translateUiLabel(value: string, language: Language) {
  const labels: Record<string, string> = language === 'en' ? {
    'Trang chủ': 'Home',
    'Sản phẩm': 'Shop',
    'Hướng dẫn': 'Guides',
    'Giới thiệu': 'About',
    'Liên hệ': 'Contact',
    'Giỏ hàng': 'Cart',
    'Tìm kiếm': 'Search',
    'Chính sách': 'Policies',
    'Quản trị': 'Admin',
    'Chọn bộ kit': 'Kit finder',
    'Phối màu len': 'Yarn colour studio',
  } : {};
  return labels[value] ?? value;
}
