/** * @license * SPDX-License-Identifier: Apache-2.0 */ import React, { useState } from 'react'; import { motion } from 'motion/react'; import { Settings, Database, Cloud, Upload, Download, Check, AlertCircle, Lock, Wifi, WifiOff, RefreshCw, Coins, Receipt, RotateCcw } from 'lucide-react'; import { SystemSettings } from '../types'; import { encryptData, decryptData } from '../utils/backup'; interface SettingsProps { settings: SystemSettings; isOnline: boolean; onUpdateSettings: (settings: SystemSettings) => void; onToggleOnlineMode: () => void; onRestoreDatabase: (restoredData: { settings: SystemSettings; products: any[]; invoices: any[]; history: any[]; staff: any[]; }) => void; onClearCacheToDefault: () => void; // Passing actual values for backup compilation activeProducts: any[]; activeInvoices: any[]; activeHistory: any[]; activeStaff: any[]; } export default function SettingsComponent({ settings, isOnline, onUpdateSettings, onToggleOnlineMode, onRestoreDatabase, onClearCacheToDefault, activeProducts, activeInvoices, activeHistory, activeStaff }: SettingsProps) { // Input states const [shopName, setShopName] = useState(settings.shopName); const [shopAddress, setShopAddress] = useState(settings.shopAddress); const [shopPhone, setShopPhone] = useState(settings.shopPhone); const [taxName, setTaxName] = useState(settings.taxName); const [taxRate, setTaxRate] = useState(settings.taxRate); const [currencyCode, setCurrencyCode] = useState(settings.currencyCode); const [currencySymbol, setCurrencySymbol] = useState(settings.currencySymbol); // Backup vault password block const [vaultPassword, setVaultPassword] = useState('haider_secret_2026'); const [uploadedCipherString, setUploadedCipherString] = useState(''); const [backupLogs, setBackupLogs] = useState(["Secure Vault active. Ready for ledger encryption."]); const [syncingCloud, setSyncingCloud] = useState(false); const handleSaveSettingsSubmit = (e: React.FormEvent) => { e.preventDefault(); if (!shopName.trim() || !shopAddress.trim()) { alert("Corporate name and address parameters are required."); return; } onUpdateSettings({ shopName: shopName.trim(), shopAddress: shopAddress.trim(), shopPhone: shopPhone.trim(), taxName: taxName.trim(), taxRate: Math.max(0, parseFloat(taxRate.toString()) || 0), currencyCode: currencyCode.trim(), currencySymbol: currencySymbol.trim() }); alert("Corporate shop parameters synced across live terminal databases."); }; // Compile full database and export as locally encrypted block file (.hbtback) const compileAndDownloadBackup = () => { try { const fullPackage = { meta: { timestamp: new Date().toISOString(), version: "HBT-VAULT-2.0.0", author: "Haider Brother Traders" }, settings, products: activeProducts, invoices: activeInvoices, history: activeHistory, staff: activeStaff }; const plainText = JSON.stringify(fullPackage); const encrypted = encryptData(plainText, vaultPassword); // Create download elements const blob = new Blob([encrypted], { type: 'text/plain;charset=utf-8' }); const link = document.createElement('a'); link.href = URL.createObjectURL(blob); const dateStr = new Date().toISOString().split('T')[0]; link.download = `HBT_Vault_Backup_${dateStr}.hbtback`; link.click(); setBackupLogs(prev => [ `[${new Date().toLocaleTimeString()}] Secure Backup compiled: Encrypted ${activeInvoices.length} transactions and ${activeProducts.length} tire SKUs.`, ...prev ]); alert("Ledger Vault encrypted file downloaded to client machine successfully!"); } catch (err: any) { alert("Encryption failure: " + err.message); } }; // Read decrypted cipher files and trigger restore const handleUploadAndRestore = (fileContent: string) => { if (!fileContent.trim()) { alert("File is empty. Select a valid .hbtback backup."); return; } try { const plainText = decryptData(fileContent, vaultPassword); const decoded = JSON.parse(plainText); // Simple schema structure audit if (!decoded.settings || !decoded.products || !decoded.invoices || !decoded.history || !decoded.staff) { throw new Error("Target file has correct password but missing necessary entity logs."); } onRestoreDatabase({ settings: decoded.settings, products: decoded.products, invoices: decoded.invoices, history: decoded.history, staff: decoded.staff }); // Update local values instantly setShopName(decoded.settings.shopName); setShopAddress(decoded.settings.shopAddress); setShopPhone(decoded.settings.shopPhone); setTaxName(decoded.settings.taxName); setTaxRate(decoded.settings.taxRate); setCurrencyCode(decoded.settings.currencyCode); setCurrencySymbol(decoded.settings.currencySymbol); setBackupLogs(prev => [ `[${new Date().toLocaleTimeString()}] Restore complete: Imported ${decoded.invoices.length} invoices, ${decoded.products.length} tires and verified cashier registers.`, ...prev ]); alert("Encrypted vault records imported and restored successfully!"); } catch (err: any) { alert("Restoration Blocked! Error: " + err.message); } }; // Drag and drop file reader const handleFileSelect = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; const reader = new FileReader(); reader.onload = (event) => { const txt = event.target?.result as string; handleUploadAndRestore(txt); }; reader.readAsText(file); }; // Cloud Backups sync mock log const handleCloudSyncTrigger = () => { setSyncingCloud(true); setBackupLogs(prev => [`[${new Date().toLocaleTimeString()}] Securing cloud payload connection to Google Cloud Run servers...`, ...prev]); setTimeout(() => { setSyncingCloud(false); setBackupLogs(prev => [ `[${new Date().toLocaleTimeString()}] Cloud backup synced! Encrypted cache saved under vault block. Transaction status: EXCELLENT.`, ...prev ]); alert("Cloud Backup Synced! All sensitive business records securely logged to secondary vault storage."); }, 1500); }; const handleResetConfirm = () => { if (confirm("Are you absolutely sure you want to restore the entire tire shop back to default factory parameters? This deletes custom added items, current stock manual adjustments, and any newly compiled invoice draft data.")) { onClearCacheToDefault(); window.location.reload(); } }; // Quick Currency Preset selection const selectCurrencyPreset = (code: string, symbol: string) => { setCurrencyCode(code); setCurrencySymbol(symbol); }; return (
{/* Splits layout settings versus encrypted backups */}
{/* LEFT COLUMN: Corporate & System settings */}
Corporate Terminal Configurations
setShopName(e.target.value)} className="w-full border border-slate-200 bg-white outline-none focus:border-slate-800 rounded-lg p-2.5 font-semibold transition" />
setShopPhone(e.target.value)} className="w-full border border-slate-200 bg-white outline-none focus:border-slate-800 rounded-lg p-2.5 font-semibold transition" />
setShopAddress(e.target.value)} className="w-full border border-slate-200 bg-white outline-none focus:border-slate-800 rounded-lg p-2.5 font-semibold transition" />
{/* CURRENCY INTEGRATION CHANGER */}
Local Currency Integration Active Preset: {currencyCode} ({currencySymbol})
setCurrencySymbol(e.target.value)} className="w-full border border-slate-200 bg-white outline-none focus:border-slate-800 rounded-lg p-2 font-mono text-center font-bold" />
setCurrencyCode(e.target.value)} className="w-full border border-slate-200 bg-white outline-none focus:border-slate-800 rounded-lg p-2 font-mono text-center font-bold" />
{/* Instant Presets */}
{/* TAX COMPILATION STRUCTURE */}
Automated Tax Calculation Engine
setTaxName(e.target.value)} className="w-full border border-slate-200 bg-white outline-none focus:border-slate-800 rounded-lg p-2" />
setTaxRate(Math.min(90, Math.max(0, parseFloat(e.target.value) || 0)))} className="w-full border border-slate-200 bg-white outline-none focus:border-slate-800 rounded-lg p-2 font-mono font-bold" />

* When set, invoice generator computes total by multiplying subtotal against rating index, subtracting items discounts instantly.

{/* OFFLINE MANAGE STATE */}
{isOnline ? : } Offline Mode Simulator

Turn offline mode on/off to test local caching queue and receipt buffer logs.

{/* RIGHT COLUMN: Encrypted Cloud Backups */}
Encrypted Backups Vault
{/* Explainer warning */}
End-To-End Security Enforced

Under air-gapped terminal paradigms, Haider Brother Traders database is encrypted using rot-salt character ciphers with customized credentials keyframes. Passwords block third-party parsing.

setVaultPassword(e.target.value)} className="w-full border border-slate-200 bg-white p-2.5 font-mono text-slate-800 rounded-lg outline-none focus:border-slate-800 shadow-sm text-center tracking-widest text-sm" />
{/* Action buttons */}
{/* Simulated live cloud database upload sync */}
{/* Restore drag files */}
Drag or select a certified (.hbtback) document
{/* Secure cryptographic logs console view */}
Cryptographic Secure Actions Telemetry
{backupLogs.map((log, i) => (
{log}
))}
); }