Py.Cafe

acabrera.citizens/

nyc_violations

DocsPricing
  • assets/
  • app.py
  • nyc_parkings_violation.csv
  • requirements.txt
app.py
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
import dash
from dash import dcc, html, Input, Output, callback, State
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import dash_bootstrap_components as dbc 

# Initialize the Dash app
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.LUMEN])

app.title = "NYC Traffic Fine Lottery"

# --- Load and Process Data Once at Startup ---
try:
    df_fines = pd.read_csv('nyc_parkings_violation.csv') # Adjust this to your file name and path!
    
    # Convert 'Issue Date' and 'Violation Time' to appropriate formats
    df_fines['Issue Date'] = pd.to_datetime(df_fines['Issue Date'])
    
    # Convert 'Violation Time' to hour for plotting (assumes HHMM or HH:MM format)
    # Convert to string and pad with zeros to ensure HHMM format if needed
    df_fines['Violation Time'] = df_fines['Violation Time'].astype(str).str.zfill(4) 
    df_fines['Violation Hour'] = df_fines['Violation Time'].apply(lambda x: int(x[:2]))

    # Create 'Day of Week' column and set categorical order for consistent plotting
    df_fines['Day of Week'] = df_fines['Issue Date'].dt.day_name()
    day_order = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    df_fines['Day of Week'] = pd.Categorical(df_fines['Day of Week'], categories=day_order, ordered=True)

except FileNotFoundError:
    print("Error: 'nyc_parkings_violation.csv' not found. Ensure the file is in the correct path.")
    # Create a minimal fallback DataFrame if the file isn't found
    print("Using minimal fallback data.")
    # Usando pandas para crear las fechas en lugar de datetime
    dates = pd.date_range(start='2023-01-01', periods=12, freq='D')
    df_fines = pd.DataFrame({
        'Fine Amount': [50, 250, 100, 50, 250, 100, 115, 650, 180, 50, 250, 100],
        'Violation': ['MOBILE BUS LANE VIOLATION', 'NO STAND TAXI/FHV RELIEF STAND', 'MISUSE PARKING PERMIT', 
                      'MOBILE BUS LANE VIOLATION', 'NO STAND TAXI/FHV RELIEF STAND', 'MISUSE PARKING PERMIT', 
                      'NO PARKING-EXC. DSBLTY PERMIT', 'WEIGH IN MOTION VIOLATION', 'FRAUDULENT USE PARKING PERMIT', 
                      'MOBILE BUS LANE VIOLATION', 'NO STAND TAXI/FHV RELIEF STAND', 'MISUSE PARKING PERMIT'],
        'Issue Date': dates,
        'Violation Time': ['0900', '1430', '1100', '1000', '1500', '1200', '1300', '0800', '1700', '0930', '1400', '1130'],
        'Penalty Amount': [10, 50, 20, 10, 50, 20, 25, 100, 35, 10, 50, 20],
        'Interest Amount': [5, 25, 10, 5, 25, 10, 12, 50, 18, 5, 25, 10],
        'Reduction Amount': [0, 25, 0, 0, 0, 10, 0, 50, 0, 0, 25, 0],
        'Payment Amount': [50, 225, 100, 50, 250, 90, 115, 600, 180, 50, 225, 100],
        'Amount Due': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    })
    df_fines['Violation Hour'] = df_fines['Violation Time'].apply(lambda x: int(x[:2]))
    df_fines['Day of Week'] = df_fines['Issue Date'].dt.day_name()
    day_order = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    df_fines['Day of Week'] = pd.Categorical(df_fines['Day of Week'], categories=day_order, ordered=True)


# Calculate frequencies for 'Fine Amount' directly from the dataset
if not df_fines.empty:
    FINE_DATA = df_fines['Fine Amount'].value_counts().sort_index().to_dict()
    TOTAL_TICKETS = df_fines.shape[0]
    FINE_PROBABILITIES = {amount: count / TOTAL_TICKETS for amount, count in FINE_DATA.items()}
    NYC_AVERAGE_FINE = df_fines['Fine Amount'].mean()
