Py.Cafe

DocsPricing
  • app.py
  • oecd_db2.py
  • oecd_wellbeing_clean.csv
  • requirements.txt
  • style.css
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
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
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
import plotly.express as px
import pandas as pd
import plotly.graph_objects as go
import dash
from dash import Dash, dcc, html, callback, Input, Output, State
import dash_bootstrap_components as dbc
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression


oecd_df = (pd.read_csv('oecd_wellbeing_clean.csv',
                       usecols=['Year','Country', 'Age', 'Sex', 'Education', 'Domain', 'Measure','OBS_VALUE']))
# Obtener listas únicas para los dropdowns
available_years = sorted(oecd_df['Year'].unique())
available_domains = sorted(oecd_df['Domain'].unique())
available_countries = sorted(oecd_df['Country'].unique())
available_demographics = ['Age', 'Sex', 'Education']

# Definir los colores personalizados con tonos más tenues y elegantes
COLORS = {
    "primary": "#507B9C",          # Azul medio tenue
    "primary-light": "#E2EBF3",    # Azul muy claro (fondo)
    "secondary": "#6D9775",        # Verde tenue
    "secondary-light": "#E5F0E7",  # Verde muy claro
    "accent": "#BA8057",           # Marrón/naranja suave
    "accent-light": "#F5EBE0",     # Beige claro
    "sidebar-bg": "#F7F9FC",       # Gris azulado muy claro
    "card-bg": "#FFFFFF",          # Blanco para tarjetas
    "text-primary": "#2C3E50",     # Azul oscuro para texto
    "text-secondary": "#5D6D7E"    # Gris azulado para texto secundario
}

# Diccionario con descripciones para tooltips mejorados con estilo storytelling
domain_descriptions = {
    "Civic Engagement": "The heartbeat of democracy and community involvement. This domain explores how citizens shape their societies through participation, trust in institutions, and engagement with governance systems.",
    "Health": "Beyond the absence of illness, this domain tells the story of our collective well-being: how long we live, how well we live, and the physical and mental resources we have to thrive.",
    "Safety": "The foundation of peaceful societies. This domain reveals how secure people feel in their daily lives, exploring crime rates, perception of safety, and the invisible social contracts that keep communities stable.",
    "Social Connections": "The invisible threads that bind us together. This domain maps our relationships, support networks, and the social fabric that catches us when we fall and celebrates with us when we rise.",
    "Subjective Well-being": "The story as told by people themselves. This domain captures how satisfied people are with their lives, their emotional states, and their personal assessment of what makes life worthwhile.",
    "Work and Job Quality": "More than just making a living. This domain explores the quality of our working lives, from fair compensation to workplace safety, job security, and the opportunity to use our talents.",
    "Work-Life Balance": "The delicate dance between professional and personal life. This domain examines how people navigate time constraints, manage family responsibilities, and find space for leisure and rest."
}

# Crear un tooltip genérico para medidas con estilo storytelling
measure_tooltip = "Every number tells a story. This indicator captures a specific chapter in the larger narrative of well-being, measuring concrete aspects that impact people's lives daily."


