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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// @ts-nocheck

import {useEffect, useRef, useState} from "react"
import {ScrollView, TextStyle, TouchableOpacity, View, ViewStyle} from "react-native"

import {Text} from "@/components/ignite/Text"
import {useAppTheme} from "@/contexts/ThemeContext"
import {ThemedStyle} from "@/theme"

export const DebugHitSlop = ({children, hitSlop, style, ...props}) => {
  if (!__DEV__ || !hitSlop) return children

  const hitSlopStyle = {
    position: "absolute",
    top: -(hitSlop.top || hitSlop || 0),
    bottom: -(hitSlop.bottom || hitSlop || 0),
    left: -(hitSlop.left || hitSlop || 0),
    right: -(hitSlop.right || hitSlop || 0),
    borderWidth: 1,
    borderColor: "rgba(255, 0, 0, 0.5)",
    borderStyle: "dashed",
    backgroundColor: "rgba(255, 0, 0, 0.1)",
    pointerEvents: "none",
  }

  return (
    <View style={style}>

      {children}

      <View style={hitSlopStyle} />

    </View>
  )
}

/**

 * Deep compares two objects and returns detailed differences

 */
function deepCompare(obj1: any, obj2: any, path: string = ""): DiffResult[] {
  const differences: DiffResult[] = []

  // Handle null/undefined cases
  if (obj1 === null || obj1 === undefined || obj2 === null || obj2 === undefined) {
    if (obj1 !== obj2) {
      differences.push({
        path: path || "root",
        type: "changed",
        oldValue: obj1,
        newValue: obj2,
      })
    }
    return differences
  }

  // Handle primitive types
  if (typeof obj1 !== "object" || typeof obj2 !== "object") {
    if (obj1 !== obj2) {
      differences.push({
        path: path || "root",
        type: "changed",
        oldValue: obj1,
        newValue: obj2,
      })
    }
    return differences
  }

  // Handle arrays
  if (Array.isArray(obj1) || Array.isArray(obj2)) {
    if (!Array.isArray(obj1) || !Array.isArray(obj2)) {
      differences.push({
        path: path || "root",
        type: "type_changed",
        oldValue: obj1,
        newValue: obj2,
      })
      return differences
    }

    const maxLength = Math.max(obj1.length, obj2.length)
    for (let i = 0; i < maxLength; i++) {
      const currentPath = path ? `${path}[${i}]` : `[${i}]`

      if (i >= obj1.length) {
        differences.push({
          path: currentPath,
          type: "added",
          oldValue: undefined,
          newValue: obj2[i],
        })
      } else if (i >= obj2.length) {
        differences.push({
          path: currentPath,
          type: "removed",
          oldValue: obj1[i],
          newValue: undefined,
        })
      } else {
        differences.push(...deepCompare(obj1[i], obj2[i], currentPath))
      }
    }
    return differences
  }

  // Handle objects
  const allKeys = new Set([...Object.keys(obj1), ...Object.keys(obj2)])

  for (const key of allKeys) {
    const currentPath = path ? `${path}.${key}` : key

    if (!(key in obj1)) {
      differences.push({
        path: currentPath,
        type: "added",
        oldValue: undefined,
        newValue: obj2[key],
      })
    } else if (!(key in obj2)) {
      differences.push({
        path: currentPath,
        type: "removed",
        oldValue: obj1[key],
        newValue: undefined,
      })
    } else {
      differences.push(...deepCompare(obj1[key], obj2[key], currentPath))
    }
  }

  return differences
}

/**

 * Pretty prints the differences between two objects

 */