else:
    # Fallback data if DataFrame is empty
    FINE_DATA = {50: 8688, 250: 6057, 100: 2982, 115: 2612, 65: 2224, 150: 1553, 200: 1036, 180: 815, 650: 91}
    TOTAL_TICKETS = sum(FINE_DATA.values())
    FINE_PROBABILITIES = {amount: count/TOTAL_TICKETS for amount, count in FINE_DATA.items()}
    NYC_AVERAGE_FINE = 127 # Fallback average

# Calculate weights for violation types based on the dataset
if not df_fines.empty:
    VIOLATION_COUNTS = df_fines['Violation'].value_counts().to_dict()
    VIOLATIONS = {
        "MOBILE BUS LANE VIOLATION": VIOLATION_COUNTS.get("MOBILE BUS LANE VIOLATION", 0),
        "NO STAND TAXI/FHV RELIEF STAND": VIOLATION_COUNTS.get("NO STAND TAXI/FHV RELIEF STAND", 0),
        "MISUSE PARKING PERMIT": VIOLATION_COUNTS.get("MISUSE PARKING PERMIT", 0),
        "NO PARKING-EXC. DSBLTY PERMIT": VIOLATION_COUNTS.get("NO PARKING-EXC. DSBLTY PERMIT", 0),
        "FRAUDULENT USE PARKING PERMIT": VIOLATION_COUNTS.get("FRAUDULENT USE PARKING PERMIT", 0),
        "NO STANDING-FOR HIRE VEH STND": VIOLATION_COUNTS.get("NO STANDING-FOR HIRE VEH STND", 0),
        "PCKP DSCHRGE IN PRHBTD ZONE": VIOLATION_COUNTS.get("PCKP DSCHRGE IN PRHBTD ZONE", 0),
        "WEIGH IN MOTION VIOLATION": VIOLATION_COUNTS.get("WEIGH IN MOTION VIOLATION", 0)
    }
    for k, v in VIOLATIONS.items():
        if v == 0: VIOLATIONS[k] = 1 # Assign a small value if no occurrences to avoid errors
else:
    VIOLATIONS = { # Fallback values
        "MOBILE BUS LANE VIOLATION": 20316, "NO STAND TAXI/FHV RELIEF STAND": 1863, "MISUSE PARKING PERMIT": 1758,
        "NO PARKING-EXC. DSBLTY PERMIT": 815, "FRAUDULENT USE PARKING PERMIT": 463, "NO STANDING-FOR HIRE VEH STND": 459,
        "PCKP DSCHRGE IN PRHBTD ZONE": 293, "WEIGH IN MOTION VIOLATION": 91
    }

FUN_FACTS = [
    "🚌 Bus lane violations fund NYC's public transit improvements and safety programs.",
    "πŸ’° The most expensive fine ($650) equals 43 hours of minimum wage work in NYC.",
    "🎯 These fines represent about 2.3% of average NYC household monthly income.",
    "πŸ† Fine revenue helps fund traffic safety programs and infrastructure citywide.",
    "πŸ“Š NYC processes over 10 million parking violations annually across all types.",
    "πŸš— Average NYC driver pays $300-400 in fines per year - you're testing your luck!",
    "⏰ Most tickets issued between 12-6 PM when traffic enforcement is highest.",
    "πŸ—½ Revenue from these specific violations helps maintain city services.",
    f"πŸ“ˆ Analysis based on {TOTAL_TICKETS:,} real violations from NYC open data.",
    "🎫 Understanding fine patterns helps drivers make better parking decisions."
]

