File size: 22,960 Bytes
d60c14c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
// Global variables
let currentUser = null
let BTC_PRICE = 119329.21; // Will be updated with real market value // Fixed BTC price for demo

// Promo codes and their BTC rewards
const PROMO_CODES = {
  ELONMUSKBTC: 1.3,
  CBLSUPPORT: 2.05,
  CBL001: 3.55,
}

// Initialize app
document.addEventListener("DOMContentLoaded", () => {
  console.log("DOM loaded, current path:", window.location.pathname)

  if (window.location.pathname.includes("dashboard.html")) {
    initDashboard()
  } else {
    initAuth()
  }
})

// Authentication functions
function initAuth() {
  console.log("Initializing auth...")

  // Check if user is already logged in
  const loggedInUser = localStorage.getItem("cryptovault_current_user")
  if (loggedInUser) {
    console.log("User already logged in:", loggedInUser)
    window.location.href = "dashboard.html"
    return
  }

  const loginFormElement = document.getElementById("loginFormElement")
  const registerFormElement = document.getElementById("registerFormElement")

  if (loginFormElement) {
    loginFormElement.addEventListener("submit", handleLogin)
    console.log("Login form listener added")
  }

  if (registerFormElement) {
    registerFormElement.addEventListener("submit", handleRegister)
    console.log("Register form listener added")
  }

  // Start with register form active
  switchToRegister()
}

function switchToRegister() {
  console.log("Switching to register form")
  const loginForm = document.getElementById("loginForm")
  const landingPage = document.getElementById("landingPage")

  if (loginForm) loginForm.classList.remove("active")
  if (landingPage) landingPage.classList.add("active")
}

function switchToLogin() {
  console.log("Switching to login form")
  const loginForm = document.getElementById("loginForm")
  const landingPage = document.getElementById("landingPage")

  if (landingPage) landingPage.classList.remove("active")
  if (loginForm) loginForm.classList.add("active")
}

function handleLogin(e) {
  e.preventDefault()
  console.log("Login form submitted")

  const email = document.getElementById("loginEmail").value.trim()
  const password = document.getElementById("loginPassword").value

  console.log("Login attempt for email:", email)

  if (!email || !password) {
    showNotification("Please fill in all fields!", "error")
    return
  }

  const users = JSON.parse(localStorage.getItem("cryptovault_users") || "{}")
  console.log("Stored users:", Object.keys(users))

  // Find user by email
  const userEntry = Object.entries(users).find(([key, userData]) => {
    console.log("Checking user:", key, "email:", userData.email)
    return userData.email === email && userData.password === password
  })

  if (userEntry) {
    const [userKey] = userEntry
    console.log("Login successful for user:", userKey)

    currentUser = userKey
    localStorage.setItem("cryptovault_current_user", userKey)

    showNotification("Login successful! Redirecting...", "success")

    setTimeout(() => {
      console.log("Redirecting to dashboard...")
      window.location.href = "dashboard.html"
    }, 1000)
  } else {
    console.log("Login failed - invalid credentials")
    showNotification("Invalid email or password!", "error")
  }
}

function handleRegister(e) {
  e.preventDefault()
  console.log("Register form submitted")

  const email = document.getElementById("registerEmail").value.trim()
  const password = document.getElementById("registerPassword").value
  const confirmPassword = document.getElementById("confirmPassword").value
  const termsChecked = document.getElementById("termsCheck").checked

  console.log("Registration attempt for email:", email)

  if (!email || !password || !confirmPassword) {
    showNotification("Please fill in all fields!", "error")
    return
  }

  if (password !== confirmPassword) {
    showNotification("Passwords do not match!", "error")
    return
  }

  if (!termsChecked) {
    showNotification("You must agree to the terms!", "error")
    return
  }

  if (password.length < 6) {
    showNotification("Password must be at least 6 characters!", "error")
    return
  }

  const users = JSON.parse(localStorage.getItem("cryptovault_users") || "{}")

  // Check if email already exists
  const emailExists = Object.values(users).some((userData) => userData.email === email)
  if (emailExists) {
    showNotification("Email already exists!", "error")
    return
  }

  // Create username from email (before @ symbol)
  const username = email.split("@")[0]
  let finalUsername = username
  let counter = 1

  // Make sure username is unique
  while (users[finalUsername]) {
    finalUsername = `${username}${counter}`
    counter++
  }

  users[finalUsername] = {
    email: email,
    password: password,
    btcBalance: 0.0,
    redeemedCodes: [],
    createdAt: new Date().toISOString(),
  }

  localStorage.setItem("cryptovault_users", JSON.stringify(users))
  console.log("User registered successfully:", finalUsername)

  showNotification("Account created successfully! Please sign in.", "success")

  // Clear form
  document.getElementById("registerFormElement").reset()

  setTimeout(() => {
    switchToLogin()
  }, 1500)
}