function prettyPrintDiff(obj1: any, obj2: any, options: PrintOptions = {}): void {
  const {colorize = true, compact = false} = options

  const differences = deepCompare(obj1, obj2)

  if (differences.length === 0) {
    console.log(colorize ? "\x1b[32mβœ“ Objects are identical\x1b[0m" : "βœ“ Objects are identical")
    return
  }

  console.log(colorize ? "\x1b[33m═══ Object Differences ═══\x1b[0m" : "═══ Object Differences ═══")
  console.log(`Found ${differences.length} difference(s)\n`)

  // Group differences by type
  const grouped = {
    added: differences.filter((d) => d.type === "added"),
    removed: differences.filter((d) => d.type === "removed"),
    changed: differences.filter((d) => d.type === "changed"),
    type_changed: differences.filter((d) => d.type === "type_changed"),
  }

  // Print additions
  if (grouped.added.length > 0) {
    console.log(colorize ? "\x1b[32m+ Added Properties:\x1b[0m" : "+ Added Properties:")
    grouped.added.forEach((diff) => {
      if (compact) {
        console.log(`  ${diff.path}: ${JSON.stringify(diff.newValue)}`)
      } else {
        console.log(`  Path: ${diff.path}`)
        console.log(`  Value: ${JSON.stringify(diff.newValue, null, 2).split("\n").join("\n  ")}`)
        console.log("")
      }
    })
  }

  // Print removals
  if (grouped.removed.length > 0) {
    console.log(colorize ? "\x1b[31m- Removed Properties:\x1b[0m" : "- Removed Properties:")
    grouped.removed.forEach((diff) => {
      if (compact) {
        console.log(`  ${diff.path}: ${JSON.stringify(diff.oldValue)}`)
      } else {
        console.log(`  Path: ${diff.path}`)
        console.log(`  Value: ${JSON.stringify(diff.oldValue, null, 2).split("\n").join("\n  ")}`)
        console.log("")
      }
    })
  }

  // Print changes
  if (grouped.changed.length > 0) {
    console.log(colorize ? "\x1b[36m~ Changed Properties:\x1b[0m" : "~ Changed Properties:")
    grouped.changed.forEach((diff) => {
      if (compact) {
        console.log(`  ${diff.path}: ${JSON.stringify(diff.oldValue)} β†’ ${JSON.stringify(diff.newValue)}`)
      } else {
        console.log(`  Path: ${diff.path}`)
        console.log(`  Old: ${JSON.stringify(diff.oldValue, null, 2).split("\n").join("\n  ")}`)
        console.log(`  New: ${JSON.stringify(diff.newValue, null, 2).split("\n").join("\n  ")}`)
        console.log("")
      }
    })
  }

  // Print type changes
  if (grouped.type_changed.length > 0) {
    console.log(colorize ? "\x1b[35m⚠ Type Changes:\x1b[0m" : "⚠ Type Changes:")
    grouped.type_changed.forEach((diff) => {
      const oldType = Array.isArray(diff.oldValue) ? "array" : typeof diff.oldValue
      const newType = Array.isArray(diff.newValue) ? "array" : typeof diff.newValue

      if (compact) {
        console.log(`  ${diff.path}: ${oldType} β†’ ${newType}`)
      } else {
        console.log(`  Path: ${diff.path}`)
        console.log(`  Changed from ${oldType} to ${newType}`)
        console.log(`  Old: ${JSON.stringify(diff.oldValue, null, 2).split("\n").join("\n  ")}`)
        console.log(`  New: ${JSON.stringify(diff.newValue, null, 2).split("\n").join("\n  ")}`)
        console.log("")
      }
    })
  }
}

/**

 * Returns differences as a formatted string

 */