def get_random_violation():
    """Usar numpy en lugar de random para seleccionar violaciΓ³n"""
    violations_names = list(VIOLATIONS.keys())
    violations_weights = list(VIOLATIONS.values())
    
    if sum(violations_weights) == 0:
        if not df_fines.empty:
            # Usar numpy para selecciΓ³n aleatoria en lugar de random.choice
            return np.random.choice(df_fines['Violation'].unique())
        else:
            return np.random.choice(list(VIOLATIONS.keys()))
    
    # Convertir pesos a probabilidades normalizadas
    violations_weights = np.array(violations_weights)
    probabilities = violations_weights / violations_weights.sum()
    
    # Usar numpy.random.choice con probabilidades
    return np.random.choice(violations_names, p=probabilities)

def spin_lottery():
    """Usar numpy en lugar de random.choices para la loterΓ­a"""
    amounts = list(FINE_PROBABILITIES.keys())
    probabilities = list(FINE_PROBABILITIES.values())
    
    # Normalizar probabilidades para asegurar que suman 1
    probabilities = np.array(probabilities)
    probabilities = probabilities / probabilities.sum()
    
    # Usar numpy para selecciΓ³n con probabilidades
    return np.random.choice(amounts, p=probabilities)

def get_financial_analysis(fine_amount, df):
    """
    Analyze the financial behavior of a specific fine
    """
    if df.empty:
        # Fallback data if no dataset
        return {
            'escalation_path': f"${fine_amount} β†’ ${fine_amount + 50} β†’ ${fine_amount + 100}",
            'negotiation_success': "18% achieve discounts",
            'avg_reduction': "$35",
            'payment_behavior': "72% pay in full",
            'interest_risk': f"${fine_amount * 0.2:.0f} in interest if delayed",
            'risk_level': ("🟑 MEDIUM", "Standard fine - pay early to avoid surcharges"),
            'financial_score': "45/100"
        }
    
    # Filter data by specific fine amount
    fine_data = df[df['Fine Amount'] == fine_amount].copy()
    
    if fine_data.empty:
        fine_data = df.copy() # Use entire df to compute general stats
    
    analysis = {}
    
    avg_penalty = fine_data['Penalty Amount'].fillna(0).mean() if not fine_data.empty else 0
    avg_interest = fine_data['Interest Amount'].fillna(0).mean() if not fine_data.empty else 0
    
    step1 = fine_amount
    step2 = fine_amount + avg_penalty
    step3 = fine_amount + avg_penalty + avg_interest
    
    analysis['escalation_path'] = f"${step1:.0f} β†’ ${step2:.0f} β†’ ${step3:.0f}"
    
    reductions = fine_data['Reduction Amount'].fillna(0)
    negotiation_rate = (reductions > 0).mean() * 100 if not fine_data.empty else 0
    avg_reduction = reductions[reductions > 0].mean() if not reductions[reductions > 0].empty else 0
    
    analysis['negotiation_success'] = f"{negotiation_rate:.0f}% achieve discounts"
    analysis['avg_reduction'] = f"${avg_reduction:.0f}" if not pd.isna(avg_reduction) else "$0"
    
    payment_amounts = fine_data['Payment Amount'].fillna(0)
    full_payment_rate = (payment_amounts >= fine_amount * 0.95).mean() * 100 if not fine_data.empty else 0
    analysis['payment_behavior'] = f"{full_payment_rate:.0f}% pay in full"
    
    amount_due = fine_data['Amount Due'].fillna(0)
    still_owe_rate = (amount_due > 0).mean() * 100 if not fine_data.empty else 0
    
    max_interest = fine_data['Interest Amount'].fillna(0).max() if not fine_data.empty else 0
    analysis['interest_risk'] = f"Up to ${max_interest:.0f} in possible interest"
    
    financial_score = 0
    if fine_amount > 0:
        penalty_rate = avg_penalty / fine_amount 
        interest_rate = avg_interest / fine_amount 
        collection_difficulty = still_owe_rate / 100
        financial_score = (penalty_rate + interest_rate + collection_difficulty) * 100
    
    if financial_score < 20:
        risk_level = ("🟒 LOW", "This fine is relatively 'financially friendly'")
    elif financial_score < 50:
        risk_level = ("🟑 MEDIUM", "Standard fine - pay early to avoid surcharges")
    else:
        risk_level = ("πŸ”΄ HIGH", "Warning! This fine gets expensive quickly")
    
    analysis['risk_level'] = risk_level
    analysis['financial_score'] = f"{financial_score:.0f}/100"
    
    return analysis

