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15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/**
 * @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<string[]>(["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<HTMLInputElement>) => {
    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 (
    <div className="space-y-6" id="terminal-settings-layout">
      {/* Splits layout settings versus encrypted backups */}
      <div className="grid grid-cols-1 xl:grid-cols-12 gap-6">
        {/* LEFT COLUMN: Corporate & System settings */}
        <div className="xl:col-span-7 bg-white border border-slate-200 rounded-xl p-5 shadow-sm space-y-6">
          <div className="flex items-center gap-2 border-b border-slate-100 pb-4 uppercase">
            <Settings className="w-5 h-5 text-slate-700 animate-spin" style={{ animationDuration: '6s' }} />
            <span className="text-xs font-bold text-slate-900">Corporate Terminal Configurations</span>
          </div>

          <form onSubmit={handleSaveSettingsSubmit} className="space-y-4 text-xs font-sans">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div className="space-y-1">
                <label className="text-[10px] text-slate-500 font-bold uppercase">Corporate Shop Name</label>
                <input 
                  type="text"
                  value={shopName}
                  onChange={(e)=>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"
                />
              </div>

              <div className="space-y-1">
                <label className="text-[10px] text-slate-500 font-bold uppercase">Shop Phone Helpline</label>
                <input 
                  type="text"
                  value={shopPhone}
                  onChange={(e)=>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"
                />
              </div>
            </div>

            <div className="space-y-1">
              <label className="text-[10px] text-slate-500 font-bold uppercase">Physical Address Coordinates</label>
              <input 
                type="text"
                value={shopAddress}
                onChange={(e)=>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"
              />
            </div>

            {/* CURRENCY INTEGRATION CHANGER */}
            <div className="bg-slate-50 border border-slate-200 p-4 rounded-lg space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-xs font-bold text-slate-850 flex items-center gap-1">
                  <Coins className="w-4 h-4 text-slate-700" />
                  Local Currency Integration
                </span>
                <span className="text-[10px] bg-slate-950 text-white font-mono font-medium px-2 py-0.5 rounded-md">
                  Active Preset: {currencyCode} ({currencySymbol})
                </span>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                <div className="space-y-1">
                  <label className="text-[9px] text-slate-400 font-bold uppercase">Currency Symbol</label>
                  <input 
                    type="text"
                    value={currencySymbol}
                    placeholder="e.g. ₨"
                    onChange={(e)=>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"
                  />
                </div>

                <div className="space-y-1">
                  <label className="text-[9px] text-slate-400 font-bold uppercase">Currency Code</label>
                  <input 
                    type="text"
                    value={currencyCode}
                    placeholder="e.g. PKR"
                    onChange={(e)=>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"
                  />
                </div>

                {/* Instant Presets */}
                <div className="space-y-1 flex flex-col justify-end">
                  <label className="text-[9px] text-slate-400 font-bold uppercase leading-none block mb-1">Fast Symbol Presets</label>
                  <div className="flex gap-1 justify-between font-mono font-semibold">
                    <button 
                      type="button"
                      onClick={() => selectCurrencyPreset('PKR', '₨')}
                      className="px-2 py-1.5 border border-slate-200 bg-white hover:bg-slate-50 text-[10px] rounded-md flex-1 cursor-pointer"
                    >
                      ₨ PKR
                    </button>
                    <button 
                      type="button"
                      onClick={() => selectCurrencyPreset('USD', '$')}
                      className="px-2 py-1.5 border border-slate-200 bg-white hover:bg-slate-50 text-[10px] rounded-md flex-1 cursor-pointer"
                    >
                      $ USD
                    </button>
                    <button 
                      type="button"
                      onClick={() => selectCurrencyPreset('AED', 'د.إ')}
                      className="px-2 py-1.5 border border-slate-200 bg-white hover:bg-slate-50 text-[10px] rounded-md flex-1 cursor-pointer"
                    >
                      د.إ AED
                    </button>
                  </div>
                </div>
              </div>
            </div>

            {/* TAX COMPILATION STRUCTURE */}
            <div className="bg-slate-50 border border-slate-200 p-4 rounded-lg space-y-3">
              <div className="flex items-center gap-1.5 text-xs font-bold text-slate-850">
                <Receipt className="w-4 h-4 text-slate-700 font-medium" />
                Automated Tax Calculation Engine
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1">
                  <label className="text-[9px] text-slate-400 font-bold uppercase">Tax Designation Name</label>
                  <input 
                    type="text"
                    value={taxName}
                    placeholder="e.g. Sales Tax (SRB)"
                    onChange={(e)=>setTaxName(e.target.value)}
                    className="w-full border border-slate-200 bg-white outline-none focus:border-slate-800 rounded-lg p-2"
                  />
                </div>

                <div className="space-y-1">
                  <label className="text-[9px] text-slate-400 font-bold uppercase">Combined Tax Rate (%)</label>
                  <input 
                    type="number"
                    step="0.1"
                    min="0"
                    max="90"
                    value={taxRate}
                    onChange={(e)=>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"
                  />
                </div>
              </div>
              <p className="text-[10px] text-slate-400 leading-normal italic">
                * When set, invoice generator computes total by multiplying subtotal against rating index, subtracting items discounts instantly.
              </p>
            </div>

            {/* OFFLINE MANAGE STATE */}
            <div className="bg-slate-50 border border-slate-200 p-4 rounded-lg flex items-center justify-between gap-4">
              <div className="space-y-1">
                <span className="text-xs font-bold text-slate-850 flex items-center gap-1">
                  {isOnline ? <Wifi className="w-4 h-4 text-emerald-600 animate-pulse" /> : <WifiOff className="w-4 h-4 text-orange-655" />}
                  Offline Mode Simulator
                </span>
                <p className="text-[10px] text-slate-400 leading-normal">
                  Turn offline mode on/off to test local caching queue and receipt buffer logs.
                </p>
              </div>

              <button
                type="button"
                onClick={onToggleOnlineMode}
                className={`text-xs font-semibold px-3.5 py-2.5 rounded-lg border transition shadow-sm cursor-pointer ${
                  isOnline 
                    ? 'bg-slate-900 border-transparent text-white hover:bg-slate-800' 
                    : 'bg-orange-600 border-transparent text-white hover:bg-orange-550'
                }`}
              >
                {isOnline ? "Simulate Disconnection" : "Connect Online Mode"}
              </button>
            </div>

            <div className="flex gap-4">
              <button 
                type="button"
                onClick={handleResetConfirm}
                className="bg-slate-50 hover:bg-slate-100 text-red-650 hover:text-red-750 font-medium border border-slate-200 px-4 py-2.5 rounded-lg transition cursor-pointer flex items-center gap-1.5 shadow-sm"
              >
                <RotateCcw className="w-4 h-4" />
                Wipe Local Database
              </button>
              <button
                type="submit"
                className="flex-1 bg-slate-900 hover:bg-slate-800 text-white font-medium text-xs px-6 py-2.5 rounded-lg transition cursor-pointer shadow flex items-center justify-center gap-2"
              >
                <Check className="w-4 h-4" />
                Commit Corporate Settings
              </button>
            </div>
          </form>
        </div>

        {/* RIGHT COLUMN: Encrypted Cloud Backups */}
        <div className="xl:col-span-5 bg-white border border-slate-200 rounded-xl p-5 shadow-sm flex flex-col justify-between">
          <div className="space-y-5">
            <div className="flex items-center gap-2 border-b border-slate-100 pb-4 uppercase">
              <Database className="w-4.5 h-4.5 text-slate-800 font-bold" />
              <span className="text-xs font-bold text-slate-900">Encrypted Backups Vault</span>
            </div>

            {/* Explainer warning */}
            <div className="bg-slate-50 border border-slate-200 p-4 rounded-lg space-y-1.5 text-xs text-slate-500">
              <span className="font-extrabold text-slate-800 flex items-center gap-1 uppercase tracking-wider text-[10px]">
                <Lock className="w-3.5 h-3.5 text-slate-705" />
                End-To-End Security Enforced
              </span>
              <p className="leading-relaxed text-[11px] text-slate-400">
                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.
              </p>
            </div>

            <div className="space-y-3 font-sans text-xs">
              <div className="space-y-1">
                <label className="text-[10px] text-slate-500 font-bold uppercase block text-center">Master Encryption Key / Cipher password</label>
                <input 
                  type="password"
                  value={vaultPassword}
                  onChange={(e) => 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"
                />
              </div>

              {/* Action buttons */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <button
                  type="button"
                  onClick={compileAndDownloadBackup}
                  className="bg-slate-900 hover:bg-slate-800 text-white text-xs font-medium py-2.5 px-3 rounded-lg flex items-center justify-center gap-1.5 shadow-sm transition cursor-pointer"
                >
                  <Download className="w-4 h-4" />
                  Save Secure Backup File
                </button>

                {/* Simulated live cloud database upload sync */}
                <button
                  type="button"
                  disabled={syncingCloud}
                  onClick={handleCloudSyncTrigger}
                  className="bg-white hover:bg-slate-100 text-slate-800 border border-slate-200 text-xs font-medium py-2.5 px-3 rounded-lg flex items-center justify-center gap-1.5 shadow-sm transition cursor-pointer"
                >
                  <Cloud className="w-4 h-4 text-slate-755" />
                  {syncingCloud ? "Uploading cipher..." : "Syndicate Cloud Backup"}
                </button>
              </div>

              {/* Restore drag files */}
              <div className="space-y-1 pt-2">
                <label className="text-[10px] text-slate-500 font-bold uppercase block mb-1">Import &amp; Restore Encrypted hbtback file</label>
                <div className="border border-dashed border-slate-200 rounded-lg p-4 text-center hover:bg-slate-50 bg-slate-50/50 transition relative flex flex-col items-center justify-center gap-2">
                  <Upload className="w-5 h-5 text-slate-400 font-light" />
                  <span className="text-[10px] text-slate-400">Drag or select a certified (.hbtback) document</span>
                  <input 
                    type="file" 
                    accept=".hbtback,.txt"
                    onChange={handleFileSelect}
                    className="absolute inset-0 opacity-0 cursor-pointer"
                  />
                </div>
              </div>
            </div>
          </div>

          {/* Secure cryptographic logs console view */}
          <div className="space-y-2 mt-6">
            <span className="text-[10px] text-slate-500 font-bold uppercase tracking-wider block">Cryptographic Secure Actions Telemetry</span>
            <div className="bg-slate-900 text-emerald-400 font-mono text-[10px] p-4 rounded-lg max-h-40 overflow-y-auto pr-1 leading-relaxed border border-slate-850 shadow-inner">
              {backupLogs.map((log, i) => (
                <div key={i} className="pb-1 border-b border-white/5 last:border-0">{log}</div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}