/* i18n.js */
const translations = {
  en: {
    "please_log_in_to_continue": "Please log in to continue.",
    "no_files_selected": "No files selected.",
    "confirm_delete_files": "Are you sure you want to delete {count} selected file(s)?",
    "element_not_found": "Element with id \"{id}\" not found.",
    "search_placeholder": "Search files, tags, & uploader...",
    "search_placeholder_advanced": "Advanced Search: files, tags, uploader & content...",
    "basic_search_tooltip": "Basic Search: Search by file name, tags, and uploader.",
    "advanced_search_tooltip": "Advanced Search: Includes file content, in addition to file name, tags, and uploader.",
    "search_everywhere_title": "Search Everywhere",
    "search_everywhere_desc": "ACL-aware search across all folders you can access.",
    "search_everywhere_label": "Search everywhere",
    "search_everywhere_placeholder": "Type to search across all folders",
    "search_everywhere_limit": "Result limit",
    "search_everywhere_run": "Search",
    "search_everywhere_hint": "Results will appear here.",
    "search_everywhere_no_results": "No results",
    "search_everywhere_reindexed": "Index refreshed.",
    "search_everywhere_error": "Search failed.",
    "search_everywhere_source_label": "Source",
    "search_everywhere_source_all": "All sources",
    "file_name": "File Name",
    "date_modified": "Date Modified",
    "upload_date": "Upload Date",
    "file_size": "File Size",
    "uploader": "Uploader",
    "enter_totp_code": "Enter TOTP Code",
    "use_recovery_code_instead": "Use Recovery Code instead",
    "enter_recovery_code": "Enter Recovery Code",
    "editing": "Editing",
    "decrease_font": "A-",
    "increase_font": "A+",
    "save": "Save",
    "close": "Close",
    "no_files_found": "No files found.",
    "switch_to_table_view": "Switch to Table View",
    "switch_to_gallery_view": "Switch to Gallery View",
    "link_file": "Link File",
    "share_file": "Share File",
    "set_expiration": "Set Expiration:",
    "password_optional": "Password (optional):",
    "generate_share_link": "Generate Share Link",
    "shareable_link": "Shareable Link:",
    "copy_link": "Copy Link",
    "tag_file": "Tag File",
    "tag_name": "Tag Name:",
    "tag_color": "Tag Color:",
    "save_tag": "Save Tag",
    "no_tags_available": "No tags available",
    "current_tags": "Current Tags",
    "light_mode": "Light Mode",
    "dark_mode": "Dark Mode",
    "dual_pane_mode": "Enable dual-pane mode",
    "dual_pane_secondary_hint": "Select a folder to open here.",
    "dual_pane_secondary_empty": "Select a folder to open in the right pane.",
    "upload_instruction": "Drop files/folders here or click 'Choose files'",
    "no_files_selected_default": "No files selected",
    "choose_files": "Choose files",
    "upload_conflict_title": "Existing files detected",
    "upload_conflict_message": "Found {existing} of {total} files already in this folder ({same} same size, {diff} different size). Resume skips same-size files, Skip ignores all existing files, Overwrite reuploads everything.",
    "upload_conflict_resume": "Resume",
    "upload_conflict_skip": "Skip existing",
    "upload_conflict_overwrite": "Overwrite",
    "upload_conflict_all_skipped": "All selected files already exist.",
    "upload_conflict_skipped": "Skipped {count} existing file(s).",
    "resumable_cleanup_hours_label": "Resumable cleanup age (hours)",
    "resumable_cleanup_hours_help": "Deletes unfinished resumable uploads after this age. Applies to background sweeps and manual cleanup.",
    "resumable_cleanup_run_now": "Run cleanup now",
    "resumable_cleanup_run_now_help": "Immediately clears resumable temp folders, ignoring the age above.",
    "resumable_cleanup_running": "Running cleanup...",
    "resumable_cleanup_done": "Cleanup complete: removed {removed}, remaining {remaining}, checked {checked}.",
    "resumable_cleanup_done_sources": "Cleanup complete: removed {removed}, remaining {remaining}, checked {checked} across {sources} sources.",
    "resumable_cleanup_failed": "Resumable cleanup failed.",
    "resumable_cleanup_cron_title": "Cron example",
    "resumable_cleanup_cron_help": "Example hourly job: <code>0 * * * * /usr/bin/php /path/to/FileRise/src/cli/resumable_cleanup.php --all --respect-interval</code>",
    "resumable_cleanup_cron_note": "Replace /path/to/FileRise with your install path.",
    "delete_selected": "Delete Selected",
    "copy_selected": "Copy Selected",
    "move_selected": "Move Selected",
    "tag_selected": "Tag Selected",
    "download_zip": "Download Archive",
    "extract_zip": "Extract Archive",
    "preview": "Preview",
    "preview_too_large": "Preview too large to display.",
    "edit": "Edit",
    "rename": "Rename",
    "trash_empty": "Trash is empty.",
    "no_trash_selected": "No trash items selected for restore.",
    "loading_slow": "Please remain patient; loading may take a while for large files/folders.",

    // Additional keys for HTML translations:
    "title": "FileRise",
    "header_title": "FileRise",
    "header_title_text": "Header Title",
    "storage_source": "Source",
    "logout": "Logout",
    "change_password": "Change Password",
    "restore_text": "Restore or",
    "delete_text": "Delete Trash Items",
    "restore_selected": "Restore Selected",
    "restore_all": "Restore All",
    "delete_selected_trash": "Delete Selected",
    "delete_all": "Delete All",
    "upload_header": "Upload Files/Folders",

    // Folder Management keys:
    "folder_navigation": "Folder Navigation & Management",
    "create_folder": "Create Folder",
    "create_folder_title": "Create Folder",
    "enter_folder_name": "Enter folder name",
    "cancel": "Cancel",
    "create": "Create",
    "rename_folder": "Rename Folder",
    "rename_folder_title": "Rename Folder",
    "rename_folder_placeholder": "Enter new folder name",
    "delete_folder": "Delete Folder",
    "delete_folder_title": "Delete Folder",
    "delete_folder_message": "Are you sure you want to delete this folder?",
    "folder_help": "Folder Help",
    "folder_help_item_1": "Click on a folder in the tree to view its files.",
    "folder_help_item_2": "Use [-] to collapse and [+] to expand folders.",
    "folder_help_item_3": "Select a folder and click \"Create Folder\" to add a subfolder.",
    "folder_help_item_4": "To rename or delete a folder, select it and then click the appropriate button.",

    // File List keys:
    "actions": "Actions",
    "file_list_title": "Files in (Root)",
    "files_in": "Files in",
    "delete_files": "Delete Files",
    "delete_selected_files_title": "Delete Selected Files",
    "delete_files_message": "Are you sure you want to delete the selected files?",
    "copy_files": "Copy Files",
    "copy_files_title": "Copy Selected Files",
    "copy_files_message": "Select a target folder for copying the selected files:",
    "move_files": "Move Files",
    "move_files_title": "Move Selected Files",
    "move_files_message": "Select a target folder for moving the selected files:",
    "move": "Move",
    "extract_zip_button": "Extract Archive",
    "download_zip_title": "Download Selected Files as Archive",
    "download_zip_prompt": "Enter a name for the archive file:",
    "download_archive_format": "Archive format",
    "zip_placeholder": "files.zip",
    "share": "Share",
    "total_files": "Total Files",
    "total_size": "Total Size",
    "prev": "Prev",
    "next": "Next",
    "page": "Page",
    "of": "of",

    // Login Form keys:
    "login": "Login",
    "remember_me": "Remember me",
    "login_oidc": "Login with OIDC",
    "basic_http_login": "Use Basic HTTP Login",

    // Change Password keys:
    "change_password_title": "Change Password",
    "old_password": "Old Password",
    "new_password": "New Password",
    "confirm_new_password": "Confirm New Password",

    // Add User keys:
    "create_new_user_title": "Create New User",
    "username": "Username:",
    "password": "Password:",
    "enter_password": "Password",
    "preparing_download": "Preparing your download...",
    "download_file": "Download File",
    "confirm_or_change_filename": "Confirm or change the download file name:",
    "filename": "Filename",
    "cancel": "Cancel",
    "download": "Download",
    "grant_admin": "Grant Admin Access",
    "save_user": "Save User",

    // Remove User keys:
    "remove_user_title": "Remove User",
    "select_user_remove": "Select a user to remove:",
    "delete_user": "Delete User",

    // Rename File keys:
    "rename_file_title": "Rename File",
    "rename_file_placeholder": "Enter new file name",

    // Folder Share
    "share_folder": "Share Folder",
    "share_folder_and_request": "Share Folder / File Request",
    "share_folder_and_request_helper": "Create a normal shared link, or enable upload-only file request mode.",
    "share_mode_heading": "Link mode",
    "share_mode_browse_label": "Folder Share",
    "share_mode_browse_desc": "View/download shared files. Uploads are optional.",
    "share_mode_request_label": "Request Files",
    "share_mode_request_desc": "Upload-only drop link. Existing files stay hidden.",
    "share_mode_notice_browse": "Folder Share mode lets recipients browse and download files. Enable uploads if you also want file submissions.",
    "share_mode_notice_request": "Request Files mode is upload-only. Recipients cannot view or download existing files.",
    "share_link_settings": "Link settings",
    "share_upload_settings": "Upload settings",
    "allow_uploads": "Allow Uploads",
    "upload_only_file_drop": "Upload-only (File Request / File Drop)",
    "upload_only_helper": "Uploaders can't see existing files.",
    "allow_subfolders": "Include Subfolders",
    "allow_subfolders_helper": "Required for folder uploads in file request mode.",
    "share_uploading": "Uploading...",
    "share_uploading_progress": "Uploading... {pct}%",
    "share_upload_complete_refreshing": "Upload complete. Refreshing...",
    "share_upload_failed": "Upload failed.",
    "share_upload_failed_http": "Upload failed (HTTP {code}): {reason}",
    "share_upload_failed_message": "Upload failed: {reason}",
    "share_upload_network_error": "Network error. Please check your connection and try again.",
    "share_upload_selection_unavailable": "Selection unavailable",
    "share_upload_selection_read_error": "Could not read selected file.",
    "share_drop_root_label": "Upload files",
    "share_drop_rule_max_file_size": "Max file size: {mb} MB",
    "share_drop_rule_allowed_types": "Allowed types: {types}",
    "share_drop_rule_daily_file_limit": "Daily file limit: {count}",
    "share_drop_rule_daily_size_limit": "Daily size limit: {mb} MB",
    "share_drop_rule_preserve_structure": "Folder structure is preserved when available.",
    "share_drop_status_queued": "Queued",
    "share_drop_status_uploaded": "Uploaded",
    "share_drop_status_failed": "Failed",
    "share_drop_error_invalid_file": "Invalid file.",
    "share_drop_error_subfolders_disabled": "Skipped: subfolder uploads are not enabled for this share.",
    "share_drop_error_size_exceeded": "Skipped: file is larger than {mb} MB.",
    "share_drop_error_type_not_allowed": "Skipped: file type not allowed.",
    "share_link_generated": "Share Link Generated",
    "error_generating_share_link": "Error Generating Share Link",
    "custom": "Custom",
    "duration": "Duration",
    "seconds": "Seconds",
    "minutes": "Minutes",
    "hours": "Hours",
    "days": "Days",
    "custom_duration_warning": "⚠️ Using a long expiration may pose security risks. Use with caution.",

    // Folder
    "folder_share": "Share Folder / File Request",

    // Custom Confirm Modal keys:
    "yes": "Yes",
    "no": "No",
    "unsaved_changes_confirm": "You have unsaved changes. Are you sure you want to close without saving?",
    "delete": "Delete",
    "download": "Download",
    "upload": "Upload",
    "copy": "Copy",
    "extract": "Extract",
    "user": "User:",
    "unknown_error": "Unknown Error",
    "link_copied": "Link Copied to Clipboard",
    "file_link_create_failed": "Could not create file link.",
    "file_link_create_failed_detail": "Could not create file link: {error}",
    "file_link_invalid_or_expired": "This file link is invalid or expired.",
    "file_link_resolve_failed": "Could not open linked file.",
    "file_link_opened": "Opened linked file.",
    "weeks": "weeks",
    "months": "months",

    // Dark Mode Toggle
    "dark_mode_toggle": "Dark Mode",
    "light_mode_toggle": "Light Mode",
    "switch_to_light_mode": "Switch to light mode",
    "switch_to_dark_mode": "Switch to dark mode",

    // Admin Panel
    "header_settings": "Header Settings",
    "header_footer_settings": "Header, FileList, Language & Footer Settings",
    "default_language": "Default language",
    "default_language_help": "Used when a user has not chosen a language yet.",
    "shared_max_upload_size_bytes_title": "Shared Max Upload Size",
    "shared_max_upload_size_bytes": "Shared Max Upload Size (bytes)",
    "max_bytes_shared_uploads_note": "Enter maximum bytes allowed for shared-folder uploads",
    "manage_shared_links": "Manage Shared Links",
    "manage_shared_links_size": "Manage Shared Links & Upload Size Limit",
    "folder_shares": "Folder Shares",
    "file_requests": "File Requests",
    "file_shares": "File Shares",
    "shared_created_by": "by {user}",
    "loading": "Loading…",
    "error_loading_share_links": "Error loading share links",
    "share_deleted_successfully": "Share deleted successfully",
    "error_deleting_share": "Error deleting share",
    "password_protected": "Password protected",
    "no_shared_links_available": "No shared links available",

    // Sources (Pro)
    "sources": "Sources",
    "sources_enabled": "Enable sources",
    "sources_help": "Sources are separate roots; users only see sources they can access.",
    "source_add": "Add Source",
    "source_edit": "Edit Source",
    "source_delete": "Delete Source",
    "source_id": "Source ID",
    "source_name": "Source Name",
    "source_type": "Type",
    "source_enabled": "Enabled",
    "source_disable_trash": "Delete permanently",
    "source_disable_trash_help": "Delete permanently toggle: ON skips Trash and deletes immediately. OFF moves files to Trash (FileRise creates the trash folder on demand).",
    "source_trash_disabled_badge": "Trash off",
    "source_local_path": "Local path",
    "source_s3_bucket": "S3 bucket",
    "source_s3_region": "S3 region (optional)",
    "source_s3_endpoint": "S3 endpoint",
    "source_s3_prefix": "S3 prefix",
    "source_s3_access_key": "S3 access key",
    "source_s3_secret_key": "S3 secret key",
    "source_s3_session_token": "S3 session token",
    "source_s3_path_style": "Force path-style addressing",
    "source_sftp_host": "SFTP host",
    "source_sftp_port": "SFTP port",
    "source_sftp_username": "SFTP username",
    "source_sftp_password": "SFTP password",
    "source_sftp_private_key": "SFTP private key",
    "source_sftp_private_key_passphrase": "SFTP key passphrase",
    "source_sftp_root": "SFTP root path",
    "source_ftp_host": "FTP host",
    "source_ftp_port": "FTP port",
    "source_ftp_username": "FTP username",
    "source_ftp_password": "FTP password",
    "source_ftp_ssl": "Use FTPS (SSL)",
    "source_ftp_passive": "Passive mode",
    "source_ftp_root": "FTP root path",
    "source_gdrive_client_id": "Google client ID",
    "source_gdrive_client_secret": "Google client secret",
    "source_gdrive_refresh_token": "Google refresh token",
    "source_gdrive_root_id": "Root folder ID",
    "source_gdrive_drive_id": "Shared drive ID (optional)",
    "source_webdav_url": "WebDAV base URL",
    "source_webdav_username": "WebDAV username",
    "source_webdav_password": "WebDAV password",
    "source_webdav_root": "WebDAV root path",
    "source_webdav_verify_tls": "Verify TLS certificate",
    "source_smb_host": "SMB host",
    "source_smb_share": "SMB share",
    "source_smb_username": "SMB username",
    "source_smb_password": "SMB password",
    "source_smb_domain": "SMB domain (optional)",
    "source_smb_version": "SMB version",
    "source_smb_root": "SMB root path",
    "source_save": "Save Source",
    "source_list_empty": "No sources configured yet.",
    "source_test": "Test",
    "source_test_idle": "Not tested",
    "source_test_running": "Testing...",
    "source_test_ok": "Connected",
    "source_test_failed": "Failed",
    "source_test_error": "Test failed",
    "source_secret_note": "Secrets are never shown after saving. Leave blank to keep existing values.",
    "source_hint_button": "Show setup hints",
    "source_hint_local": "Use an absolute server path. Leave blank to use the default uploads root. Ensure the web user can read/write this path. If trash cannot be created, enable Delete permanently for this source.",
    "source_hint_s3": "Bucket is required.\nRegion is optional (defaults to us-east-1).\nEndpoint and path-style are for S3-compatible providers.\nPrefix is optional.",
    "source_hint_sftp": "Host and username are required.\nUse a password or private key.\nRoot is optional; blank uses the login directory.",
    "source_hint_ftp": "Host and username are required.\nPassive mode is recommended.\nRoot is optional; blank uses the login directory.",
    "source_hint_gdrive": "Create an OAuth client in Google Cloud.\nGet a refresh token with scope https://www.googleapis.com/auth/drive.\nRootId: drive.google.com/drive/folders/ID or blank for root.\nDriveId: set for shared drives.\nNative Docs/Sheets/Slides export as DOCX/XLSX/PPTX on download.",
    "source_hint_webdav": "Base URL and username are required.\nRoot is optional; blank uses the server root.\nDisable TLS verification only for self-signed certs.",
    "source_hint_smb": "Host, share, and username are required.\nDomain and root are optional.\nLeave SMB version on Auto unless your server requires a specific version.",

    // Gateway Shares (Pro)
    "gateway_shares": "Gateway Shares",
    "gateway_locked_body": "Expose a scoped source root over SFTP, S3, or MCP with generated start commands and safety checks.",
    "gateway_add": "Add Gateway",
    "gateway_edit": "Edit Gateway",
    "gateway_save": "Save Gateway",
    "gateway_name": "Name",
    "gateway_type": "Gateway Type",
    "gateway_source_id": "Source ID",
    "gateway_root_path": "Root Path",
    "gateway_mode": "Mode",
    "gateway_listen_addr": "Listen Address",
    "gateway_port": "Port",
    "gateway_bind": "Bind",
    "gateway_snippets": "Gateway snippets",
    "gateway_start_command": "Start command",
    "gateway_docker_compose": "docker-compose snippet",
    "gateway_systemd_unit": "systemd unit snippet",
    "gateway_include_secrets": "Include secrets on test",
    "gateway_secrets_warning": "Warning: snippets may include secrets. Handle output carefully.",
    "gateway_test_output": "Test output",
    "gateway_runtime_title": "Gateway runtime setup (managed recommended)",
    "gateway_runtime_line_1": "1) Managed Mode can install, start, stop, and restart rclone from this panel.",
    "gateway_runtime_line_2": "2) If rclone is missing, use Download + install or upload a custom binary.",
    "gateway_runtime_line_3": "3) In Docker/container setups, publish each gateway port (example: -p 2022:2022).",
    "gateway_runtime_line_4": "4) Use listen address 0.0.0.0 for LAN access; use 127.0.0.1 for local-only.",
    "gateway_runtime_line_5": "5) Manual snippets are advanced fallback; Test validates config only.",
    "gateway_runtime_docs": "Open Gateway setup guide",
    "gateway_command": "Command",
    "gateway_list_empty": "No gateway shares configured yet.",
    "gateway_name_required": "Gateway name is required.",
    "gateway_type_required": "Gateway type is required.",
    "gateway_port_invalid": "Port must be between 1024 and 65535.",
    "gateway_sftp_user": "SFTP user",
    "gateway_sftp_pass": "SFTP password",
    "gateway_sftp_authorized_keys": "Authorized keys",
    "gateway_sftp_user_required": "SFTP user is required.",
    "gateway_sftp_auth_required": "Provide SFTP password or authorized keys.",
    "gateway_s3_access_key": "S3 access key",
    "gateway_s3_secret_key": "S3 secret key",
    "gateway_s3_keys_required": "S3 access key and secret key are required.",
    "gateway_s3_keys_pair_required": "Provide both S3 access key and secret key.",
    "gateway_mcp_token": "MCP token (optional)",
    "gateway_mcp_token_hint": "Leave blank to keep existing token or auto-generate on create.",
    "gateway_secret_note": "Secrets are never shown after saving. Leave secret fields blank to keep existing values.",
    "gateway_saving": "Saving gateway...",
    "gateway_saved": "Gateway share saved.",
    "gateway_deleted": "Gateway share deleted.",
    "gateway_delete_confirm": "Delete gateway \"{name}\"?",
    "gateway_save_failed": "Failed to save gateway share.",
    "gateway_delete_failed": "Failed to delete gateway share.",
    "gateway_list_failed": "Failed to load gateway shares.",
    "gateway_test_ok": "Gateway config validation passed (service not started).",
    "gateway_test_failed": "Gateway test failed.",
    "gateway_count": "{count} gateway share(s).",
    "enabled": "Enabled",
    "disabled": "Disabled",

    // NEW KEYS ADDED FOR ADMIN, USER PANELS, AND TOTP MODALS:
    "admin_panel": "Admin Panel",
    "admin_search_audit_logging": "Search Everywhere & Audit Logging",
    "user_panel": "User Panel",
    "user_settings": "User Settings",
    "save_profile_picture": "Save Profile Picture",
    "please_select_picture": "Please select a picture",
    "profile_picture_updated": "Profile picture updated",
    "error_updating_picture": "Error updating profile picture",
    "trash_restore_delete": "Trash Restore/Delete",
    "restore_delete_hint": "Restore or permanently delete files from your trash. (Files in trash for over 3 days are auto-deleted.)",
    "recycle_bin": "Recycle Bin",
    "empty_recycle_bin": "Empty Recycle Bin",
    "totp_settings": "TOTP Settings",
    "enable_totp": "Enable TOTP",
    "language": "Language",
    "select_language": "Select Language",
    "english": "English",
    "spanish": "Spanish",
    "french": "French",
    "german": "German",
    "chinese_simplified": "Chinese (Simplified)",
    "polish": "Polish",
    "russian": "Russian",
    "japanese": "Japanese",
    "use_totp_code_instead": "Use TOTP Code instead",
    "submit_recovery_code": "Submit Recovery Code",
    "please_enter_recovery_code": "Please enter your recovery code.",
    "recovery_code_verification_failed": "Recovery code verification failed",
    "error_verifying_recovery_code": "Error verifying recovery code",
    "totp_verification_failed": "TOTP verification failed",
    "error_verifying_totp_code": "Error verifying TOTP code",
    "totp_setup": "TOTP Setup",
    "scan_qr_code": "Scan this QR code with your authenticator app.",
    "enter_totp_confirmation": "Enter the 6-digit code from your app to confirm setup:",
    "confirm": "Confirm",
    "please_enter_valid_code": "Please enter a valid 6-digit code.",
    "totp_enabled_successfully": "TOTP successfully enabled.",
    "error_generating_recovery_code": "Error generating recovery code",
    "error_loading_qr_code": "Error loading QR code.",
    "error_disabling_totp_setting": "Error disabling TOTP setting",
    "user_management": "Users, Groups & Access",
    "add_user": "Add User",
    "remove_user": "Remove User",
    "user_permissions": "User Permissions",
    "oidc_configuration": "OIDC Configuration",
    "oidc_provider_url": "OIDC Provider URL",
    "oidc_client_id": "OIDC Client ID",
    "oidc_client_secret": "OIDC Client Secret",
    "oidc_redirect_uri": "OIDC Redirect URI",
    "global_totp_settings": "Global TOTP Settings",
    "global_otpauth_url": "Global OTPAuth URL",
    "login_options": "Login Options",
    "login_webdav": "Login Options & WebDAV Access",
    "footer_text": "Footer Text",
    "header_colors": "Header Colors",
    "header_logo": "Header Logo",
    "disable_login_form": "Disable Login Form",
    "disable_basic_http_auth": "Disable Basic HTTP Auth",
    "disable_oidc_login": "Disable OIDC Login (OIDC Config Required to enable)",
    "save_settings": "Save Settings",
    "at_least_one_login_method": "At least one login method must remain enabled.",
    "settings_updated_successfully": "Settings updated successfully.",
    "error_updating_settings": "Error updating settings",
    "user_permissions_updated_successfully": "User permissions updated successfully.",
    "error_updating_permissions": "Error updating permissions",
    "no_users_found": "No users found.",
    "user_folder_only": "User Folder Only",
    "read_only": "Read Only",
    "disable_upload": "Disable Upload",
    "error_loading_users": "Error loading users",
    "save_permissions": "Save Permissions",
    "your_recovery_code": "Your Recovery Code",
    "please_save_recovery_code": "Please save this code securely. It will not be shown again and can only be used once.",
    "ok": "OK",
    "show": "Show",
    "items_per_page": "items per page",
    "columns": "Columns",
    "row_height": "Row Height",
    "api_docs": "API Docs",
    "show_folders_above_files": "Show folder strip above list",
    "display": "Display",
    "create_file": "Create File",
    "create_new_file": "Create New File",
    "enter_file_name": "Enter file name",
    "newfile_placeholder": "New file name",
    "file_created_successfully": "File created successfully!",
    "error_creating_file": "Error creating file",
    "file_created": "File created successfully!",
    "no_access_to_resource": "You do not have access to this resource.",
    "can_share": "Can Share",
    "bypass_ownership": "Bypass Ownership",
    "error_loading_user_grants": "Error loading user grants",
    "click_to_edit": "Click to edit",
    "folder_access": "Folder Access",
    "grant_folders_help": "Grant per-folder capabilities to each user. View (all) shows all contents; View (own) shows only the user's uploads. Write is file-level ops (upload/edit/rename/copy/delete/extract). Create is file-only; subfolders require Manage/Ownership. Manage/Ownership enables folder actions (create/rename/move/delete, grant access) and implies View (all), Write, and Share. Share File auto-enables View (own); Share Folder requires Manage/Ownership + View (all).",
    "grant_folders_help_short": "Per-folder access. Create is file-only; subfolders need Manage/Ownership. Share Folder needs Manage + View (all).",
    "help_more": "More",
    "help_less": "Less",
    "move_folder": "Move Folder",
    "move_folder_message": "Select a destination folder to move this folder to:",
    "move_folder_title": "Move this folder",
    "copy_folder": "Copy Folder",
    "copy_folder_message": "Select a destination folder to copy this folder to:",
    "copy_folder_title": "Copy this folder",
    "move_folder_success": "Folder moved successfully.",
    "move_folder_error": "Error moving folder.",
    "move_folder_invalid": "Invalid source or destination folder.",
    "move_folder_denied": "You do not have permission to move this folder.",
    "move_folder_same_dest": "Destination cannot be the source or one of its subfolders.",
    "move_folder_same_owner": "Source and destination must have the same owner.",
    "move_folder_confirm": "Are you sure you want to move this folder?",
    "move_folder_select_dest": "Select a destination folder",
    "move_folder_select_dest_help": "Choose where this folder should be moved to.",
    "acl_move_folder_label": "Move Folder (source)",
    "acl_move_folder_help": "Allows moving this folder to a different parent. Requires Manage or Ownership on the folder.",
    "acl_move_in_label": "Allow Moves Into This Folder (destination)",
    "acl_move_in_help": "Allows items or folders from elsewhere to be moved into this folder. Requires Manage on the destination folder.",
    "acl_move_folder_info": "Moving folders is restricted to folder owners or managers. Destination folders must also allow moves in.",
    "context_move_folder": "Move Folder...",
    "context_move_here": "Move Here",
    "context_move_cancel": "Cancel Move",
    "mark_as_viewed": "Mark as viewed",
    "viewed": "Viewed",
    "resumed_from": "Resumed from",
    "clear_progress": "Clear progress",
    "marked_viewed": "Marked as viewed",
    "progress_cleared": "Progress cleared",
    "previous": "Previous",
    "next": "Next",
    "watched": "Watched",
    "reset_progress": "Reset Progress",
    "color_folder": "Color folder",
    "choose_color": "Choose a color",
    "reset_default": "Reset",
    "save_color": "Save",
    "folder_color_saved": "Folder color saved.",
    "folder_color_cleared": "Folder color reset.",
    "load_more": "Load more",
    "loading": "Loading...",
    "no_access": "You do not have access to this resource.",
    "please_select_valid_folder": "Please select a valid folder.",
    "folder_help_click_view": "Click a folder in the tree to view its files.",
    "folder_help_expand_chevrons": "Use chevrons to expand/collapse. Locked folders (padlock) can expand but can’t be opened.",
    "folder_help_context_menu": "Right-click a folder for quick actions: Create, Move, Rename, Share, Color, Delete.",
    "folder_help_drag_drop": "Drag a folder onto another folder or a breadcrumb to move it.",
    "folder_help_load_more": "For long lists, click “Load more” to fetch the next page of folders.",
    "folder_help_last_folder": "Your last opened folder is remembered. If you lose access, we pick the first allowed folder automatically.",
    "folder_help_breadcrumbs": "Use the breadcrumb to jump up the path. You can also drop onto a breadcrumb.",
    "folder_help_permissions": "Buttons enable/disable based on your permissions for the selected folder.",
    "load_more_folders": "Load More Folders",
    "show_inline_folders": "Show folders as rows above files",
    "name": "Name",
    "size": "Size",
    "modified": "Modified",
    "created": "Created",
    "owner": "Owner",
    "hide_header_zoom_controls": "Hide header zoom controls",
    "preview_not_available": "Preview is not available for this file type.",
    "storage_pro_bundle_outdated": "Please upgrade to the latest FileRise Pro bundle to use the Storage explorer.",
    "svg_preview_disabled": "SVG preview is disabled for now for security reasons.",
    "no_files_or_folders": "No files or folders.",
    "no_preview_available": "No preview available.",
    "more_actions": "More Actions",
    "folder_actions": "Folder Actions",
    "disable_hover_preview": "Disable hover preview in file list",
    "show_hover_preview": "Show hover preview in file list",
    "hover_preview_delay_ms": "Hover preview delay (ms)",
    "hover_preview_delay_help": "Wait before showing hover preview. Set 0 for instant preview (range: 0-2500 ms).",
    "view_options": "View Options",
    "zoom_in": "Zoom In",
    "zoom_out": "Zoom Out",
    "rotate_left": "Rotate Left",
    "rotate_right": "Rotate Right",
    "download_plain": "Download (no ZIP)",
    "download_next": "Download next",
    "nonzip_queue_title": "Files queued for download",
    "nonzip_queue_subtitle": "{count} files queued. Click \"Download next\" for each file.",
    "nonzip_queue_cleared": "Download queue cleared.",
    "your_access": "Your access",

    "perm_upload": "Upload",
    "perm_move":   "Move",
    "perm_rename": "Rename",
    "perm_share":  "Share",
    "perm_delete": "Delete",
    "clamav_scanning_title": "Scanning uploads for viruses…",
    "clamav_scanning_desc":"Uploads may take a little longer while antivirus scanning is enabled.",
    "oidc_quick_test_label": "Quick OIDC connectivity test",
    "oidc_test_button": "Test OIDC discovery",
    "clamav_enable_label": "Enable ClamAV scanning for uploads",
    "clamav_scan_uploads_help": "Files are scanned with ClamAV before being accepted. This may impact upload speed.",
    "clamav_env_locked_help": "Controlled by container env VIRUS_SCAN_ENABLED ({state}). Change it in your Docker/host env.",

    "filter_folders": "Filter folders by name",
    "view_own": "View (Own)",
    "view_all": "View (All)",
    "write": "Write",
    "manage": "Manage",
    "enter_search_term": "Enter search term",

    "csrf_error": "Invalid CSRF token.",
    "day": "day",
    "downloads_started": "All downloads started.",
    "enter_tag_name": "Please enter a tag name.",
    "error_generating_share": "Error generating share link.",
    "error_updating_totp_setting": "Error updating TOTP setting.",
    "extension": "Extension",
    "file": "File",
    "file_not_editable": "File is not editable.",
    "filter_by_tag": "Filter by tag",
    "folder": "Folder",
    "no_files_queued": "No files queued.",
    "no_folder_access_yet": "No folder access has been assigned to your account yet.",
    "none": "None",
    "path": "Path",
    "permissions": "Permissions",
    "please_sign_in_again": "Please sign in again.",
    "reset_zoom": "Reset Zoom",
    "root_folder": "Root folder",
    "select_folder": "Select a folder first.",
    "select_single_file": "Select a single file.",
    "too_many_plain_downloads": "You selected {count} files. For more than {limit} files, please use \"Download as Archive\".",
    "zoom": "Zoom",

    "portal_label_default": "Client Portal",
    "portal_login_heading_default": "Sign in to Client Portal",
    "portal_login_heading_with_title": "Sign in to {title}",
    "portal_login_subtitle": "to access this client portal",
    "portal_login_label_user": "Username or email",
    "portal_login_label_password": "Password",
    "portal_login_sign_in": "Sign in",
    "portal_login_signing_in": "Signing in…",
    "portal_login_hint": "You’ll be sent back to the portal automatically after signing in.",
    "portal_login_error_required": "Username and password are required.",
    "portal_login_error_default": "Login failed.",
    "portal_login_error_failed_retry": "Login failed. Please try again.",
    "portal_login_doc_title": "Sign in – {title}",

    "portal_doc_title": "{title}",
    "portal_form_heading": "Your details",
    "portal_form_hint": "Please fill in your information before uploading files.",
    "portal_form_label_name": "Name",
    "portal_form_label_email": "Email",
    "portal_form_label_reference": "Reference / Case / Order #",
    "portal_form_label_notes": "Notes",
    "portal_form_continue": "Continue",
    "portal_dropzone_drop_here": "Drop files here",
    "portal_dropzone_browse": "or click to browse.",
    "portal_dropzone_uploads_note": "Files will be uploaded to this portal only.",
    "portal_files_heading": "Files in this portal",
    "portal_files_refresh": "Refresh",
    "portal_files_loading": "Loading files…",
    "portal_files_error": "Error loading files.",
    "portal_files_empty": "No files in this portal yet.",
    "portal_file_unnamed": "Unnamed file",
    "portal_file_badge": "FILE",
    "portal_files_more": "And {count} more…",
    "portal_thankyou_heading": "Thank you!",
    "portal_thankyou_message": "Your files have been uploaded.",
    "portal_thankyou_default": "Your files have been uploaded successfully.",
    "portal_form_error_save": "Error saving form.",
    "portal_form_missing_fields": "Please fill in: {fields}.",
    "portal_form_require_one": "Please provide at least a name or email.",
    "portal_form_thanks_ready": "Thank you. You can now upload files.",
    "portal_form_save_failed": "Error saving your info. Please try again.",
    "portal_loading_details": "Loading portal details…",
    "portal_not_found": "Portal not found.",
    "portal_status_not_found": "This portal could not be found or is no longer available.",
    "portal_toast_not_found": "Portal not found or expired.",
    "portal_desc_uploads_to": "Files you upload here go directly into: {folder}",
    "portal_desc_max_file_size": "Max file size: {size} MB",
    "portal_desc_allowed_types": "Allowed types: {types}",
    "portal_desc_daily_limit": "Daily upload limit: {count} file(s)",
    "portal_mode_upload_download": "Upload & download",
    "portal_mode_upload_only": "Upload only",
    "portal_mode_download_only": "Download only",
    "portal_mode_access_only": "Access only",
    "portal_uploads_disabled": "Uploads are disabled for this portal.",
    "portal_upload_limit_reached": "Daily upload limit reached for this portal.",
    "portal_upload_limit_remaining": "You can only upload {count} more file(s) today for this portal.",
    "portal_upload_form_required": "Please fill in your details before uploading.",
    "portal_upload_skipped_size": "Skipped {count} file(s) over {size} MB.",
    "portal_upload_skipped_types": "Skipped {count} file(s) not matching allowed types: {types}",
    "portal_upload_none_after_rules": "No files to upload after applying portal rules.",
    "portal_upload_blocked": "Upload blocked by daily limit.",
    "portal_uploading": "Uploading {count} file(s)…",
    "portal_upload_success": "Uploaded {count} file(s).",
    "portal_upload_partial": "Uploaded {count} file(s), {failed} failed.",
    "portal_upload_failed": "Upload failed.",
    "portal_upload_complete": "Upload complete.",
    "portal_upload_some_failed": "Some files failed to upload.",
    "portal_missing_slug": "Missing portal slug.",
    "portal_slug_missing_url": "Portal slug missing in URL.",
    "portal_ready": "Ready.",
    "portal_init_error": "Unexpected error initializing portal.",
    "portal_load_error": "Unexpected error loading portal.",

    // Action + toast messages
    "already_in_target_folder": "Already in target folder.",
    "app_load_failed": "Failed to load app.",
    "archive_name_required": "Please enter a name for the archive file.",
    "archive_prepare_failed": "Failed to prepare archive.",
    "copy_files_error": "Error copying files: {error}",
    "copy_files_error_default": "Could not copy files.",
    "copy_files_success": "Selected files copied successfully!",
    "copy_folder_success": "Folder copied.",
    "copy_same_folder_error": "Cannot copy files to the same folder.",
    "copy_target_folder_required": "Please select a target folder for copying.",
    "create_folder_error": "Error creating folder: {error}",
    "create_folder_success": "Folder created!",
    "csrf_refresh_failed": "Could not refresh CSRF token. Please reload.",
    "delete_files_error": "Error deleting files: {error}",
    "delete_files_error_default": "Could not delete files.",
    "delete_files_success": "Selected files deleted successfully!",
    "delete_folder_error": "Error deleting folder: {error}",
    "delete_folder_error_default": "Could not delete folder.",
    "delete_folder_success": "Folder deleted successfully!",
    "dest_cannot_be_descendant": "Destination cannot be the source or its descendant.",
    "download_file_name_required": "Please enter a name for the file.",
    "download_started": "Download started. Check your browser’s download manager.",
    "encrypted_download_limit": "In encrypted folders, downloads are limited to {limit} file(s) at a time.",
    "enter_folder_name_prompt": "Please enter a folder name.",
    "enter_new_folder_name": "Please enter a valid new folder name.",
    "error_generic": "Error",
    "error_prefix": "Error: {error}",
    "extract_error_generic": "Error extracting archive files.",
    "extract_error_prefix": "Error extracting archive: {error}",
    "extract_error_some_failed": "Some files failed to extract.",
    "extract_result_default": "Archive extracted.",
    "extract_result_files": "Extracted: {files}",
    "extract_result_warning": "{result} Warning: {warning}",
    "extracting_files": "Extracting files…",
    "file_edit_too_large": "This file is larger than {size} MB and cannot be edited in the browser.",
    "fill_all_fields": "Please fill in all fields.",
    "folder_crypto_failed": "Folder crypto failed.",
    "folder_crypto_failed_detail": "Folder crypto failed: {error}",
    "folder_decryption_completed": "Folder decryption completed.",
    "folder_encryption_completed": "Folder encryption completed.",
    "folder_encryption_disabled": "Folder encryption disabled.",
    "folder_encryption_enabled": "Folder encryption enabled.",
    "folder_encryption_estimate_failed": "Failed to estimate folder encryption work.",
    "folder_encryption_start_failed": "Failed to start folder encryption.",
    "folder_encryption_update_failed": "Failed to update folder encryption.",
    "folders_view_denied": "You don't have permission to view folders.",
    "invalid_destination": "Invalid destination.",
    "invalid_drag_data": "Invalid drag data.",
    "keyboard_shortcuts_help": "Shortcuts: / search, ? help, Del delete, F2 rename, F3 preview, F4 edit, F5 copy, F6 move, F7 new folder, F8 delete, Ctrl/Cmd+Shift+N new folder.",
    "login_failed": "Login failed",
    "login_failed_detail": "Login failed: {error}",
    "login_session_not_established": "Login session not established",
    "login_try_again": "You can now try logging in again.",
    "move_failed": "Move failed",
    "move_file_success_to": "Moved \"{name}\" to {folder}.",
    "move_files_error": "Error moving files: {error}",
    "move_files_error_default": "Could not move files.",
    "move_files_error_generic": "Error moving files.",
    "move_files_success": "Selected files moved successfully!",
    "move_files_success_to": "Moved {count} file(s) to {folder}.",
    "move_folder_error_default": "Could not move folder.",
    "move_folder_error_detail": "Error moving folder: {error}",
    "move_folder_success_named_to": "Moved folder \"{name}\" to {folder}.",
    "move_folder_success_named_from_to": "Moved folder \"{name}\" from {source} to {folder}.",
    "move_folder_success_to": "Folder moved to {folder}.",
    "move_same_folder_error": "Cannot move files to the same folder.",
    "move_target_folder_required": "Please select a target folder for moving.",
    "no_archive_files_selected": "No archive files selected.",
    "no_files_selected_for_copy": "No files selected for copying.",
    "no_files_selected_for_download": "No files selected for download.",
    "no_files_selected_for_move": "No files selected for moving.",
    "no_files_to_move": "No files to move.",
    "onlyoffice_disabled_encrypted": "ONLYOFFICE is disabled inside encrypted folders.",
    "onlyoffice_open_failed": "Unable to open ONLYOFFICE editor.",
    "password_change_disabled_demo": "Password changes are disabled on the public demo.",
    "password_change_error": "Error changing password: {error}",
    "password_change_error_default": "Could not change password.",
    "password_change_error_generic": "Error changing password.",
    "passwords_do_not_match": "New passwords do not match.",
    "pick_destination": "Pick a destination",
    "recycle_bin_empty_unavailable": "Empty recycle bin action is not available.",
    "remove_user_none": "No other users found to remove.",
    "rename_file_error": "Error renaming file: {error}",
    "rename_file_error_generic": "Error renaming file.",
    "rename_file_success": "File renamed successfully!",
    "rename_folder_error": "Error renaming folder: {error}",
    "rename_folder_error_default": "Could not rename folder.",
    "rename_folder_success": "Folder renamed successfully!",
    "select_folder_delete": "Please select a valid folder to delete.",
    "select_folder_rename": "Please select a valid folder to rename.",
    "select_folder_share": "Please select a valid folder to share.",
    "select_non_root_folder_move": "Select a non-root folder to move.",
    "select_user_remove_prompt": "Please select a user to remove.",
    "setup_create_user_failed": "Failed to create user. Check server logs.",
    "setup_enter_username_password": "Enter a username and password.",
    "setup_no_users": "Setup mode: No users found. Please add an admin user.",
    "source_dest_same": "Source and destination are the same.",
    "upload_aborted": "Upload was aborted.",
    "upload_failed_some": "Some files failed to upload. Please check the list.",
    "upload_may_have_failed": "Some files may have failed to upload. Please check the list.",
    "upload_network_error": "Upload failed due to a network error.",
    "upload_pasted_added": "Pasted file added to upload list.",
    "upload_read_error": "Could not read the selected file.",
    "upload_resumable_started": "Resumable upload started...",
    "upload_summary_failed": "{failed} file(s) failed, {succeeded} succeeded. Please check the list.",
    "upload_summary_success": "{succeeded} file(s) succeeded. Please check the list.",
    "user_add_error": "Error adding user: {error}",
    "user_add_error_default": "Could not add user.",
    "user_add_success": "User added successfully!",
    "user_remove_error": "Error removing user: {error}",
    "user_remove_error_default": "Could not remove user.",
    "user_remove_success": "User removed successfully!",
    "username_password_required": "Username and password are required!",
    "portal_language_label": "Language",
    "admin_onlyoffice_csp_copied": "CSP snippet copied.",
    "admin_onlyoffice_copy_failed": "Copy failed.{reason}",
    "admin_onlyoffice_copy_failed_reason_insecure": " Insecure context; use HTTPS.",
    "admin_onlyoffice_select_prompt": "Press Ctrl+C to copy.",
    "nothing_to_save": "Nothing to save.",
    "admin_group_name_required": "Group name is required.",
    "admin_groups_save_error": "Error saving groups.",
    "admin_groups_saved": "Groups saved.",
    "admin_group_access_updated": "Group access updated.",
    "admin_portals_users_add": "Use “Manage users” to add a user.",
    "admin_portals_users_access": "Use “Folder access” to manage portal user access.",
    "admin_portals_users_groups": "Use “User groups” to manage groups.",
    "admin_portal_open_folder_picker_failed": "Unable to open folder picker.",
    "admin_portal_slug_required": "Portal slug is required to upload a logo.",
    "admin_portal_logo_uploaded": "Portal logo uploaded.",
    "admin_portal_logo_upload_error": "Logo upload failed: {error}",
    "admin_portal_preset_applied": "Preset applied: {label}.",
    "admin_portal_no_submissions_export": "No submissions to export.",
    "admin_portal_submissions_load_error": "Error loading submissions: {error}",
    "admin_portal_no_submissions_yet": "No submissions yet.",
    "admin_portal_slug_folder_required": "Please fill slug and folder for: {list}",
    "admin_portal_saved": "Client portals saved.",
    "admin_portal_save_error": "Error saving client portals: {error}",
    "admin_csv_download_failed": "Failed to download CSV.",
    "admin_oidc_test_failed_detail": "OIDC test failed: {error}",
    "admin_oidc_discovery_reachable": "OIDC discovery succeeded.",
    "admin_oidc_test_failed_console": "OIDC test failed. Check the console for details.",
    "admin_oidc_snapshot_failed": "Failed to load OIDC snapshot. Check the console for details.",
    "admin_clamav_selftest_ok": "ClamAV self-test succeeded.",
    "admin_clamav_test_failed_console": "ClamAV test failed. Check the console for details.",
    "admin_source_required_fields": "Please complete all required fields.",
    "admin_source_s3_bucket_required": "S3 bucket is required.",
    "admin_source_sftp_host_required": "SFTP host is required.",
    "admin_source_sftp_auth_required": "Provide an SFTP password or private key.",
    "admin_source_ftp_host_required": "FTP host is required.",
    "admin_source_webdav_base_required": "WebDAV base URL is required.",
    "admin_source_webdav_password_required": "WebDAV password is required.",
    "admin_source_smb_host_required": "SMB host is required.",
    "admin_source_smb_password_required": "SMB password is required.",
    "admin_source_gdrive_client_required": "Google client ID is required.",
    "admin_source_gdrive_secret_required": "Google client secret is required.",
    "admin_source_test_failed_detail": "Source test failed: {error}{note}",
    "admin_source_test_left_disabled_note": " Source left disabled.",
    "admin_source_test_failed_left_disabled": "Source test failed and was left disabled.",
    "admin_source_test_failed_disable_error": "Failed to disable source after test failure.",
    "key_file_created": "Key file created.",
    "key_file_cleared": "Key file cleared.",
    "saving_source_toast": "Saving source...",
    "admin_key_file_locked_env": "Key file is locked by env override.",
    "admin_encryption_not_supported": "Encryption at rest is not supported on this server.",
    "admin_share_delete_forbidden": "Forbidden while deleting share (check CSRF/session).",
    "admin_pro_feature_user_groups": "User Groups are a FileRise Pro feature. Visit filerise.net to purchase a license.",
    "admin_pro_feature_portals": "Client Portals are a FileRise Pro feature. Visit filerise.net to purchase a license.",
    "admin_logo_choose_image": "Please choose an image first.",
    "admin_logo_upload_error": "Error uploading logo.",
    "admin_logo_uploaded_reminder": "Logo uploaded. Don't forget to save settings.",
    "admin_license_file_invalid": "Could not find a valid FRP1 license in that file.",
    "admin_license_loaded_prompt": "License loaded from file. Click “Save license” to apply.",
    "admin_license_read_error": "Error reading license file.",
    "admin_license_copied": "License copied to clipboard.",
    "admin_license_copy_failed": "Could not copy license. Please copy it manually.",
    "admin_instance_id_copied": "Instance ID copied to clipboard.",
    "admin_instance_id_copy_failed": "Could not copy Instance ID. Please copy it manually.",
    "admin_license_saved": "License saved.",
    "admin_license_save_error": "Error saving license.",
    "admin_pro_install_failed_detail": "Download/install failed: {error}",
    "admin_pro_installed_reloading": "Pro bundle installed{version}. Reloading...",
    "admin_pro_install_failed": "Download/install failed.",
    "admin_audit_logs_unavailable": "Audit Logs are not available.",
    "admin_settings_saved": "Settings saved.",
    "admin_settings_save_failed": "Save failed."
  
  },
};