function getDiffString(obj1: any, obj2: any, _options: PrintOptions = {}): string {
  const differences = deepCompare(obj1, obj2)

  if (differences.length === 0) {
    return "βœ“ Objects are identical"
  }

  let output = "═══ Object Differences ═══\n"
  output += `Found ${differences.length} difference(s)\n\n`

  const grouped = {
    added: differences.filter((d) => d.type === "added"),
    removed: differences.filter((d) => d.type === "removed"),
    changed: differences.filter((d) => d.type === "changed"),
    type_changed: differences.filter((d) => d.type === "type_changed"),
  }

  if (grouped.added.length > 0) {
    output += "+ Added Properties:\n"
    grouped.added.forEach((diff) => {
      output += `  ${diff.path}: ${JSON.stringify(diff.newValue)}\n`
    })
    output += "\n"
  }

  if (grouped.removed.length > 0) {
    output += "- Removed Properties:\n"
    grouped.removed.forEach((diff) => {
      output += `  ${diff.path}: ${JSON.stringify(diff.oldValue)}\n`
    })
    output += "\n"
  }

  if (grouped.changed.length > 0) {
    output += "~ Changed Properties:\n"
    grouped.changed.forEach((diff) => {
      output += `  ${diff.path}: ${JSON.stringify(diff.oldValue)} β†’ ${JSON.stringify(diff.newValue)}\n`
    })
    output += "\n"
  }

  if (grouped.type_changed.length > 0) {
    output += "⚠ Type Changes:\n"
    grouped.type_changed.forEach((diff) => {
      const oldType = Array.isArray(diff.oldValue) ? "array" : typeof diff.oldValue
      const newType = Array.isArray(diff.newValue) ? "array" : typeof diff.newValue
      output += `  ${diff.path}: ${oldType} β†’ ${newType}\n`
    })
  }

  return output
}

// Type definitions
interface DiffResult {
  path: string
  type: "added" | "removed" | "changed" | "type_changed"
  oldValue: any
  newValue: any
}

interface PrintOptions {
  showEqual?: boolean
  colorize?: boolean
  compact?: boolean
}

// Export functions
export {deepCompare, getDiffString, prettyPrintDiff}

// Example usage:
/*

const obj1 = {

  name: "John",

  age: 30,

  address: {

    city: "New York",

    zip: "10001"

  },

  hobbies: ["reading", "gaming"],

  active: true

};



const obj2 = {

  name: "John",

  age: 31,

  address: {

    city: "Boston",

    zip: "10001",

    country: "USA"

  },

  hobbies: ["reading", "gaming", "cooking"],

  email: "john@example.com"

};



// Pretty print to console with colors

prettyPrintDiff(obj1, obj2);



// Get compact output

prettyPrintDiff(obj1, obj2, { compact: true });



// Get as string

const diffString = getDiffString(obj1, obj2);

console.log(diffString);



// Get raw diff data

const differences = deepCompare(obj1, obj2);

console.log(differences);

*/

export const ConsoleLogger = () => {
  const [logs, setLogs] = useState([])
  const [isVisible, setIsVisible] = useState(true)
  const scrollViewRef = useRef(null)
  const {themed} = useAppTheme()

  useEffect(() => {
    const originalLog = console.log
    const originalWarn = console.warn
    const originalError = console.error

    const addLog = (type: string, args: any[]) => {
      const message = args
        .map((arg) => (typeof arg === "object" ? JSON.stringify(arg, null, 2) : String(arg)))
        .join(" ")

      setLogs((prev) => {
        const newLogs = [
          ...prev,
          {
            type,
            message,
            timestamp: new Date().toLocaleTimeString(),
          },
        ]
        return newLogs.slice(-500) // Keep only last 100
      })
    }

    console.log = (...args) => {
      addLog("log", args)
      originalLog(...args)
    }

    console.warn = (...args) => {
      addLog("warn", args)
      originalWarn(...args)
    }

    console.error = (...args) => {
      addLog("error", args)
      originalError(...args)
    }

    return () => {
      console.log = originalLog
      console.warn = originalWarn
      console.error = originalError
    }
  }, [])

  if (!isVisible) {
    return (
      <TouchableOpacity style={themed($toggleButton)} onPress={() => setIsVisible(true)}>

        <Text style={themed($toggleButtonText)}>Show Console</Text>

      </TouchableOpacity>
    )
  }

  return (
    <View style={themed($container)}>

      <View style={themed($header)}>

        <Text style={themed($headerText)}>Console ({logs.length}/100)</Text>

        <View style={themed($headerButtons)}>

          <TouchableOpacity style={themed($clearButton)} onPress={() => setLogs([])}>

            <Text style={themed($buttonText)}>Clear</Text>

          </TouchableOpacity>

          <TouchableOpacity style={themed($hideButton)} onPress={() => setIsVisible(false)}>

            <Text style={themed($buttonText)}>Hide</Text>

          </TouchableOpacity>

        </View>

      </View>

      <ScrollView

        ref={scrollViewRef}

        style={themed($logContainer)}

        onContentSizeChange={() => scrollViewRef.current?.scrollToEnd()}>

        {logs.map((log: any, index: number) => (

          <View key={index} style={themed($logEntry)}>

            <Text style={themed($timestamp)}>{log.timestamp}</Text>

            <Text

              style={[

                themed($logText),

                log.type === "error" && themed($errorText),

                log.type === "warn" && themed($warnText),

              ]}>

              [{log.type.toUpperCase()}] {log.message}

            </Text>

          </View>

        ))}

      </ScrollView>

    </View>
  )
}