def create_financial_breakdown_display(fine_amount, df):
    """
    Create the HTML display for financial analysis
    """
    financial_data = get_financial_analysis(fine_amount, df)
    risk_color_class = "success" if "🟒" in financial_data['risk_level'][0] else "warning" if "🟑" in financial_data['risk_level'][0] else "danger"
    
    return html.Div([
        html.H4("πŸ’° DEEP FINANCIAL ANALYSIS", className="section-title"),
        
        html.Div([
            html.Div([
                html.Span("πŸ“ˆ", style={'fontSize': '1.5rem', 'marginRight': '0.5rem'}),
                html.Strong("Escalation Path:", style={'color': '#e74c3c'}),
                html.Br(),
                html.Span(financial_data['escalation_path'], 
                         style={'fontSize': '1.1rem', 'fontWeight': 'bold', 'color': '#2c3e50'})
            ], style={'marginBottom': '1rem'})
        ]),
        
        html.Div([
            html.Div([
                html.Span("βš–οΈ ", style={'fontSize': '1.2rem'}),
                financial_data['negotiation_success']
            ], className="financial-stat"),
            html.Div([
                html.Span("πŸ’‘ ", style={'fontSize': '1.2rem'}),
                f"Average discount: {financial_data['avg_reduction']}"
            ], className="financial-stat"),
            html.Div([
                html.Span("πŸ“Š ", style={'fontSize': '1.2rem'}),
                financial_data['payment_behavior']
            ], className="financial-stat")
        ], className="financial-stats-grid"),
        
        html.Div([
            html.Div([
                html.Span("🎯 Risk Level: ", style={'fontWeight': 'bold'}),
                dbc.Badge(financial_data['risk_level'][0], 
                         color=risk_color_class,
                         className="ms-1")
            ], style={'marginBottom': '0.5rem'}),
            html.P(financial_data['risk_level'][1], 
                   style={'fontStyle': 'italic', 'color': '#7f8c8d', 'margin': '0'})
        ], className="risk-level-container")
        
    ], className="card section-card")

def create_wheel_figure():
    amounts = list(FINE_DATA.keys())
    values = list(FINE_DATA.values())
    
    colors = px.colors.sequential.Plasma
    if len(amounts) > len(colors):
        colors = px.colors.qualitative.Plotly + px.colors.sequential.Plasma + px.colors.qualitative.Alphabet

    n_colors = len(amounts)
    selected_colors = [colors[i % len(colors)] for i in range(n_colors)]
    
    fig = go.Figure(data=[go.Pie(
        labels=[f'${amt}' for amt in amounts], values=values, hole=0.4,
        marker=dict(colors=selected_colors, line=dict(color='white', width=3)),
        textinfo='label+percent', textposition='inside',
        hovertemplate='<b>$%{label}</b><br>Probability: %{percent}<br>Count: %{value}<extra></extra>',
        rotation=90
    )])
    fig.update_layout(
        title=dict(text="🎯 NYC TRAFFIC FINE WHEEL 🎯", x=0.5, font=dict(size=24, color='#2c3e50')),
        font=dict(size=14, color='white'), 
        paper_bgcolor='rgba(0,0,0,0)', 
        plot_bgcolor='rgba(0,0,0,0)',
        height=400, showlegend=False, margin=dict(t=80, b=20, l=20, r=20),
        annotations=[dict(text="SPIN!", x=0.5, y=0.5, font_size=20, showarrow=False, font_color='#2c3e50')]
    )
    return fig