const localeLoaders = {
  de: () => import(new URL('./i18n/locales/de.js?v={{APP_QVER}}', import.meta.url)),
  es: () => import(new URL('./i18n/locales/es.js?v={{APP_QVER}}', import.meta.url)),
  fr: () => import(new URL('./i18n/locales/fr.js?v={{APP_QVER}}', import.meta.url)),
  ja: () => import(new URL('./i18n/locales/ja.js?v={{APP_QVER}}', import.meta.url)),
  pl: () => import(new URL('./i18n/locales/pl.js?v={{APP_QVER}}', import.meta.url)),
  ru: () => import(new URL('./i18n/locales/ru.js?v={{APP_QVER}}', import.meta.url)),
  'zh-CN': () => import(new URL('./i18n/locales/zh-CN.js?v={{APP_QVER}}', import.meta.url)),
};

const localePromises = {};

async function loadLocale(locale) {
  if (!locale || translations[locale]) return true;
  const loader = localeLoaders[locale];
  if (!loader) return false;
  if (!localePromises[locale]) {
    localePromises[locale] = loader()
      .then((mod) => {
        if (mod && mod.default) {
          translations[locale] = mod.default;
          return true;
        }
        return false;
      })
      .catch((err) => {
        console.warn(`[i18n] Failed to load locale "${locale}"`, err);
        return false;
      });
  }
  return localePromises[locale];
}