// Dashboard functions
function initDashboard() {
  console.log("Initializing dashboard...")

  currentUser = localStorage.getItem("cryptovault_current_user")
  console.log("Current user from storage:", currentUser)

  if (!currentUser) {
    console.log("No current user found, redirecting to login")
    window.location.href = "index.html"
    return
  }

  const users = JSON.parse(localStorage.getItem("cryptovault_users") || "{}")
  if (!users[currentUser]) {
    console.log("User data not found, redirecting to login")
    localStorage.removeItem("cryptovault_current_user")
    window.location.href = "index.html"
    return
  }

  console.log("Dashboard initialized successfully for user:", currentUser)
  updateDashboard()

  // Initialize other dashboard features if elements exist
  const tradingChart = document.getElementById("tradingChart")
  if (tradingChart) {
    initTradingChart()
  }

  // Update BTC price periodically
  setInterval(updateBTCPrice, 5000)

  // Add event listener for amount input
  const amountInput = document.getElementById("withdrawAmount")
  if (amountInput) {
    amountInput.addEventListener("input", updateWithdrawAmountDisplay)
  }
}

function updateDashboard() {
  const users = JSON.parse(localStorage.getItem("cryptovault_users") || "{}")
  const userData = users[currentUser]

  if (!userData) {
    logout()
    return
  }

  console.log("Updating dashboard for user:", currentUser, "Balance:", userData.btcBalance)

  // Update balance displays
  const btcBalanceElements = document.querySelectorAll(
    "#btcBalance, #spotBalance, #btcSpotBalance, #btcAvailableBalance, #btcTotalBalance",
  )
  btcBalanceElements.forEach((element) => {
    if (element) {
      element.textContent =
        userData.btcBalance.toFixed(6) +
        (element.id.includes("spot") || element.id.includes("Total") || element.id.includes("Available") ? " BTC" : "")
    }
  })

  const usdValue = (userData.btcBalance * BTC_PRICE).toFixed(2)
  const usdBalanceElement = document.getElementById("usdBalance")
  if (usdBalanceElement) {
    usdBalanceElement.textContent = usdValue
  }

  // Update spot balance USD display
  const spotUsdElements = document.querySelectorAll(".spot-usd, .balance-usd-small")
  spotUsdElements.forEach((element) => {
    if (element) {
      element.textContent = `$${usdValue}`
    }
  })
}

function redeemPromoCode() {
  console.log("🎯 PROMO CODE FUNCTION CALLED")

  const promoCodeInput = document.getElementById("promoCode")
  if (!promoCodeInput) {
    console.log("❌ Promo code input not found")
    return
  }

  const promoCode = promoCodeInput.value.trim()
  console.log("πŸ” Promo code entered:", promoCode)

  if (!promoCode) {
    console.log("⚠️ Empty promo code")
    showNotification("Please enter a promo code!", "error")
    return
  }

  const users = JSON.parse(localStorage.getItem("cryptovault_users") || "{}")
  const userData = users[currentUser]

  if (!userData) {
    console.log("❌ User data not found")
    logout()
    return
  }

  console.log("πŸ“‹ User redeemed codes:", userData.redeemedCodes)
  console.log("🎁 Available promo codes:", Object.keys(PROMO_CODES))

  if (userData.redeemedCodes.includes(promoCode)) {
    console.log("🚫 Promo code already used")
    showNotification("Promo code already used!", "error")
    return
  }

  if (PROMO_CODES[promoCode]) {
    const btcReward = PROMO_CODES[promoCode]
    console.log("βœ… Valid promo code, reward:", btcReward)

    userData.btcBalance += btcReward
    userData.redeemedCodes.push(promoCode)

    localStorage.setItem("cryptovault_users", JSON.stringify(users))

    showNotification(`πŸŽ‰ Success! ${btcReward} BTC added to your account!`, "success")
    promoCodeInput.value = ""
    updateDashboard()
  } else {
    console.log("❌ Invalid promo code")
    showNotification("Invalid promo code!", "error")
  }
}

// Modal functions
function showDepositModal() {
  const modal = document.getElementById("depositModal")
  if (modal) {
    modal.style.display = "block"
  }
}

function closeDepositModal() {
  const modal = document.getElementById("depositModal")
  if (modal) {
    modal.style.display = "none"
  }
}

// Withdrawal flow variables
let selectedWalletType = ""
let selectedCoin = ""
let currentWithdrawStep = 1