const $container: ThemedStyle<ViewStyle> = ({colors}) => ({
  position: "absolute",
  top: 50,
  left: 0,
  right: 0,
  height: 250,
  backgroundColor: colors.background,
  borderTopWidth: 2,
  borderTopColor: colors.border,
  zIndex: 1000,
})

const $header: ThemedStyle<ViewStyle> = ({colors, spacing}) => ({
  flexDirection: "row",
  justifyContent: "space-between",
  alignItems: "center",
  padding: spacing.s3 || 8,
  backgroundColor: colors.background,
  borderBottomWidth: 1,
  borderBottomColor: colors.border || "#333",
})

const $headerText: ThemedStyle<TextStyle> = ({colors}) => ({
  color: colors.text,
  fontSize: 14,
})

const $headerButtons: ThemedStyle<ViewStyle> = ({spacing}) => ({
  flexDirection: "row",
  gap: spacing.s2 || 8,
})

const $clearButton: ThemedStyle<ViewStyle> = ({colors, spacing}) => ({
  backgroundColor: colors.tint,
  paddingHorizontal: spacing.s4 || 12,
  paddingVertical: spacing.s2 || 4,
  borderRadius: spacing.s2 || 4,
})

const $hideButton: ThemedStyle<ViewStyle> = ({colors, spacing}) => ({
  backgroundColor: colors.tint,
  paddingHorizontal: spacing.s4 || 12,
  paddingVertical: spacing.s2 || 4,
  borderRadius: spacing.s2 || 4,
})

const $buttonText: ThemedStyle<TextStyle> = ({colors}) => ({
  color: colors.text,
  fontSize: 12,
})

const $logContainer: ThemedStyle<ViewStyle> = ({spacing}) => ({
  flex: 1,
  padding: spacing.s3 || 8,
})

const $logEntry: ThemedStyle<ViewStyle> = () => ({
  marginBottom: 4,
})

const $timestamp: ThemedStyle<TextStyle> = ({colors}) => ({
  color: colors.textDim || "#888",
  fontSize: 10,
  fontFamily: "monospace",
})

const $logText: ThemedStyle<TextStyle> = () => ({
  color: "#0f0", // Most themes won't have neon green, so fall back to legacy color
  fontFamily: "monospace",
  fontSize: 11,
})

const $errorText: ThemedStyle<TextStyle> = () => ({
  color: "#f00",
})

const $warnText: ThemedStyle<TextStyle> = () => ({
  color: "#ff0",
})

const $toggleButton: ThemedStyle<ViewStyle> = ({colors, spacing}) => ({
  position: "absolute",
  bottom: 20,
  right: 20,
  backgroundColor: colors.tint,
  paddingHorizontal: spacing.s5 || 16,
  paddingVertical: spacing.s3 || 8,
  borderRadius: spacing.s3 || 8,
  borderWidth: 1,
  borderColor: colors.border || "#333",
  zIndex: 1000,
})

const $toggleButtonText: ThemedStyle<TextStyle> = ({colors}) => ({
  color: colors.text,
  fontSize: 12,
})