let currentLocale = 'en';

export async function setLocale(locale) {
  const next = locale || 'en';
  if (next === 'en') {
    currentLocale = 'en';
    return currentLocale;
  }
  const loaded = await loadLocale(next);
  currentLocale = loaded ? next : 'en';
  return currentLocale;
}

export function t(key, placeholders) {
  const localeTranslations = translations[currentLocale] || {};
  const baseTranslations = translations.en || {};
  let translation = localeTranslations[key] || baseTranslations[key] || key;
  if (placeholders) {
    Object.keys(placeholders).forEach(ph => {
      translation = translation.replace(`{${ph}}`, placeholders[ph]);
    });
  }
  return translation;
}

export function applyTranslations() {
  document.querySelectorAll('[data-i18n-key]').forEach(el => {
    el.innerText = t(el.getAttribute('data-i18n-key'));
  });
  document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
    el.setAttribute('placeholder', t(el.getAttribute('data-i18n-placeholder')));
  });
  document.querySelectorAll('[data-i18n-title]').forEach(el => {
    el.setAttribute('title', t(el.getAttribute('data-i18n-title')));
  });
  try {
    window.dispatchEvent(new CustomEvent('filerise:i18n-applied', {
      detail: { locale: currentLocale }
    }));
  } catch (e) { /* ignore */ }
}