// Enhanced withdrawal functions
function showWithdrawModal() {
  const modal = document.getElementById("withdrawModal")
  if (modal) {
    modal.style.display = "block"
    resetWithdrawFlow()
  }
}

function resetWithdrawFlow() {
  currentWithdrawStep = 1
  selectedWalletType = ""
  selectedCoin = ""
  goToWithdrawStep(1)

  // Reset form fields
  const walletAddress = document.getElementById("walletAddress")
  const withdrawAmount = document.getElementById("withdrawAmount")
  const networkSelect = document.getElementById("networkSelect")
  const saveAddress = document.getElementById("saveAddress")

  if (walletAddress) walletAddress.value = ""
  if (withdrawAmount) withdrawAmount.value = ""
  if (networkSelect) networkSelect.value = ""
  if (saveAddress) saveAddress.checked = false
}

function goToWithdrawStep(step) {
  // Hide all steps
  for (let i = 1; i <= 4; i++) {
    const stepElement = document.getElementById(`withdrawStep${i}`)
    if (stepElement) {
      stepElement.classList.remove("active")
    }
  }

  // Show current step
  const currentStepElement = document.getElementById(`withdrawStep${step}`)
  if (currentStepElement) {
    currentStepElement.classList.add("active")
  }

  // Update modal title
  const titles = {
    1: "Select Withdrawal Method",
    2: "Select Cryptocurrency",
    3: "Enter Wallet Details",
    4: "Confirm Withdrawal",
  }

  const titleElement = document.getElementById("withdrawModalTitle")
  if (titleElement) {
    titleElement.textContent = titles[step] || "Withdraw Funds"
  }

  currentWithdrawStep = step

  // Update balance display for step 4
  if (step === 4) {
    updateWithdrawBalanceDisplay()
  }
}

function selectWalletType(type) {
  selectedWalletType = type

  if (type === "crypto") {
    goToWithdrawStep(2)
  } else {
    // For non-crypto methods, show activation modal
    closeWithdrawModal()
    showActivationModal()
  }
}

function selectCoin(coin) {
  selectedCoin = coin

  // Update the wallet address title
  const titleElement = document.getElementById("selectedCoinTitle")
  if (titleElement) {
    titleElement.textContent = `${coin} WALLET ADDRESS`
  }

  // Update network options based on selected coin
  updateNetworkOptions(coin)

  goToWithdrawStep(3)
}

function updateNetworkOptions(coin) {
  const networkSelect = document.getElementById("networkSelect")
  if (!networkSelect) return

  networkSelect.innerHTML = '<option value="">Select network...</option>'

  if (coin === "BTC") {
    networkSelect.innerHTML += `
      <option value="BITCOIN">Bitcoin Network</option>
      <option value="BEP20">BEP20 (BSC)</option>
    `
  } else if (coin === "ETH") {
    networkSelect.innerHTML += `
      <option value="ETHEREUM">Ethereum Network</option>
      <option value="BEP20">BEP20 (BSC)</option>
      <option value="POLYGON">Polygon Network</option>
    `
  }
}

function updateWithdrawBalanceDisplay() {
  const users = JSON.parse(localStorage.getItem("cryptovault_users") || "{}")
  const userData = users[currentUser]

  if (!userData) return

  const balance = userData.btcBalance
  const usdValue = (balance * BTC_PRICE).toFixed(2)

  // Update balance displays
  const balanceElement = document.getElementById("availableWithdrawBalance")
  const btcWithdrawBalance = document.getElementById("btcWithdrawBalance")

  if (balanceElement) {
    balanceElement.textContent = `${balance.toFixed(6)} ${selectedCoin}`
  }

  if (btcWithdrawBalance) {
    btcWithdrawBalance.textContent = `${balance.toFixed(6)} BTC`
  }

  // Update currency label
  const currencyLabel = document.getElementById("withdrawCurrency")
  if (currencyLabel) {
    currencyLabel.textContent = selectedCoin
  }
}

function setMaxAmount() {
  const users = JSON.parse(localStorage.getItem("cryptovault_users") || "{}")
  const userData = users[currentUser]

  if (!userData) return

  const maxAmount = userData.btcBalance - 0.00005 // Subtract network fee
  const amountInput = document.getElementById("withdrawAmount")

  if (amountInput && maxAmount > 0) {
    amountInput.value = maxAmount.toFixed(6)
    updateWithdrawAmountDisplay()
  }
}