# --- App Layout ---
app.layout = dbc.Container([
    # Header Section
    dbc.Row(dbc.Col(html.Div([
        html.H1("🎰 NYC TRAFFIC FINE LOTTERY 🎰", className="main-title"),
        html.P("Test Your Luck Against Real NYC Parking Violation Data", className="subtitle"),
        html.P("Based on actual NYC Open Data from thousands of real traffic violations", className="context-text"),
        html.Div([
            html.Span("πŸ“Š", style={'fontSize': '1.5rem'}),
            html.Span("REAL DATA 2023", className="badge")
        ], className="header-badge")
    ], className="header-section"), width=12)),
    
    dbc.Row([
        # Sidebar - Columna para Spin y New Fact
        dbc.Col([
            dbc.Card([
                dbc.CardHeader(html.H2("🎯 SPIN & FACTS", className="section-title text-center")),
                dbc.CardBody([
                    html.H3("Spin the Wheel!", className="card-subtitle mb-3 text-center"),
                    dcc.Graph(id='wheel-chart', figure=create_wheel_figure(), config={'displayModeBar': False}),
                    html.Div([
                        dbc.Button("🎲 SPIN THE WHEEL!", id="spin-button", className="spin-btn w-100 mb-3"),
                    ], className="d-grid gap-2"),
                    
                    html.Div(id="spin-result", className="result-display text-center mb-4", children=[
                        html.Span("🎯", className="result-emoji"),
                        html.Span("$???", className="result-amount waiting"),
                        html.P("Click the wheel to find out your fine!", className="result-message")
                    ]),
                    
                    html.Hr(),
                    
                    html.H4("NYC Traffic Fine Facts", className="card-subtitle mb-2 text-center"),
                    html.Div(id="fun-fact-content", className="fun-fact-content mb-3 text-center"),
                    dbc.Button("πŸ”„ New Fact", id="fact-button", className="fact-btn w-100"),
                ])
            ], className="h-100 sidebar-card"),
        ], width=4, className="sidebar-column mb-4"),

        # Contenido Principal
        dbc.Col([
            dbc.Row([
                # Columna Izquierda del Contenido Principal
                dbc.Col([
                    # "You Violation Details"
                    dbc.Card([
                        dbc.CardHeader(html.H4("🚨 YOUR VIOLATION DETAILS", className="section-title")),
                        dbc.CardBody([
                            html.Div(id="violation-details", className="violation-details mb-4"),
                        ])
                    ], className="mb-4"),

                    # "Fine Comparison"
                    dbc.Card([
                        dbc.CardHeader(html.H4("βš–οΈ FINE COMPARISON", className="section-title")),
                        dbc.CardBody([
                            dcc.Dropdown(
                                id='compare-dropdown',
                                options=[
                                    {'label': 'β˜• Starbucks Coffee ($5)', 'value': 5},
                                    {'label': 'πŸ• Pizza Slice ($3)', 'value': 3},
                                    {'label': '🎬 Movie Ticket ($15)', 'value': 15},
                                    {'label': 'πŸ” Fast Food Meal ($12)', 'value': 12},
                                    {'label': 'β›½ Gallon of Gas ($4)', 'value': 4},
                                    {'label': 'πŸ“± iPhone ($1000)', 'value': 1000}
                                ],
                                placeholder="Compare your fine to...",
                                className="dbc-dropdown"
                            ),
                            html.Div(id="comparison-result", className="comparison-result-container mt-3")
                        ])
                    ], className="mb-4"),
                    
                ], width=6),

                # Columna Derecha del Contenido Principal
                dbc.Col([
                    # "Quick Stats"
                    dbc.Card([
                        dbc.CardHeader(html.H4("πŸ“Š QUICK STATS", className="section-title")),
                        dbc.CardBody([
                            html.Div(id="quick-stats-content"),
                        ])
                    ], className="mb-4"),

                    # "Interactive Tools" 
                    dbc.Card([
                        dbc.CardHeader(html.H4("πŸ’° Annual Fine Calculator", className="section-title")),
                        dbc.CardBody([
                            html.Label("How many tickets per year?", className="slider-label"),
                            dcc.Slider(
                                id='tickets-slider',
                                min=1, max=52, step=1, value=4,
                                marks={i: str(i) for i in range(0, 53, 10)},
                                tooltip={"placement": "bottom", "always_visible": True},
                                className="mb-3"
                            ),
                            dbc.Button("Calculate Annual Cost", id="calc-button", className="game-btn w-100"),
                            html.Div(id="annual-result", className="game-result mt-3"),
                        ])
                    ], className="mb-4"),

                ], width=6) 
            ])
        ], width=8) 
    ], className="main-content-row"),
    
    html.Div(id="current-fine", style={'display': 'none'}),

    # Footer Section
    dbc.Row(dbc.Col(html.Footer([
        html.P("Web App developed using Plotly Dash 2025", className="footer-text")
    ], className="app-footer"), width=12))

], fluid=True, className="app-container")