# Inicializar la app con el tema Bootstrap FLATLY
app = Dash(__name__, external_stylesheets=[dbc.themes.FLATLY, 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css', 'style.css'])
app.title = "OECD Well-being Dashboard - Stories Behind the Numbers"

# Definir estilo CSS personalizado
custom_css = {
    "body": {
        "backgroundColor": COLORS["primary-light"],
        "color": COLORS["text-primary"],
        "fontFamily": "'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"
    }
}

# Create ML clustering function
def cluster_countries(df, domain, measure, year, n_clusters=3):
    """
    Cluster countries based on selected measure values
    """
    # Filter data for the specific domain, measure and year
    filtered_df = df[(df['Domain'] == domain) & 
                    (df['Measure'] == measure) & 
                    (df['Year'] == year) &
                    (df['Age'] == 'Total') &
                    (df['Sex'] == 'Total') &
                    (df['Education'] == 'Total')]
    
    # If not enough data, return empty results
    if len(filtered_df) < n_clusters:
        return pd.DataFrame(), {}
    
    # Prepare data for clustering
    pivot_df = filtered_df.pivot_table(
        index='Country', values='OBS_VALUE', aggfunc='mean'
    ).reset_index()
    
    # For real clustering we'd use multiple features, but for simplicity we'll use just one
    X = pivot_df[['OBS_VALUE']].values
    
    # Standardize features
    scaler = StandardScaler()
    X_scaled = scaler.fit_transform(X)
    
    # Perform clustering
    kmeans = KMeans(n_clusters=n_clusters, random_state=42)
    pivot_df['Cluster'] = kmeans.fit_predict(X_scaled)
    
    # Get cluster centers
    centers = scaler.inverse_transform(kmeans.cluster_centers_)
    
    # Create cluster labels
    cluster_labels = {}
    centers_sorted = sorted([(i, centers[i][0]) for i in range(n_clusters)], key=lambda x: x[1])
    labels = ["Lower performers", "Mid-range performers", "Higher performers"]
    
    for i, (cluster_idx, _) in enumerate(centers_sorted):
        if i < len(labels):
            cluster_labels[cluster_idx] = labels[i]
    
    return pivot_df, cluster_labels

# Function to predict future values
def predict_future_values(df, domain, measure, country, demographic_type, demographic_value, years_to_predict=2):
    """
    Predict future values using simple linear regression
    """
    # Filter data
    filtered_df = df[(df['Domain'] == domain) & 
                    (df['Measure'] == measure) & 
                    (df['Country'] == country) &
                    (df[demographic_type] == demographic_value)]
    
    # If not enough data points, return empty results
    if len(filtered_df) < 3:  # Need at least 3 points for meaningful prediction
        return None, None
    
    # Prepare training data
    X = filtered_df['Year'].values.reshape(-1, 1)
    y = filtered_df['OBS_VALUE'].values
    
    # Fit model
    model = LinearRegression()
    model.fit(X, y)
    
    # Create future years
    last_year = max(filtered_df['Year'])
    future_years = np.array(range(last_year + 1, last_year + years_to_predict + 1))
    
    # Predict
    future_X = future_years.reshape(-1, 1)
    predictions = model.predict(future_X)
    
    return future_years, predictions

# Crear el componente de tooltip informativo con estilo storytelling
def create_tooltip(id, text):
    return html.Div([
        html.I(className="fas fa-info-circle me-2", id=f"tooltip-{id}"),
        dbc.Tooltip(text, target=f"tooltip-{id}", placement="right")
    ], className="d-inline-block ms-2")

# Crear los componentes de la sidebar con nuevo estilo
sidebar = dbc.Card([
    html.H4([html.I(className="fas fa-sliders-h me-2"), "Well-being Navigator:"], 
            className="card-header", 
            style={"backgroundColor": COLORS["primary"], "color": "white"}),
    dbc.CardBody([
        html.Div([
            html.Label([
                html.I(className="fas fa-th me-2"), "Well-being Domain",
                create_tooltip("domain", "Choose which chapter of the well-being story you want to explore.")
            ]),
            dcc.Dropdown(
                id='domain-dropdown',
                options=[{'label': d, 'value': d} for d in available_domains],
                value= "Work and job quality",
                placeholder="Select a Domain",
                className="mb-3"
            ),
        ]),
        
        html.Div([
            html.Label([
                html.I(className="fas fa-chart-bar me-2"), "Story Indicator",
                create_tooltip("measure", measure_tooltip)
            ]),
            dcc.Dropdown(
                id='measure-dropdown',
                options=[],
                value=["Employment rate"],
                placeholder="Select a Measure",
                className="mb-3"
            ),
        ]),
        
        html.Div([
            html.Label([
                html.I(className="fas fa-users me-2"), "Population Lens",
                create_tooltip("demographic", "Focus your story on different segments of society - by age, gender, or education level.")
            ]),
            dcc.Dropdown(
                id='demographic-dropdown',
                options=[{'label': demo, 'value': demo} for demo in available_demographics],
                value='Sex',
                placeholder="Select a demographic group.",
                className="mb-3"
            ),
        ]),
        
        html.Div([
            html.Label([
                html.I(className="fas fa-globe-americas me-2"), "Nations in Focus",
                create_tooltip("countries", "Choose which countries' stories you want to compare.")
            ]),
            dcc.Dropdown(
                id='country-dropdown',
                options=[{'label': country, 'value': country} for country in available_countries],
                value=['Austria', 'Belgium'],
                multi=True,
                placeholder="Select one or more countries",
                className="mb-3"
            ),
        ]),
        
        html.Div([
            html.Label([html.I(className="fas fa-film me-2"), "Narrative View"], className="fw-bold mt-3 mb-2"),
            dbc.RadioItems(
                id="time-view-selector",
                options=[
                    {"label": "Snapshot (One Year)", "value": "single"},
                    {"label": "Journey (Time Series)", "value": "series"}
                ],
                value="single",
                inline=True,
                className="mb-2"
            ),
        ]),
        
        html.Div(id="year-selector-container", children=[
            html.Label([
                html.I(className="fas fa-calendar-alt me-2"), "Year in Focus",
                create_tooltip("year", "Select a moment in time for your snapshot.")
            ]),
            dcc.Dropdown(
                id='year-dropdown',
                options=[{'label': str(year), 'value': year} for year in available_years],
                value=2020,
                placeholder="Select a Year",
                className="mb-3"
            ),
        ]),
        
        html.Div(id="year-range-container", style={"display": "none"}, children=[
            html.Label([
                html.I(className="fas fa-calendar-week me-2"), "Timeline",
                create_tooltip("year-range", "Choose the historical period for your narrative.")
            ]),
            dcc.RangeSlider(
                id='year-range-slider',
                min=min(available_years) if len(available_years) > 0 else 2000,
                max=max(available_years) if len(available_years) > 0 else 2020,
                value=[min(available_years) if len(available_years) > 0 else 2000, 
                       max(available_years) if len(available_years) > 0 else 2020],
                marks={int(year): str(int(year)) for year in available_years[::3]},
                className="mb-3"
            ),
        ]),
        
        dbc.Checklist(
            id='include-total-checkbox',
            options=[{'label': ' Include Population Totals', 'value': 'Total'}],
            value=['Total'],
            inline=True,
            className="mb-3"
        ),
        
        html.Hr(),
        
        # Advanced Analytics Section (New)
        html.H5([html.I(className="fas fa-brain me-2"), "Smart Insights"], className="mt-3 mb-2"),
        dbc.Button(
            [html.I(className="fas fa-object-group me-2"), "Cluster Analysis"],
            id="show-clusters-button",
            color="secondary",
            outline=True,
            className="mb-2 me-2",
            size="sm",
            style={"borderColor": COLORS["secondary"], "color": COLORS["secondary"]}
        ),
        dbc.Button(
            [html.I(className="fas fa-chart-line me-2"), "Future Trends"],
            id="show-predictions-button",
            color="accent",
            outline=True,
            className="mb-2",
            size="sm",
            style={"borderColor": COLORS["accent"], "color": COLORS["accent"]}
        ),
        
        html.Hr(),
        
        # Mini glosario desplegable
        dbc.Button(
            [html.I(className="fas fa-book-open me-2"), "Story Guide"],
            id="collapse-button",
            className="mb-3",
            color="primary",
            outline=True,
            style={"borderColor": COLORS["primary"], "color": COLORS["primary"]}
        ),
        dbc.Collapse(
            dbc.Card(dbc.CardBody([
                html.H5("The Language of Well-being"),
                html.P([html.Strong("OECD: "), "Organisation for Economic Cooperation and Development – the storytellers behind this data"]),
                html.P([html.Strong("Domain: "), "A chapter in the well-being story – health, work, connections with others"]),
                html.P([html.Strong("Indicator: "), "The specific characters and plot points that make each chapter unique"]),
                html.P([html.Strong("OBS_VALUE: "), "The numbers that quantify human experience and well-being"])
            ])),
            id="collapse",
            is_open=False,
        ),
    ]),
], className="shadow-sm h-100", style={"backgroundColor": COLORS["sidebar-bg"], "borderColor": COLORS["primary-light"]})

# Diseño principal de la aplicación
app.layout = dbc.Container([
    # Estilos globales
    html.Div([
        html.Link(
            rel='stylesheet',
            href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css'
        ),
    ]),
    
    dbc.Navbar([
            dbc.Container([
                html.A(
                    dbc.Row([
                        dbc.Col(html.I(className="fas fa-map-marked-alt", style={"color": COLORS["secondary-light"]})),
                        dbc.Col(dbc.NavbarBrand("OECD Well-being Dashboard", className="ms-2",style={"fontSize": "2.0rem"})),
                    ], align="center", className="g-0"),
                    href="#",
                    style={"textDecoration": "none"},
                ),
            ], fluid=True)
        ], color=COLORS["primary"], dark=True, className="mb-4 shadow-sm"),
    
    dbc.Row([
        # Sidebar
        dbc.Col(sidebar, width=3, className="mb-4"),
        
        # Área principal de contenido
        dbc.Col([
            dbc.Card([
                dbc.CardHeader(html.H4(id="chart-title", children="Well-being Explorer"), 
                            style={"backgroundColor": COLORS["primary-light"], "color": COLORS["text-primary"]}),
                dbc.CardBody([
                    # Insight summary - new storytelling element
                    html.Div(id="insight-summary", className="story-callout mb-3"),
                    
                    dbc.Tabs([
                        dbc.Tab(
                            dcc.Graph(id='comparison-graph', className="h-100"),
                            label=" Comparison Snapshot",
                            tab_id="bar-tab",
                            label_style={"color": COLORS["text-secondary"]},
                            active_label_style={"color": COLORS["primary"], "fontWeight": "bold"}
                        ),
                        dbc.Tab(
                            dcc.Graph(id='time-series-graph', className="h-100"),
                            label="Historical Journey",
                            tab_id="time-tab",
                            label_style={"color": COLORS["text-secondary"]},
                            active_label_style={"color": COLORS["primary"], "fontWeight": "bold"}
                        ),
                        # New tabs for ML insights
                        dbc.Tab(
                            dcc.Graph(id='clusters-graph', className="h-100"),
                            label="Country Clusters",
                            tab_id="clusters-tab",
                            label_style={"color": COLORS["text-secondary"]},
                            active_label_style={"color": COLORS["secondary"], "fontWeight": "bold"}
                        ),
                        dbc.Tab(
                            dcc.Graph(id='predictions-graph', className="h-100"),
                            label="Future Trends",
                            tab_id="predictions-tab",
                            label_style={"color": COLORS["text-secondary"]},
                            active_label_style={"color": COLORS["accent"], "fontWeight": "bold"}
                        ),
                    ], id="chart-tabs", active_tab="bar-tab", className="custom-tabs"),
                ], className="d-flex flex-column", style={"minHeight": "600px"}),
                dbc.CardFooter(html.P(id="chart-note", children=[
                    html.I(className="fas fa-compass me-2"), 
                    "Journey Source: OECD Better Life Index"
                ], className="text-muted", style={"color": COLORS["text-secondary"]}))
            ], className="shadow-sm h-100", style={"borderColor": COLORS["primary-light"]}),
        ], width=9),
    ]),
    
    dbc.Row([
        dbc.Col([
            dbc.Card([
                dbc.CardHeader(html.H5([
                    html.I(className="fas fa-lightbulb me-2"), 
                    "The Story Behind the Numbers"
                ]), style={"backgroundColor": COLORS["secondary-light"], "color": COLORS["text-primary"]}),
                dbc.CardBody(html.Div(id="interpretation-text"), style={"color": COLORS["text-secondary"]})
            ], className="shadow-sm mt-4", style={"borderColor": COLORS["secondary-light"]})
        ], width=12)
    ]),
    
    # Modals for cluster and prediction explanations
    dbc.Modal([
        dbc.ModalHeader(html.H4("Country Clusters Explained")),
        dbc.ModalBody([
            html.P([
                "Our smart analysis has identified patterns in the data and grouped countries into clusters based on their performance in this indicator. ",
                "This reveals which nations share similar characteristics and challenges."
            ]),
            html.Hr(),
            html.H5("How to interpret the clusters:"),
            html.Ul([
                html.Li(html.Strong("Higher performers: "), "Countries with the strongest results in this indicator"),
                html.Li(html.Strong("Mid-range performers: "), "Countries with average results"),
                html.Li(html.Strong("Lower performers: "), "Countries with results below the average")
            ]),
            html.P([
                "These clusters are purely based on data patterns and should be interpreted alongside contextual factors ",
                "like policy environments, historical context, and other socioeconomic conditions."
            ], className="text-muted mt-3")
        ]),
        dbc.ModalFooter(
            dbc.Button("Close", id="close-clusters-modal", className="ms-auto", color="primary")
        ),
    ], id="clusters-explanation-modal", is_open=False, size="lg"),
    
    dbc.Modal([
        dbc.ModalHeader(html.H4("Future Trends Explained")),
        dbc.ModalBody([
            html.P([
                "Our predictive analysis projects how indicators might evolve in the coming years based on historical patterns. ",
                "These projections use linear regression to extend existing trends."
            ]),
            html.Hr(),
            html.H5("How to interpret the predictions:"),
            html.Ul([
                html.Li("Solid lines show actual historical data"),
                html.Li("Dashed lines show projected future values"),
                html.Li("Shaded areas represent the margin of uncertainty")
            ]),
            html.P([
                "Remember that predictions are estimates based on past patterns and cannot account for unexpected events, ",
                "policy changes, or other disruptions that might affect these trajectories."
            ], className="text-muted mt-3")
        ]),
        dbc.ModalFooter(
            dbc.Button("Close", id="close-predictions-modal", className="ms-auto", color="primary")
        ),
    ], id="predictions-explanation-modal", is_open=False, size="lg"),
    
    # Footer with storytelling style
    html.Footer(
        dbc.Container([
            html.P([
                "Every number tells a human story. Dashboard crafted with ",
                html.I(className="fas fa-heart text-danger"),
                " using OECD data. © 2025"
            ], className="text-center", style={"color": COLORS["text-secondary"], "fontSize": "0.9rem"})
        ]),
        className="mt-5 py-3 shadow-sm",
        style={"backgroundColor": COLORS["primary-light"], "borderTop": f"1px solid {COLORS['primary-light']}"})
    
], fluid=True, className="mb-5")

# Callback para mostrar/ocultar el glosario
@callback(
    Output("collapse", "is_open"),
    [Input("collapse-button", "n_clicks")],
    [State("collapse", "is_open")],
)
def toggle_collapse(n, is_open):
    if n:
        return not is_open
    return is_open

# Callbacks for showing/hiding explanation modals
@callback(
    Output("clusters-explanation-modal", "is_open"),
    [Input("show-clusters-button", "n_clicks"), Input("close-clusters-modal", "n_clicks")],
    [State("clusters-explanation-modal", "is_open")],
)
def toggle_clusters_modal(n1, n2, is_open):
    if n1 or n2:
        return not is_open
    return is_open

@callback(
    Output("predictions-explanation-modal", "is_open"),
    [Input("show-predictions-button", "n_clicks"), Input("close-predictions-modal", "n_clicks")],
    [State("predictions-explanation-modal", "is_open")],
)
def toggle_predictions_modal(n1, n2, is_open):
    if n1 or n2:
        return not is_open
    return is_open

# Callback para establecer la pestaña activa cuando se presionan los botones de análisis
@callback(
    Output("chart-tabs", "active_tab"),
    [Input("show-clusters-button", "n_clicks"), 
     Input("show-predictions-button", "n_clicks"),
     Input("time-view-selector", "value")],
    [State("chart-tabs", "active_tab")]
)
def set_active_tab(clusters_clicks, predictions_clicks, view_type, current_tab):
    ctx = dash.callback_context
    if not ctx.triggered:
        if view_type == "single":
            return "bar-tab"
        else:
            return "time-tab"
    else:
        button_id = ctx.triggered[0]["prop_id"].split(".")[0]
        if button_id == "show-clusters-button":
            return "clusters-tab"
        elif button_id == "show-predictions-button":
            return "predictions-tab"
        elif button_id == "time-view-selector":
            if view_type == "single":
                return "bar-tab"
            else:
                return "time-tab"
    return current_tab

# Callback para actualizar las opciones de medida basadas en el dominio seleccionado
@callback(
    Output('measure-dropdown', 'options'),
    Output('measure-dropdown', 'value'),
    [Input('domain-dropdown', 'value')]
)
def update_measure_options(selected_domain):
    if selected_domain:
        domain_measures = sorted(oecd_df[oecd_df['Domain'] == selected_domain]['Measure'].unique())
        options = [{'label': m, 'value': m} for m in domain_measures]
        value = domain_measures[0] if len(domain_measures) > 0 else None
        return options, value
    return [], None

# Callback for toggling between year selector and year range based on time view
@callback(
    Output("year-selector-container", "style"),
    Output("year-range-container", "style"),
    [Input("time-view-selector", "value")]
)
def toggle_year_selectors(view_type):
    if view_type == "single":
        return {"display": "block"}, {"display": "none"}
    else:
        return {"display": "none"}, {"display": "block"}

# Callback para actualizar el título del gráfico
@callback(
    Output('chart-title', 'children'),
    [Input('domain-dropdown', 'value'),
     Input('measure-dropdown', 'value')]
)

def update_chart_title(domain, measure):
    if domain and measure:
        return f"🌟 {measure} in {domain}"
    return "Well-being Data Explorer"

# Callback to update the insight summary with storytelling
@callback(
    Output('insight-summary', 'children'),
    [Input('domain-dropdown', 'value'),
     Input('measure-dropdown', 'value'),
     Input('year-dropdown', 'value'),
     Input('country-dropdown', 'value'),
     Input('demographic-dropdown', 'value')]
)
def update_insight_summary(domain, measure, year, countries, demographic):
    if not domain or not measure or not year or not countries or not demographic:
        return "Select parameters to explore well-being data."

    country_phrase = ""
    if len(countries) == 1:
        country_phrase = f"{countries[0]}"
    elif len(countries) == 2:
        country_phrase = f"{countries[0]} and {countries[1]}"
    else:
        country_phrase = f"{len(countries)} selected countries"

    summary_text = f"Data for {measure} in {domain} for {country_phrase} in {year}, analyzed by {demographic}."
    return html.P(summary_text)

# Callback para generar el gráfico de comparación
@callback(
    Output('comparison-graph', 'figure'),
    [Input('domain-dropdown', 'value'),
     Input('measure-dropdown', 'value'),
     Input('year-dropdown', 'value'),
     Input('country-dropdown', 'value'),
     Input('demographic-dropdown', 'value'),
     Input('include-total-checkbox', 'value')]
)
def update_comparison_graph(domain, measure, year, countries, demographic, include_total):
    if not domain or not measure or not year or not countries or not demographic:
        return go.Figure()
    
    # Filter data
    filtered_df = oecd_df[(oecd_df['Year'] == year) & 
                         (oecd_df['Domain'] == domain) & 
                         (oecd_df['Measure'] == measure) &
                         (oecd_df['Country'].isin(countries))]
    
    # Filter by demographic and handle 'Total' differently
    if 'Total' in include_total:
        demographic_values = filtered_df[demographic].unique()
    else:
        demographic_values = [val for val in filtered_df[demographic].unique() if val != 'Total']
    
    filtered_df = filtered_df[filtered_df[demographic].isin(demographic_values)]
    
    # Create bar chart with improved styling
    fig = px.bar(
        filtered_df, 
        x='Country', 
        y='OBS_VALUE',
        color=demographic,
        barmode='group',
        title=f"{measure} by {demographic} ({year})",
        labels={'OBS_VALUE': 'Value', 'Country': 'Country'},
        color_discrete_sequence=[COLORS["primary"], COLORS["secondary"], COLORS["accent"], 
                               "#D68C45", "#8E6C8A", "#4F94B8", "#97AC3D"]
    )
    
    # Improve styling
    fig.update_layout(
        plot_bgcolor=COLORS["card-bg"],
        paper_bgcolor=COLORS["card-bg"],
        font_family="'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
        font_color=COLORS["text-primary"],
        legend_title_text="",
        margin=dict(l=40, r=40, t=60, b=40),
        hoverlabel=dict(
            bgcolor=COLORS["primary-light"],
            font_size=12,
            font_family="'Segoe UI', Roboto"
        ),
        title={
            'text': f"<b>{measure}</b> by {demographic} ({year})",
            'y':0.95,
            'x':0.5,
            'xanchor': 'center',
            'yanchor': 'top',
            'font': dict(size=18)
        }
    )
    
    fig.update_traces(
        hovertemplate='<b>%{x}</b><br>%{y:.2f}<extra></extra>'
    )
    
    # Add annotation with storytelling insights
    if len(filtered_df) > 0:
        max_country = filtered_df.loc[filtered_df['OBS_VALUE'].idxmax()]['Country']
        max_value = filtered_df['OBS_VALUE'].max()
        
        fig.add_annotation(
            x=0.5,
            y=-0.15,
            xref="paper",
            yref="paper",
            text=f"<i>Story Insight:</i> {max_country} shows the highest value at {max_value:.2f}",
            showarrow=False,
            font=dict(
                family="'Segoe UI', italic",
                size=12,
                color=COLORS["accent"]
            ),
            align="center",
            bgcolor=COLORS["accent-light"],
            bordercolor=COLORS["accent"],
            borderwidth=1,
            borderpad=4
        )
    
    return fig

# Callback para generar el gráfico de series temporales
@callback(
    Output('time-series-graph', 'figure'),
    [Input('domain-dropdown', 'value'),
     Input('measure-dropdown', 'value'),
     Input('year-range-slider', 'value'),
     Input('country-dropdown', 'value'),
     Input('demographic-dropdown', 'value'),
     Input('include-total-checkbox', 'value')]
)
def update_time_series_graph(domain, measure, year_range, countries, demographic, include_total):
    if not domain or not measure or not year_range or not countries or not demographic:
        return go.Figure()
    
    # Filter data
    filtered_df = oecd_df[(oecd_df['Year'] >= year_range[0]) &
                         (oecd_df['Year'] <= year_range[1]) &
                         (oecd_df['Domain'] == domain) &
                         (oecd_df['Measure'] == measure) &
                         (oecd_df['Country'].isin(countries))]
    
    # Filter by demographic and handle 'Total' differently
    if 'Total' in include_total:
        demographic_values = ['Total']
    else:
        demographic_values = [val for val in filtered_df[demographic].unique() if val != 'Total']
    
    filtered_df = filtered_df[filtered_df[demographic].isin(demographic_values)]
    
    # Create line chart with improved styling
    fig = px.line(
        filtered_df, 
        x='Year', 
        y='OBS_VALUE',
        color='Country',
        line_dash=demographic,
        markers=True,
        title=f"{measure} Over Time ({year_range[0]}-{year_range[1]})",
        labels={'OBS_VALUE': measure, 'Year': 'Year'},
        color_discrete_sequence=[COLORS["primary"], COLORS["secondary"], COLORS["accent"], 
                               "#D68C45", "#8E6C8A", "#4F94B8", "#97AC3D"]
    )
    
    # Improve styling
    fig.update_layout(
        plot_bgcolor=COLORS["card-bg"],
        paper_bgcolor=COLORS["card-bg"],
        font_family="'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
        font_color=COLORS["text-primary"],
        legend_title_text="",
        margin=dict(l=40, r=40, t=60, b=80),
        hoverlabel=dict(
            bgcolor=COLORS["primary-light"],
            font_size=12,
            font_family="'Segoe UI', Roboto"
        ),
        title={
            'text': f"<b>{measure}</b> Historical Journey ({year_range[0]}-{year_range[1]})",
            'y':0.95,
            'x':0.5,
            'xanchor': 'center',
            'yanchor': 'top',
            'font': dict(size=18)
        }
    )
    
    fig.update_traces(
        hovertemplate='<b>%{x}</b><br>%{y:.2f}<extra></extra>'
    )
    
    # Add dynamic annotation with trend insights
    if len(filtered_df) > 0:
        # Try to find a meaningful trend insight
        trend_text = ""
        
        # Check if we have enough years to analyze trends
        if len(filtered_df['Year'].unique()) > 2:
            # Find country with biggest improvement
            pivot_df = filtered_df[filtered_df[demographic] == 'Total'].pivot_table(
                index='Country', values='OBS_VALUE', aggfunc=lambda x: x.iloc[-1] - x.iloc[0]
            ).reset_index()
            
            if len(pivot_df) > 0:
                max_improve_country = pivot_df.iloc[pivot_df['OBS_VALUE'].argmax()]['Country']
                max_improve_value = pivot_df['OBS_VALUE'].max()
                
                if max_improve_value > 0:
                    trend_text = f"{max_improve_country} showed the strongest improvement over this period"
                else:
                    trend_text = "All countries show declining trends in this period"
        
        if trend_text:
            fig.add_annotation(
                x=0.5,
                y=-0.15,
                xref="paper",
                yref="paper",
                text=f"<i>Trend Insight:</i> {trend_text}",
                showarrow=False,
                font=dict(
                    family="'Segoe UI', italic",
                    size=12,
                    color=COLORS["accent"]
                ),
                align="center",
                bgcolor=COLORS["accent-light"],
                bordercolor=COLORS["accent"],
                borderwidth=1,
                borderpad=4
            )
    
    return fig

# Callback para generar el gráfico de clusters
@callback(
    Output('clusters-graph', 'figure'),
    [Input('domain-dropdown', 'value'),
     Input('measure-dropdown', 'value'),
     Input('year-dropdown', 'value')]
)
def update_clusters_graph(domain, measure, year):
    if not domain or not measure or not year:
        return go.Figure()
    
    # Get clusters
    cluster_df, cluster_labels = cluster_countries(oecd_df, domain, measure, year)
    
    if len(cluster_df) == 0:
        # Create an empty figure with a message
        fig = go.Figure()
        fig.update_layout(
            title="Not enough data for clustering",
            annotations=[
                dict(
                    text="Insufficient data to create clusters for these parameters",
                    showarrow=False,
                    xref="paper",
                    yref="paper",
                    x=0.5,
                    y=0.5
                )
            ]
        )
        return fig
    
    # Create a color map
    colors = [COLORS["primary"], COLORS["secondary"], COLORS["accent"]]
    cluster_colors = {i: colors[i] for i in range(len(cluster_labels))}
    
    # Create the scatter plot
    fig = px.scatter(
        cluster_df,
        x='Country',
        y='OBS_VALUE',
        color='Cluster',
        color_discrete_map={i: cluster_colors[i] for i in range(len(cluster_labels))},
        title=f"Country Clusters for {measure} ({year})",
        labels={'OBS_VALUE': measure, 'Cluster': 'Group', 'Country':''},
        category_orders={"Cluster": sorted(cluster_df['Cluster'].unique())},
        size=[12] * len(cluster_df)
    )
    
    # Add horizontal lines for cluster centers
    for cluster, label in cluster_labels.items():
        cluster_mean = cluster_df[cluster_df['Cluster'] == cluster]['OBS_VALUE'].mean()
        fig.add_shape(
            type="line",
            x0=-0.5,
            y0=cluster_mean,
            x1=len(cluster_df['Country'].unique()) - 0.5,
            y1=cluster_mean,
            line=dict(
                color=cluster_colors[cluster],
                width=2,
                dash="dash",
            )
        )
        
        # Add annotation for cluster label
        fig.add_annotation(
            x=len(cluster_df['Country'].unique()) - 0.5,
            y=cluster_mean,
            text=label,
            showarrow=False,
            xshift=50,
            font=dict(
                color=cluster_colors[cluster],
                size=12
            ),
            bgcolor="rgba(255, 255, 255, 0.8)",
            bordercolor=cluster_colors[cluster],
            borderwidth=1,
            borderpad=4
        )
    
    # Improve styling
    fig.update_layout(
        plot_bgcolor=COLORS["card-bg"],
        paper_bgcolor=COLORS["card-bg"],
        font_family="'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
        font_color=COLORS["text-primary"],
        showlegend=False,
        margin=dict(l=40, r=120, t=60, b=120),
        title={
            'text': f"<b>Country Performance Groups</b> for {measure} ({year})",
            'y':0.95,
            'x':0.5,
            'xanchor': 'center',
            'yanchor': 'top',
            'font': dict(size=18)
        }
    )
    
    # Better x-axis with rotated labels
    fig.update_xaxes(
        tickangle=45,
        tickmode='array',
        tickvals=list(range(len(cluster_df['Country'].unique()))),
        ticktext=cluster_df['Country'].unique()
    )
    
    # Add a storytelling annotation
    fig.add_annotation(
        x=0.5,
        y=-0.4,
        xref="paper",
        yref="paper",
        text=f"<i>Cluster Insight:</i> Countries are grouped by similar performance patterns",
        showarrow=False,
        font=dict(
            family="'Segoe UI', italic",
            size=12,
            color=COLORS["secondary"]
        ),
        align="center",
        bgcolor=COLORS["secondary-light"],
        bordercolor=COLORS["secondary"],
        borderwidth=1,
        borderpad=4
    )
    
    return fig

# Callback para generar el gráfico de predicciones
@callback(
    Output('predictions-graph', 'figure'),
    [Input('domain-dropdown', 'value'),
     Input('measure-dropdown', 'value'),
     Input('country-dropdown', 'value'),
     Input('demographic-dropdown', 'value')]
)
def update_predictions_graph(domain, measure, countries, demographic_type):
    if not domain or not measure or not countries or not demographic_type:
        return go.Figure()
    
    # We'll use 'Total' for demographic value for predictions
    demographic_value = 'Total'
    
    # Create figure
    fig = go.Figure()
    
    # Colors for countries
    country_colors = [COLORS["primary"], COLORS["secondary"], COLORS["accent"], 
                      "#D68C45", "#8E6C8A", "#4F94B8", "#97AC3D"]
    
    # Add lines for each country
    for i, country in enumerate(countries):
        color = country_colors[i % len(country_colors)]
        
        # Get historical data
        historical_df = oecd_df[(oecd_df['Domain'] == domain) & 
                             (oecd_df['Measure'] == measure) & 
                             (oecd_df['Country'] == country) &
                             (oecd_df[demographic_type] == demographic_value)]
        
        if len(historical_df) > 0:
            # Add historical line
            fig.add_trace(go.Scatter(
                x=historical_df['Year'],
                y=historical_df['OBS_VALUE'],
                mode='lines+markers',
                name=f"{country} (historical)",
                line=dict(color=color),
                marker=dict(size=12)
            ))
            
            # Try to predict future values
            future_years, predictions = predict_future_values(
                oecd_df, domain, measure, country, demographic_type, demographic_value
            )
            
            if future_years is not None and len(future_years) > 0:
                # Add prediction line
                fig.add_trace(go.Scatter(
                    x=future_years,
                    y=predictions,
                    mode='lines',
                    name=f"{country} (predicted)",
                    line=dict(color=color, dash='dash'),
                    marker=dict(size=8)
                ))
                
                # Add uncertainty area
                # Simple approach: 5% margin above and below
                fig.add_trace(go.Scatter(
                    x=np.concatenate([future_years, future_years[::-1]]),
                    y=np.concatenate([predictions * 1.05, (predictions * 0.95)[::-1]]),
                    fill='toself',
                    fillcolor=f"rgba({int(color[1:3], 16)}, {int(color[3:5], 16)}, {int(color[5:7], 16)}, 0.2)",
                    line=dict(color='rgba(0,0,0,0)'),
                    hoverinfo="skip",
                    showlegend=False
                ))
    
    # Improve styling
    fig.update_layout(
        plot_bgcolor=COLORS["card-bg"],
        paper_bgcolor=COLORS["card-bg"],
        font_family="'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
        font_color=COLORS["text-primary"],
        margin=dict(l=40, r=40, t=60, b=80),
        hoverlabel=dict(
            bgcolor=COLORS["primary-light"],
            font_size=12,
            font_family="'Segoe UI', Roboto"
        ),
        title={
            'text': f"<b>Future Trends</b> for {measure}",
            'y':0.95,
            'x':0.5,
            'xanchor': 'center',
            'yanchor': 'top',
            'font': dict(size=18)
        }
    )
    
    # Add vertical line to separate historical and predicted data
    if len(oecd_df) > 0:
        max_year = max(oecd_df['Year'])
        fig.add_vline(
            x=max_year, 
            line_width=1, 
            line_dash="dot", 
            line_color=COLORS["text-secondary"],
            annotation_text="Forecast starts",
            annotation_position="top right"
        )
    
    # Add a storytelling annotation
    fig.add_annotation(
        x=0.5,
        y=-0.15,
        xref="paper",
        yref="paper",
        text=f"<i>Forecast Insight:</i> These projections extend current trends into the future",
        showarrow=False,
        font=dict(
            family="'Segoe UI', italic",
            size=8,
            color=COLORS["accent"]
        ),
        align="center",
        bgcolor=COLORS["accent-light"],
        bordercolor=COLORS["accent"],
        borderwidth=1,
        borderpad=4
    )
    
    return fig

# Callback para actualizar el texto interpretativo con estilo storytelling
@callback(
    Output('interpretation-text', 'children'),
    [Input('domain-dropdown', 'value'),
     Input('measure-dropdown', 'value'),
     Input('year-dropdown', 'value'),
     Input('country-dropdown', 'value'),
     Input('demographic-dropdown', 'value'),
     Input('chart-tabs', 'active_tab')]
)
def update_interpretation_text(domain, measure, year, countries, demographic, active_tab):
    if not domain or not measure:
        return "Select parameters to see the story behind the numbers..."
    
    # Get domain description for storytelling
    domain_desc = domain_descriptions.get(domain, domain)
    
    # Different interpretations based on active tab
    if active_tab == "bar-tab":
        return html.Div([
            html.H5([html.I(className="fas fa-chart-bar me-2"), "Comparing Well-being Across Nations"]),
            html.P([
                "The chart above reveals how different countries compare on ",
                html.Span(f"{measure}", className="fw-bold"), 
                ", a key indicator in the ", 
                html.Span(f"{domain}", className="story-emphasis"), 
                " domain of well-being."
            ]),
            html.P([
                f"{domain_desc}"
            ]),
            html.P([
                "By examining differences across ",
                html.Span(demographic.lower(), className="story-emphasis"),
                " groups, we can uncover hidden patterns in well-being that might be missed in aggregate statistics.",
                " These patterns often reflect deeper social structures, cultural values, and policy environments."
            ]),
            html.P([
                "What story does this data tell about societal priorities and challenges? ",
                "Consider how historical contexts and policy choices might have shaped these outcomes."
            ], className="fst-italic text-muted mt-3")
        ])
    
    elif active_tab == "time-tab":
        return html.Div([
            html.H5([html.I(className="fas fa-history me-2"), "The Evolution of Well-being"]),
            html.P([
                "This timeline shows how ",
                html.Span(f"{measure}", className="fw-bold"), 
                " has evolved over time, revealing progress, setbacks, and persistent challenges in the ",
                html.Span(f"{domain.lower()}", className="story-emphasis"),
                " domain."
            ]),
            html.P([
                "Trajectories often reflect major policy shifts, economic cycles, or social transformations. ",
                "Diverging paths between countries can highlight different approaches to similar challenges."
            ]),
            html.P([
                "Look for pivotal moments where trends change direction—these often mark important policy ",
                "interventions or external shocks that reshape well-being outcomes."
            ]),
            html.P([
                "What future directions do these trajectories suggest? Which approaches appear most sustainable or equitable?"
            ], className="fst-italic text-muted mt-3")
        ])
    
    elif active_tab == "clusters-tab":
        return html.Div([
            html.H5([html.I(className="fas fa-object-group me-2"), "Patterns Across Nations"]),
            html.P([
                "This analysis groups countries into clusters based on their performance in ",
                html.Span(f"{measure}", className="fw-bold"),
                ", revealing natural groupings in the data."
            ]),
            html.P([
                "Countries within the same cluster often share similar historical contexts, policy approaches, ",
                "or socioeconomic conditions that contribute to comparable outcomes in this aspect of ",
                html.Span(f"{domain.lower()}", className="story-emphasis"),
                "."
            ]),
            html.P([
                "These patterns invite deeper investigation: What common characteristics or policies might explain ",
                "why certain countries cluster together? What can lower-performing countries learn from those with stronger outcomes?"
            ]),
            html.P([
                "Consider these clusters as starting points for more nuanced comparative analysis, rather than definitive groupings."
            ], className="fst-italic text-muted mt-3")
        ])
    
    elif active_tab == "predictions-tab":
        return html.Div([
            html.H5([html.I(className="fas fa-crystal-ball me-2"), "Glimpsing Future Possibilities"]),
            html.P([
                "These projections extend current trends in ",
                html.Span(f"{measure}", className="fw-bold"),
                " to suggest possible future trajectories, based on historical patterns in the ", 
                html.Span(f"{domain.lower()}", className="story-emphasis"),
                " domain."
            ]),
            html.P([
                "The shaded areas represent uncertainty—reminder that the future is not predetermined. ",
                "Policy interventions, social changes, or external disruptions could alter these trajectories."
            ]),
            html.P([
                "Countries with diverging projections suggest different levels of sustainability in current approaches. ",
                "Convergence might indicate that different paths ultimately lead to similar outcomes over time."
            ]),
            html.P([
                "How might these projections inform current policy priorities? What interventions could help bend concerning trends toward more positive outcomes?"
            ], className="fst-italic text-muted mt-3")
        ])
    
    else:
        return "Explore the data to uncover the story behind the numbers..."