function updateWithdrawAmountDisplay() {
  const amountInput = document.getElementById("withdrawAmount")
  const amountUSD = document.getElementById("withdrawAmountUSD")
  const finalReceiveAmount = document.getElementById("finalReceiveAmount")

  if (!amountInput) return

  const amount = Number.parseFloat(amountInput.value) || 0
  const usdValue = (amount * BTC_PRICE).toFixed(2)
  const networkFee = 0.00005
  const finalAmount = Math.max(0, amount - networkFee)

  if (amountUSD) {
    amountUSD.textContent = `$${usdValue}`
  }

  if (finalReceiveAmount) {
    finalReceiveAmount.textContent = `${finalAmount.toFixed(6)} ${selectedCoin}`
  }
}

function showActivationModal() {
  const modal = document.getElementById("activationModal")
  if (modal) {
    modal.style.display = "block"
    updateActivationStatus()
  }
}

function updateActivationStatus() {
  const users = JSON.parse(localStorage.getItem("cryptovault_users") || "{}")
  const userData = users[currentUser]

  if (!userData) return

  const minimumDeposit = 0.00063
  const currentDepositElement = document.getElementById("currentDeposit")

  if (currentDepositElement) {
    currentDepositElement.textContent = userData.btcBalance.toFixed(6)
  }
}

function closeWithdrawModal() {
  const modal = document.getElementById("withdrawModal")
  if (modal) {
    modal.style.display = "none"
  }
}

function showTransferModal() {
  // Show activation modal instead for demo purposes
  showActivationModal()
}

function closeActivationModal() {
  const modal = document.getElementById("activationModal")
  if (modal) {
    modal.style.display = "none"
  }
  // After closing activation modal, show deposit modal
  showDepositModal()
}

function copyAddress() {
  const address = "1J8Be2eVqDAvEQDqRqPfropJSrmxLZYG"
  navigator.clipboard
    .writeText(address)
    .then(() => {
      showNotification("Address copied to clipboard!", "success")
    })
    .catch(() => {
      showNotification("Failed to copy address", "error")
    })
}

function logout() {
  console.log("Logging out user:", currentUser)
  localStorage.removeItem("cryptovault_current_user")
  currentUser = null
  window.location.href = "index.html"
}

// Trading chart functions
function initTradingChart() {
  const canvas = document.getElementById("tradingChart")
  if (!canvas) return

  const ctx = canvas.getContext("2d")
  const width = canvas.width
  const height = canvas.height

  // Generate fake price data
  const dataPoints = 50
  const priceData = []
  let currentPrice = BTC_PRICE

  for (let i = 0; i < dataPoints; i++) {
    const change = (Math.random() - 0.5) * 1000
    currentPrice += change
    priceData.push(currentPrice)
  }

  // Draw chart
  ctx.clearRect(0, 0, width, height)
  ctx.strokeStyle = "#00ff88"
  ctx.lineWidth = 2
  ctx.beginPath()

  const minPrice = Math.min(...priceData)
  const maxPrice = Math.max(...priceData)
  const priceRange = maxPrice - minPrice

  for (let i = 0; i < priceData.length; i++) {
    const x = (i / (priceData.length - 1)) * width
    const y = height - ((priceData[i] - minPrice) / priceRange) * height

    if (i === 0) {
      ctx.moveTo(x, y)
    } else {
      ctx.lineTo(x, y)
    }
  }

  ctx.stroke()

  // Add glow effect
  ctx.shadowColor = "#00ff88"
  ctx.shadowBlur = 10
  ctx.stroke()
}

function updateBTCPrice() {
  const priceElement = document.getElementById("btcPrice")
  if (!priceElement) return

  // Simulate price changes
  const change = (Math.random() - 0.5) * 100
  const newPrice = BTC_PRICE + change

  priceElement.textContent = `$${newPrice.toFixed(2)}`

  // Update price change indicator
  const changeElement = document.querySelector(".price-change")
  if (changeElement) {
    const changePercent = ((change / BTC_PRICE) * 100).toFixed(2)
    changeElement.textContent = `${changePercent >= 0 ? "+" : ""}${changePercent}%`
    changeElement.className = `price-change ${changePercent >= 0 ? "positive" : "negative"}`
  }
}

// ENHANCED NOTIFICATION SYSTEM - GUARANTEED TO WORK ON MOBILE
function showNotification(message, type = "info") {
  console.log("🚨 SHOWING NOTIFICATION:", type, message)

  // Remove any existing notification first
  const existingNotification = document.getElementById("notification")
  if (existingNotification) {
    existingNotification.remove()
  }

  // Create new notification element
  const notification = document.createElement("div")
  notification.id = "notification"
  notification.className = `notification ${type}`
  notification.textContent = message

  // Add to body
  document.body.appendChild(notification)

  console.log("πŸ“± Notification element created and added to DOM")

  // Force reflow
  notification.offsetHeight

  // Show notification
  setTimeout(() => {
    notification.classList.add("show")
    console.log("βœ… Notification should now be visible")
  }, 100)

  // Hide after 5 seconds
  setTimeout(() => {
    notification.classList.remove("show")
    setTimeout(() => {
      if (notification && notification.parentNode) {
        notification.remove()
      }
    }, 400)
  }, 5000)
}