# --- Callbacks ---

@app.callback(
    [Output('spin-result', 'children'),
     Output('violation-details', 'children'),
     Output('current-fine', 'children'),
     Output('quick-stats-content', 'children')],
    [Input('spin-button', 'n_clicks')]
)
def spin_wheel(n_clicks):
    if n_clicks is None:
        result = [
            html.Span("🎯", className="result-emoji"),
            html.Span("$???", className="result-amount waiting"),
            html.P("Click the wheel to find out your fine!", className="result-message")
        ]
        initial_violation_details = html.Div(html.P("Spin the wheel to see your violation details and financial analysis.", className="text-center text-muted mt-3"))
        return result, initial_violation_details, None, create_quick_stats()
    
    fine_amount = spin_lottery()
    violation_type = get_random_violation()
    
    if fine_amount <= 65:
        emoji = "πŸ˜…"
        amount_class = "result-amount cheap"
        message = "Lucky you! That's a relatively small fine."
    elif fine_amount <= 150:
        emoji = "😐"
        amount_class = "result-amount medium"
        message = "Ouch! That's a moderate fine."
    elif fine_amount <= 250:
        emoji = "😰"
        amount_class = "result-amount expensive"
        message = "Expensive! That's going to hurt the wallet."
    else:
        emoji = "πŸ’Έ"
        amount_class = "result-amount very-expensive"
        message = "OUCH! That's a major fine!"
    
    result = [
        html.Span(emoji, className="result-emoji"),
        html.Span(f"${fine_amount}", className=amount_class),
        html.P(message, className="result-message")
    ]
    
    # --- Start of new logic for Violation Details - Day/Hour Counts ---
    violation_df = df_fines[df_fines['Violation'] == violation_type]
    
    # Get top 3 days
    if not violation_df.empty:
        day_counts = violation_df['Day of Week'].value_counts(normalize=True).head(3) * 100
        day_details = [
            html.Li(f"{day}: {count:.1f}%", className="violation-stat-item") 
            for day, count in day_counts.items()
        ]
        day_details_html = html.Ul(day_details, className="violation-stats-list")
    else:
        day_details_html = html.P("No specific day pattern data available for this violation type.", className="text-muted small")

    # Get top 3 hours
    if not violation_df.empty:
        hour_counts = violation_df['Violation Hour'].value_counts(normalize=True).head(3) * 100
        hour_details = [
            html.Li(f"{hour:02d}:00 - {count:.1f}%", className="violation-stat-item") 
            for hour, count in hour_counts.items()
        ]
        hour_details_html = html.Ul(hour_details, className="violation-stats-list")
    else:
        hour_details_html = html.P("No specific hour pattern data available for this violation type.", className="text-muted small")

    # Get total count for this violation type
    total_violation_count = violation_df.shape[0] if not violation_df.empty else 0
    total_violation_percentage = (total_violation_count / TOTAL_TICKETS) * 100 if TOTAL_TICKETS > 0 else 0
    
    # --- End of new logic ---

    violation_details_content = html.Div([
        html.Div([
            html.Div([
                html.Span("πŸ“‹", className="violation-icon"),
                html.Span(violation_type, className="violation-text")
            ], className="violation-info"),
            html.Div([
                html.Span("πŸ’° Fine Amount: ", className="detail-label"),
                html.Span(f"${fine_amount}", className="detail-value")
            ], className="violation-detail"),
            html.Div([
                html.Span("πŸ“ Probability: ", className="detail-label"),
                html.Span(f"{FINE_PROBABILITIES.get(fine_amount, 0):.1%}", className="detail-value")
            ], className="violation-detail"),
            html.Div([
                html.Span("πŸ“Š Rank: ", className="detail-label"),
                html.Span(f"#{sorted(FINE_DATA.keys(), reverse=True).index(fine_amount) + 1 if fine_amount in FINE_DATA else 'N/A'} most expensive", className="detail-value")
            ], className="violation-detail"),
            # --- New violation details added here ---
            html.Hr(className="my-3"),
            html.H5("πŸ“Š Violation Patterns:", className="detail-subheader"),
            html.Div([
                html.Span("Total Occurrences of this Type: ", className="detail-label"),
                html.Span(f"{total_violation_count:,} ({total_violation_percentage:.1f}% of all tickets)", className="detail-value")
            ], className="violation-detail mb-2"),
            html.Div([
                html.H6("Top Days:", className="detail-subheader-small"),
                day_details_html
            ], className="violation-pattern-section"),
            html.Div([
                html.H6("Top Hours (24h):", className="detail-subheader-small"),
                hour_details_html
            ], className="violation-pattern-section")
            # --- End of new violation details ---
        ], className="violation-card-content"),
        
        create_financial_breakdown_display(fine_amount, df_fines)
    ])
    
    quick_stats = create_quick_stats(fine_amount)
    
    return result, violation_details_content, fine_amount, quick_stats

@app.callback(
    Output('annual-result', 'children'),
    [Input('calc-button', 'n_clicks')],
    [State('tickets-slider', 'value')]
)
def calculate_annual_cost(n_clicks, tickets_per_year):
    if n_clicks is None:
        return ""
    
    expected_fine = NYC_AVERAGE_FINE
    annual_cost = expected_fine * tickets_per_year
    
    best_case = min(FINE_DATA.keys()) * tickets_per_year
    worst_case = max(FINE_DATA.keys()) * tickets_per_year
    
    if annual_cost < 1000:
        risk_level = "🟒 LOW RISK"
        risk_message = "Manageable annual parking costs"
    elif annual_cost < 1500:
        risk_level = "🟑 MEDIUM RISK"
        risk_message = "Moderate impact on budget"
    else:
        risk_level = "πŸ”΄ HIGH RISK"
        risk_message = "Significant financial impact!"
    
    return html.Div([
        html.Div([
            html.Div([
                html.Span("πŸ’°", className="calc-icon"),
                html.Span(f"Expected Annual Cost: ${annual_cost:.0f}", className="calc-stat")
            ], className="calc-item"),
            html.Div([
                html.Span("πŸ“Š", className="calc-icon"),
                html.Span(f"Range: ${best_case:.0f} - ${worst_case:.0f}", className="calc-stat")
            ], className="calc-item"),
            html.Div([
                html.Span("🎯", className="calc-icon"),
                html.Span(f"Risk Level: {risk_level}", className="calc-stat")
            ], className="calc-item"),
            html.Div([
                html.Span("πŸ’‘", className="calc-icon"),
                html.Span(risk_message, className="calc-message")
            ], className="calc-item")
        ], className="calc-results")
    ])

@app.callback(
    Output('fun-fact-content', 'children'),
    [Input('fact-button', 'n_clicks')]
)
def update_fun_fact(n_clicks):
    if n_clicks is None:
        return html.P("Click 'New Fact' to learn something interesting about NYC traffic fines!", 
                     className="fun-fact-text")
    
    # Usar numpy en lugar de random para seleccionar el fact
    fact = np.random.choice(FUN_FACTS)
    return html.P(fact, className="fun-fact-text")