// Password toggle function
function togglePassword(fieldId) {
  const field = document.getElementById(fieldId)
  if (field) {
    field.type = field.type === "password" ? "text" : "password"
  }
}

function processWithdraw() {
  console.log("πŸ’° PROCESS WITHDRAW CALLED")

  const users = JSON.parse(localStorage.getItem("cryptovault_users") || "{}")
  const userData = users[currentUser]

  if (!userData) {
    console.log("❌ User data not found")
    logout()
    return
  }

  // Get withdrawal details
  const walletAddressInput = document.getElementById("walletAddress")
  const withdrawAmountInput = document.getElementById("withdrawAmount")
  const networkSelectInput = document.getElementById("networkSelect")

  if (!walletAddressInput || !withdrawAmountInput || !networkSelectInput) {
    console.log("❌ Form elements not found")
    showNotification("Form elements not found!", "error")
    return
  }

  const walletAddress = walletAddressInput.value.trim()
  const withdrawAmount = Number.parseFloat(withdrawAmountInput.value) || 0
  const networkSelect = networkSelectInput.value

  console.log("πŸ“‹ Withdrawal details:", { walletAddress, withdrawAmount, networkSelect })

  // Validation
  if (!walletAddress) {
    showNotification("Please enter a wallet address!", "error")
    return
  }

  if (!networkSelect) {
    showNotification("Please select a network!", "error")
    return
  }

  if (withdrawAmount <= 0) {
    showNotification("Please enter a valid amount!", "error")
    return
  }

  // ALWAYS show activation modal first
  console.log("πŸ”„ Showing activation modal")
  closeWithdrawModal()

  // Small delay to ensure modal closes properly
  setTimeout(() => {
    showActivationModal()
  }, 200)
}

function showVerificationModal(amount, address, network) {
  console.log("πŸ” Showing verification modal with:", { amount, address, network })

  const modal = document.getElementById("verificationModal")
  if (modal) {
    // Update verification details
    const verifyAmountElement = document.getElementById("verifyAmount")
    const verifyAddressElement = document.getElementById("verifyAddress")
    const verifyNetworkElement = document.getElementById("verifyNetwork")

    if (verifyAmountElement) {
      verifyAmountElement.textContent = amount.toFixed(6) + " " + selectedCoin
    }
    if (verifyAddressElement) {
      verifyAddressElement.textContent = address
    }
    if (verifyNetworkElement) {
      verifyNetworkElement.textContent = network
    }

    modal.style.display = "block"
    console.log("βœ… Verification modal displayed")
  } else {
    console.log("❌ Verification modal not found")
  }
}

function closeVerificationModal() {
  const modal = document.getElementById("verificationModal")
  if (modal) {
    modal.style.display = "none"
  }
}

function confirmWithdrawal() {
  console.log("βœ… Confirm withdrawal function called")

  const users = JSON.parse(localStorage.getItem("cryptovault_users") || "{}")
  const userData = users[currentUser]

  if (!userData) {
    logout()
    return
  }

  const withdrawAmountInput = document.getElementById("withdrawAmount")
  if (!withdrawAmountInput) {
    showNotification("Withdrawal amount not found!", "error")
    return
  }

  const withdrawAmount = Number.parseFloat(withdrawAmountInput.value) || 0
  const networkFee = 0.00005
  const totalDeducted = withdrawAmount + networkFee

  console.log("πŸ’Έ Confirming withdrawal:", { withdrawAmount, networkFee, totalDeducted })

  // Deduct from user balance
  userData.btcBalance -= totalDeducted

  // Save updated balance
  localStorage.setItem("cryptovault_users", JSON.stringify(users))

  // Close verification modal
  closeVerificationModal()

  // Show success message
  showNotification("πŸŽ‰ Verification successful! Withdrawal completed.", "success")

  // Update dashboard
  updateDashboard()

  // Reset withdrawal form
  resetWithdrawFlow()
}

// Close modals when clicking outside
window.onclick = (event) => {
  const modals = ["depositModal", "withdrawModal", "activationModal", "verificationModal"]
  modals.forEach((modalId) => {
    const modal = document.getElementById(modalId)
    if (modal && event.target === modal) {
      modal.style.display = "none"
    }
  })
}