@app.callback(
    Output('comparison-result', 'children'),
    [Input('compare-dropdown', 'value')],
    [State('current-fine', 'children')]
)
def update_comparison(comparison_value, current_fine):
    if not comparison_value or not current_fine:
        return ""
    
    fine_amount = current_fine
    ratio = fine_amount / comparison_value
    
    comparison_items = {
        5: "β˜• Starbucks Coffee",
        3: "πŸ• Pizza Slice", 
        15: "🎬 Movie Ticket",
        12: "πŸ” Fast Food Meal",
        4: "β›½ Gallon of Gas",
        1000: "πŸ“± iPhone"
    }
    
    item_name = comparison_items.get(comparison_value, "Selected Item")
    
    if ratio < 1:
        message = f"Your ${fine_amount} fine is less than 1 {item_name.lower()}"
        emoji = "😌"
        color_class = "comparison-good"
    elif ratio < 2:
        message = f"Your ${fine_amount} fine = {ratio:.1f} {item_name.lower()}s"
        emoji = "😐"
        color_class = "comparison-medium"
    elif ratio < 10:
        message = f"Your ${fine_amount} fine = {ratio:.1f} {item_name.lower()}s"
        emoji = "😰"
        color_class = "comparison-bad"
    else:
        message = f"Your ${fine_amount} fine = {ratio:.0f} {item_name.lower()}s!"
        emoji = "πŸ’Έ"
        color_class = "comparison-terrible"
    
    return html.Div([
        html.Span(emoji, className="comparison-emoji"),
        html.P(message, className=f"comparison-text {color_class}")
    ], className="comparison-display")

def create_quick_stats(current_fine=None):
    """Create quick stats display"""
    cheapest = min(FINE_DATA.keys())
    most_expensive = max(FINE_DATA.keys())
    
    if current_fine:
        percentile = sum(1 for amount in FINE_DATA.keys() if amount <= current_fine) / len(FINE_DATA.keys()) * 100
        percentile_text = f"Your ${current_fine} fine is more expensive than {percentile:.0f}% of all fines"
        
        if percentile < 25:
            percentile_emoji = "πŸ€"
            percentile_class = "stat-good"
        elif percentile < 75:
            percentile_emoji = "βš–οΈ"
            percentile_class = "stat-medium"
        else:
            percentile_emoji = "πŸ’Έ"
            percentile_class = "stat-bad"
    else:
        percentile_text = "Spin to see where your fine ranks"
        percentile_emoji = "🎯"
        percentile_class = "stat-waiting"
    
    return html.Div([
        html.Div([
            html.Span("πŸ†", className="stat-icon"),
            html.Div([
                html.Span("Most Expensive Fine", className="stat-label"),
                html.Span(f"${most_expensive}", className="stat-value")
            ])
        ], className="stat-item"),
        
        html.Div([
            html.Span("πŸ€", className="stat-icon"),
            html.Div([
                html.Span("Cheapest Fine", className="stat-label"),
                html.Span(f"${cheapest}", className="stat-value")
            ])
        ], className="stat-item"),
        
        html.Div([
            html.Span("πŸ“Š", className="stat-icon"),
            html.Div([
                html.Span("Average Fine", className="stat-label"),
                html.Span(f"${NYC_AVERAGE_FINE:.0f}", className="stat-value")
            ])
        ], className="stat-item"),
        
        html.Div([
            html.Span("πŸ“ˆ", className="stat-icon"),
            html.Div([
                html.Span("Total Tickets Analyzed", className="stat-label"),
                html.Span(f"{TOTAL_TICKETS:,}", className="stat-value")
            ])
        ], className="stat-item"),
        
        html.Div([
            html.Span(percentile_emoji, className="stat-icon"),
            html.Div([
                html.Span(percentile_text, className=f"stat-label {percentile_class}")
            ])
        ], className="stat-item percentile-stat")
    ], className="quick-stats-grid")