File size: 42,315 Bytes
e452864
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# ui/analytics_tab.py
import gradio as gr
import pandas as pd
import logging
from collections import OrderedDict
import asyncio
from datetime import datetime, timedelta

# --- Module Imports ---
from config import PLOT_ID_TO_FORMULA_KEY_MAP
from ui.ui_generators import (
    build_analytics_tab_plot_area,
    BOMB_ICON, EXPLORE_ICON, FORMULA_ICON, ACTIVE_ICON
)
from ui.analytics_plot_generator import update_analytics_plots_figures, create_placeholder_plot
from formulas import PLOT_FORMULAS
from features.chatbot.chatbot_prompts import get_initial_insight_prompt_and_suggestions
from features.chatbot.chatbot_handler import generate_llm_response

logger = logging.getLogger(__name__)

PLOT_CONFIGS = [
    {"label": "Numero di Follower nel Tempo", "id": "followers_count", "section": "Dinamiche dei Follower"},
    {"label": "Tasso di Crescita Follower", "id": "followers_growth_rate", "section": "Dinamiche dei Follower"},
    {"label": "Follower per Località", "id": "followers_by_location", "section": "Demografia Follower"},
    {"label": "Follower per Ruolo (Funzione)", "id": "followers_by_role", "section": "Demografia Follower"},
    {"label": "Follower per Settore", "id": "followers_by_industry", "section": "Demografia Follower"},
    {"label": "Follower per Anzianità", "id": "followers_by_seniority", "section": "Demografia Follower"},
    {"label": "Tasso di Engagement nel Tempo", "id": "engagement_rate", "section": "Approfondimenti Performance Post"},
    {"label": "Copertura nel Tempo", "id": "reach_over_time", "section": "Approfondimenti Performance Post"},
    {"label": "Visualizzazioni nel Tempo", "id": "impressions_over_time", "section": "Approfondimenti Performance Post"},
    {"label": "Reazioni (Like) nel Tempo", "id": "likes_over_time", "section": "Approfondimenti Performance Post"},
    {"label": "Click nel Tempo", "id": "clicks_over_time", "section": "Engagement Dettagliato Post nel Tempo"},
    {"label": "Condivisioni nel Tempo", "id": "shares_over_time", "section": "Engagement Dettagliato Post nel Tempo"},
    {"label": "Commenti nel Tempo", "id": "comments_over_time", "section": "Engagement Dettagliato Post nel Tempo"},
    {"label": "Ripartizione Commenti per Sentiment", "id": "comments_sentiment", "section": "Engagement Dettagliato Post nel Tempo"},
    {"label": "Frequenza Post", "id": "post_frequency_cs", "section": "Analisi Strategia Contenuti"},
    {"label": "Ripartizione Contenuti per Formato", "id": "content_format_breakdown_cs", "section": "Analisi Strategia Contenuti"},
    {"label": "Ripartizione Contenuti per Argomenti", "id": "content_topic_breakdown_cs", "section": "Analisi Strategia Contenuti"},
    {"label": "Volume Menzioni nel Tempo (Dettaglio)", "id": "mention_analysis_volume", "section": "Analisi Menzioni (Dettaglio)"},
    {"label": "Ripartizione Menzioni per Sentiment (Dettaglio)", "id": "mention_analysis_sentiment", "section": "Analisi Menzioni (Dettaglio)"}
]
# IMPORTANT: Review if 'mention_analysis_volume' and 'mention_analysis_sentiment' plots
# can still be generated without the dedicated mentions data processing.
# If not, they should also be removed from PLOT_CONFIGS.
# For now, I am assuming they might draw from a general data pool in token_state.
assert len(PLOT_CONFIGS) == 19, "Mancata corrispondenza in PLOT_CONFIGS e grafici attesi."

UNIQUE_ORDERED_SECTIONS = list(OrderedDict.fromkeys(pc["section"] for pc in PLOT_CONFIGS))
NUM_UNIQUE_SECTIONS = len(UNIQUE_ORDERED_SECTIONS)

# Store references to UI components that handlers need to update
_plot_ui_objects = {}
_section_titles_map = {}
_global_actions_column_ui = None
_insights_chatbot_ui = None
_insights_chat_input_ui = None
_insights_suggestions_row_ui = None
_insights_suggestion_1_btn = None
_insights_suggestion_2_btn = None
_insights_suggestion_3_btn = None
_formula_display_markdown_ui = None
_formula_close_hint_md = None
_analytics_status_md = None
_date_filter_selector = None
_custom_start_date_picker = None
_custom_end_date_picker = None


def handle_toggle_custom_date_pickers(selection):
    is_custom = selection == "Intervallo Personalizzato"
    return gr.update(visible=is_custom), gr.update(visible=is_custom)

async def handle_panel_action(
    plot_id_clicked: str, action_type: str, current_active_action_from_state: dict,
    current_chat_histories: dict, current_chat_plot_id: str,
    current_plot_data_for_chatbot: dict, current_explored_plot_id: str
):
    logger.info(f"Panel Action: '{action_type}' for plot '{plot_id_clicked}'. Active: {current_active_action_from_state}, Explored: {current_explored_plot_id}")
    clicked_plot_config = next((p for p in PLOT_CONFIGS if p["id"] == plot_id_clicked), None)
    if not clicked_plot_config:
        logger.error(f"Config not found for plot_id {plot_id_clicked}")
        num_plots = len(PLOT_CONFIGS)
        error_list_len = 15 + (4 * num_plots) + NUM_UNIQUE_SECTIONS # Matches expected length in original code
        error_list = [gr.update()] * error_list_len
        error_list[11] = current_active_action_from_state # active_panel_action_state
        error_list[12] = current_chat_plot_id # current_chat_plot_id_st
        error_list[13] = current_chat_histories # chat_histories_st
        error_list[14] = current_explored_plot_id # explored_plot_id_state
        return error_list

    clicked_plot_label = clicked_plot_config["label"]
    clicked_plot_section = clicked_plot_config["section"]
    hypothetical_new_active_state = {"plot_id": plot_id_clicked, "type": action_type}
    is_toggling_off = current_active_action_from_state == hypothetical_new_active_state

    action_col_visible_update = gr.update(visible=False)
    insights_chatbot_visible_update = gr.update(visible=False)
    insights_chat_input_visible_update = gr.update(visible=False)
    insights_suggestions_row_visible_update = gr.update(visible=False)
    formula_display_visible_update = gr.update(visible=False)
    formula_close_hint_visible_update = gr.update(visible=False)

    chatbot_content_update = gr.update()
    s1_upd, s2_upd, s3_upd = gr.update(), gr.update(), gr.update()
    formula_content_update = gr.update()

    new_active_action_state_to_set = None
    new_current_chat_plot_id = current_chat_plot_id
    updated_chat_histories = current_chat_histories
    new_explored_plot_id_to_set = current_explored_plot_id

    generated_panel_vis_updates = []
    generated_bomb_btn_updates = []
    generated_formula_btn_updates = []
    generated_explore_btn_updates = []
    section_title_vis_updates = [gr.update()] * NUM_UNIQUE_SECTIONS

    if is_toggling_off:
        new_active_action_state_to_set = None
        action_col_visible_update = gr.update(visible=False)
        logger.info(f"Toggling OFF panel {action_type} for {plot_id_clicked}.")
        for _ in PLOT_CONFIGS:
            generated_bomb_btn_updates.append(gr.update(value=BOMB_ICON))
            generated_formula_btn_updates.append(gr.update(value=FORMULA_ICON))

        if current_explored_plot_id:
            explored_cfg = next((p for p in PLOT_CONFIGS if p["id"] == current_explored_plot_id), None)
            explored_sec = explored_cfg["section"] if explored_cfg else None
            for i, sec_name in enumerate(UNIQUE_ORDERED_SECTIONS):
                section_title_vis_updates[i] = gr.update(visible=(sec_name == explored_sec))
            for cfg in PLOT_CONFIGS:
                is_exp = (cfg["id"] == current_explored_plot_id)
                generated_panel_vis_updates.append(gr.update(visible=is_exp))
                generated_explore_btn_updates.append(gr.update(value=ACTIVE_ICON if is_exp else EXPLORE_ICON))
        else:
            for i in range(NUM_UNIQUE_SECTIONS):
                section_title_vis_updates[i] = gr.update(visible=True)
            for _ in PLOT_CONFIGS:
                generated_panel_vis_updates.append(gr.update(visible=True))
                generated_explore_btn_updates.append(gr.update(value=EXPLORE_ICON))
        if action_type == "insights":
            new_current_chat_plot_id = None # Reset chat plot ID
    else: # Toggling ON or switching
        new_active_action_state_to_set = hypothetical_new_active_state
        action_col_visible_update = gr.update(visible=True)
        new_explored_plot_id_to_set = None # Cancel explore view
        logger.info(f"Toggling ON panel {action_type} for {plot_id_clicked}. Cancelling explore view if any.")

        for i, sec_name in enumerate(UNIQUE_ORDERED_SECTIONS):
            section_title_vis_updates[i] = gr.update(visible=(sec_name == clicked_plot_section))
        for cfg in PLOT_CONFIGS:
            generated_panel_vis_updates.append(gr.update(visible=(cfg["id"] == plot_id_clicked)))
            generated_explore_btn_updates.append(gr.update(value=EXPLORE_ICON)) # Reset all explore buttons

        for cfg_btn in PLOT_CONFIGS:
            is_active_insights = new_active_action_state_to_set == {"plot_id": cfg_btn["id"], "type": "insights"}
            is_active_formula = new_active_action_state_to_set == {"plot_id": cfg_btn["id"], "type": "formula"}
            generated_bomb_btn_updates.append(gr.update(value=ACTIVE_ICON if is_active_insights else BOMB_ICON))
            generated_formula_btn_updates.append(gr.update(value=ACTIVE_ICON if is_active_formula else FORMULA_ICON))

        if action_type == "insights":
            insights_chatbot_visible_update = gr.update(visible=True)
            insights_chat_input_visible_update = gr.update(visible=True)
            insights_suggestions_row_visible_update = gr.update(visible=True)
            new_current_chat_plot_id = plot_id_clicked
            history = current_chat_histories.get(plot_id_clicked, [])
            summary = current_plot_data_for_chatbot.get(plot_id_clicked, f"No summary for '{clicked_plot_label}'.")

            if not history: # First time opening chat for this plot
                prompt, sugg = get_initial_insight_prompt_and_suggestions(plot_id_clicked, clicked_plot_label, summary)
                llm_history_for_api = [{"role": "user", "content": prompt}] # History for LLM call
                # Yield initial state if you want to show "Thinking..."
                # For simplicity, directly call and update.
                response_text = await generate_llm_response(prompt, plot_id_clicked, clicked_plot_label, llm_history_for_api, summary)
                history = [{"role": "assistant", "content": response_text}] # Gradio chat history
                updated_chat_histories = {**current_chat_histories, plot_id_clicked: history}
            else: # Re-opening chat, just get suggestions
                _, sugg = get_initial_insight_prompt_and_suggestions(plot_id_clicked, clicked_plot_label, summary)

            chatbot_content_update = gr.update(value=history)
            s1_upd = gr.update(value=sugg[0] if sugg and len(sugg) > 0 else "N/A")
            s2_upd = gr.update(value=sugg[1] if sugg and len(sugg) > 1 else "N/A")
            s3_upd = gr.update(value=sugg[2] if sugg and len(sugg) > 2 else "N/A")

        elif action_type == "formula":
            formula_display_visible_update = gr.update(visible=True)
            formula_close_hint_visible_update = gr.update(visible=True)
            formula_key = PLOT_ID_TO_FORMULA_KEY_MAP.get(plot_id_clicked)
            formula_text = f"**Formula/Methodology for: {clicked_plot_label}** (ID: `{plot_id_clicked}`)\n\n"
            if formula_key and formula_key in PLOT_FORMULAS:
                formula_data = PLOT_FORMULAS[formula_key]
                formula_text += f"### {formula_data['title']}\n\n{formula_data['description']}\n\n**Calculation:**\n"
                formula_text += "\n".join([f"- {step}" for step in formula_data['calculation_steps']])
            else:
                formula_text += "(No detailed formula information found.)"
            formula_content_update = gr.update(value=formula_text)
            new_current_chat_plot_id = None # Ensure chat context is cleared if formula is opened

    # Order of outputs must match the list provided to .click() in build_and_wire_tab
    final_updates = [
        action_col_visible_update,          # global_actions_column_ui
        insights_chatbot_visible_update,    # insights_chatbot_ui (visibility)
        chatbot_content_update,             # insights_chatbot_ui (content)
        insights_chat_input_visible_update, # insights_chat_input_ui
        insights_suggestions_row_visible_update, # insights_suggestions_row_ui
        s1_upd,                             # insights_suggestion_1_btn
        s2_upd,                             # insights_suggestion_2_btn
        s3_upd,                             # insights_suggestion_3_btn
        formula_display_visible_update,     # formula_display_markdown_ui (visibility)
        formula_content_update,             # formula_display_markdown_ui (content)
        formula_close_hint_visible_update,  # formula_close_hint_md
        new_active_action_state_to_set,     # active_panel_action_state (state)
        new_current_chat_plot_id,           # current_chat_plot_id_st (state)
        updated_chat_histories,             # chat_histories_st (state)
        new_explored_plot_id_to_set         # explored_plot_id_state (state)
    ]
    final_updates.extend(generated_panel_vis_updates) # plot_ui_objects[pc["id"]]["panel_component"]
    final_updates.extend(generated_bomb_btn_updates)    # plot_ui_objects[pc["id"]]["bomb_button"]
    final_updates.extend(generated_formula_btn_updates)# plot_ui_objects[pc["id"]]["formula_button"]
    final_updates.extend(generated_explore_btn_updates) # plot_ui_objects[pc["id"]]["explore_button"]
    final_updates.extend(section_title_vis_updates)   # section_titles_map[s_name]

    logger.debug(f"handle_panel_action returning {len(final_updates)} updates. Expected {15 + 4*len(PLOT_CONFIGS) + NUM_UNIQUE_SECTIONS}.")
    return final_updates

async def handle_chat_message_submission(user_message: str, current_plot_id: str, chat_histories: dict, current_plot_data_for_chatbot: dict ):
    if not current_plot_id or not user_message.strip():
        current_history_for_plot = chat_histories.get(current_plot_id, [])
        if not isinstance(current_history_for_plot, list): current_history_for_plot = []
        yield current_history_for_plot, gr.update(value=""), chat_histories # chatbot, chat_input, chat_histories_st
        return

    cfg = next((p for p in PLOT_CONFIGS if p["id"] == current_plot_id), None)
    lbl = cfg["label"] if cfg else "Selected Plot"
    summary = current_plot_data_for_chatbot.get(current_plot_id, f"No summary for '{lbl}'.")

    hist_for_plot = chat_histories.get(current_plot_id, [])
    if not isinstance(hist_for_plot, list): hist_for_plot = [] # Ensure it's a list

    # Append user message to local history for display
    current_display_history = hist_for_plot.copy() + [{"role": "user", "content": user_message}]
    yield current_display_history, gr.update(value=""), chat_histories # Update UI immediately with user message

    # Prepare history for LLM (this might be different from display history if system prompts are used internally)
    llm_call_history = current_display_history # Or a modified version
    
    response_text = await generate_llm_response(user_message, current_plot_id, lbl, llm_call_history, summary)
    
    # Append AI response to display history
    current_display_history.append({"role": "assistant", "content": response_text})
    
    # Update the master chat_histories state
    updated_chat_histories = {**chat_histories, current_plot_id: current_display_history}
    
    yield current_display_history, "", updated_chat_histories


async def handle_suggested_question_click(suggestion_text: str, current_plot_id: str, chat_histories: dict, current_plot_data_for_chatbot: dict):
    if not current_plot_id or not suggestion_text.strip() or suggestion_text == "N/A":
        current_history_for_plot = chat_histories.get(current_plot_id, [])
        if not isinstance(current_history_for_plot, list): current_history_for_plot = []
        yield current_history_for_plot, gr.update(value=""), chat_histories
        return

    # Use an async generator to stream updates from handle_chat_message_submission
    async for update_chunk in handle_chat_message_submission(suggestion_text, current_plot_id, chat_histories, current_plot_data_for_chatbot):
        yield update_chunk


def handle_explore_click(plot_id_clicked, current_explored_plot_id_from_state, current_active_panel_action_state):
    logger.info(f"Explore Click: Plot '{plot_id_clicked}'. Current Explored: {current_explored_plot_id_from_state}. Active Panel: {current_active_panel_action_state}")
    num_plots = len(PLOT_CONFIGS)

    if not _plot_ui_objects: # Ensure _plot_ui_objects is populated
        logger.error("_plot_ui_objects not populated for handle_explore_click.")
        # Construct an error return list of the correct length
        error_list_len = 4 + (4 * num_plots) + NUM_UNIQUE_SECTIONS
        error_list = [gr.update()] * error_list_len
        error_list[0] = current_explored_plot_id_from_state # explored_plot_id_state
        error_list[2] = current_active_panel_action_state # active_panel_action_state
        # Other elements remain gr.update()
        return error_list

    new_explored_id_to_set = None
    is_toggling_off_explore = (plot_id_clicked == current_explored_plot_id_from_state)

    action_col_upd = gr.update() # Default: no change
    new_active_panel_state_upd = current_active_panel_action_state # Default: no change
    formula_hint_upd = gr.update(visible=False) # Default: hide formula hint

    panel_vis_updates = []
    explore_btns_updates = []
    bomb_btns_updates = [gr.update() for _ in PLOT_CONFIGS] # Default: no change
    formula_btns_updates = [gr.update() for _ in PLOT_CONFIGS] # Default: no change
    section_title_vis_updates = [gr.update()] * NUM_UNIQUE_SECTIONS

    clicked_cfg = next((p for p in PLOT_CONFIGS if p["id"] == plot_id_clicked), None)
    sec_of_clicked = clicked_cfg["section"] if clicked_cfg else None

    if is_toggling_off_explore:
        new_explored_id_to_set = None
        logger.info(f"Stopping explore for {plot_id_clicked}. All plots/sections to be visible.")
        for i in range(NUM_UNIQUE_SECTIONS):
            section_title_vis_updates[i] = gr.update(visible=True)
        for _ in PLOT_CONFIGS:
            panel_vis_updates.append(gr.update(visible=True))
            explore_btns_updates.append(gr.update(value=EXPLORE_ICON))
        # Bomb and Formula buttons remain as they were unless an action panel was closed
    else: # Activating explore for plot_id_clicked or switching explore target
        new_explored_id_to_set = plot_id_clicked
        logger.info(f"Exploring {plot_id_clicked}. Hiding other plots/sections.")
        for i, sec_name in enumerate(UNIQUE_ORDERED_SECTIONS):
            section_title_vis_updates[i] = gr.update(visible=(sec_name == sec_of_clicked))
        for cfg in PLOT_CONFIGS:
            is_target = (cfg["id"] == new_explored_id_to_set)
            panel_vis_updates.append(gr.update(visible=is_target))
            explore_btns_updates.append(gr.update(value=ACTIVE_ICON if is_target else EXPLORE_ICON))

        if current_active_panel_action_state: # If an action panel (insights/formula) is open
            logger.info("Closing active insight/formula panel due to explore click.")
            action_col_upd = gr.update(visible=False)
            new_active_panel_state_upd = None # Clear active panel state
            formula_hint_upd = gr.update(visible=False) # Hide formula hint specifically
            # Reset bomb and formula buttons to their default icons
            bomb_btns_updates = [gr.update(value=BOMB_ICON) for _ in PLOT_CONFIGS]
            formula_btns_updates = [gr.update(value=FORMULA_ICON) for _ in PLOT_CONFIGS]

    # Order of outputs must match the list provided to .click() in build_and_wire_tab
    final_explore_updates = [
        new_explored_id_to_set,         # explored_plot_id_state
        action_col_upd,                 # global_actions_column_ui
        new_active_panel_state_upd,     # active_panel_action_state
        formula_hint_upd                # formula_close_hint_md (specifically for closing formula panel)
    ]
    final_explore_updates.extend(panel_vis_updates)         # plot_ui_objects[pc["id"]]["panel_component"]
    final_explore_updates.extend(explore_btns_updates)      # plot_ui_objects[pc["id"]]["explore_button"]
    final_explore_updates.extend(bomb_btns_updates)         # plot_ui_objects[pc["id"]]["bomb_button"]
    final_explore_updates.extend(formula_btns_updates)      # plot_ui_objects[pc["id"]]["formula_button"]
    final_explore_updates.extend(section_title_vis_updates) # section_titles_map[s_name]

    logger.debug(f"handle_explore_click returning {len(final_explore_updates)} updates. Expected {4 + 4*len(PLOT_CONFIGS) + NUM_UNIQUE_SECTIONS}.")
    return final_explore_updates

async def handle_refresh_analytics_graphs(current_token_state_val, date_filter_val, custom_start_val, custom_end_val, current_chat_histories_val):
    logger.info("Refreshing analytics graph UI elements and resetting actions/chat.")
    # Call the existing plot generation logic
    plot_gen_results = update_analytics_plots_figures(current_token_state_val, date_filter_val, custom_start_val, custom_end_val, PLOT_CONFIGS)
    status_msg, gen_figs, new_summaries_for_chatbot = plot_gen_results[0], plot_gen_results[1:-1], plot_gen_results[-1]

    all_updates = [status_msg] # For analytics_status_md
    all_updates.extend(gen_figs if len(gen_figs) == len(PLOT_CONFIGS) else [create_placeholder_plot("Error", f"Fig missing {i}") for i in range(len(PLOT_CONFIGS))]) # For each plot component

    # Updates for resetting the global action panel UI
    all_updates.extend([
        gr.update(visible=False),  # global_actions_column_ui
        gr.update(value=[], visible=False),  # insights_chatbot_ui (content and visibility)
        gr.update(value="", visible=False),  # insights_chat_input_ui
        gr.update(visible=False),  # insights_suggestions_row_ui
        gr.update(value="Suggerimento 1"),  # insights_suggestion_1_btn
        gr.update(value="Suggerimento 2"),  # insights_suggestion_2_btn
        gr.update(value="Suggerimento 3"),  # insights_suggestion_3_btn
        gr.update(value="Formula details here.", visible=False),  # formula_display_markdown_ui
        gr.update(visible=False)  # formula_close_hint_md
    ])

    # Updates for resetting relevant states
    all_updates.extend([
        None,  # active_panel_action_state
        None,  # current_chat_plot_id_st
        {},    # chat_histories_st (resetting all chat histories on graph refresh)
        new_summaries_for_chatbot  # plot_data_for_chatbot_st
    ])

    # Updates for resetting plot-specific action buttons and panel visibility
    for _ in PLOT_CONFIGS:
        all_updates.extend([
            gr.update(value=BOMB_ICON),      # bomb_button
            gr.update(value=FORMULA_ICON),   # formula_button
            gr.update(value=EXPLORE_ICON),   # explore_button
            gr.update(visible=True)          # panel_component (make all plot panels visible)
        ])
    
    all_updates.append(None) # explored_plot_id_state (reset explore state)

    # Updates for making all section titles visible
    all_updates.extend([gr.update(visible=True)] * NUM_UNIQUE_SECTIONS)
    
    expected_len = 1 + len(PLOT_CONFIGS) + 9 + 4 + (4 * len(PLOT_CONFIGS)) + 1 + NUM_UNIQUE_SECTIONS # Match original structure
    logger.info(f"Prepared {len(all_updates)} updates for graph refresh. Expected {expected_len}.")
    if len(all_updates) != expected_len:
        logger.error(f"MISMATCH in refresh_analytics_graphs_ui output length. Got {len(all_updates)}, expected {expected_len}")
        # Fallback to a safe number of gr.update() if length mismatch to avoid Gradio error
        # This part needs careful review if mismatches occur.
        # For now, assume the calculation is correct based on original structure.
    return tuple(all_updates)


def build_and_wire_tab(token_state, chat_histories_st, current_chat_plot_id_st, plot_data_for_chatbot_st, active_panel_action_state, explored_plot_id_state):
    """Builds the UI for the Analytics Tab and wires up its internal event handlers."""
    global _plot_ui_objects, _section_titles_map, _global_actions_column_ui, \
           _insights_chatbot_ui, _insights_chat_input_ui, _insights_suggestions_row_ui, \
           _insights_suggestion_1_btn, _insights_suggestion_2_btn, _insights_suggestion_3_btn, \
           _formula_display_markdown_ui, _formula_close_hint_md, _analytics_status_md, \
           _date_filter_selector, _custom_start_date_picker, _custom_end_date_picker
    
    # These will be returned to app.py for .then() chains if needed, or for constructing output lists
    # that app.py will manage for calls to handlers in this module.
    components_for_refresh_outputs = []

    with gr.Column(): # Main column for the tab
        _analytics_status_md = gr.Markdown("Stato analisi grafici...")
        components_for_refresh_outputs.append(_analytics_status_md)

        gr.Markdown("## 📈 Analisi Performance LinkedIn")
        gr.Markdown("Seleziona un intervallo di date per i grafici. Clicca i pulsanti (💣 Insights, ƒ Formula, 🧭 Esplora) su un grafico per azioni.")

        with gr.Row():
            _date_filter_selector = gr.Radio(
                ["Sempre", "Ultimi 7 Giorni", "Ultimi 30 Giorni", "Intervallo Personalizzato"],
                label="Seleziona Intervallo Date per Grafici", value="Sempre", scale=3
            )
            with gr.Column(scale=2):
                _custom_start_date_picker = gr.DateTime(label="Data Inizio", visible=False, include_time=False, type="datetime")
                _custom_end_date_picker = gr.DateTime(label="Data Fine", visible=False, include_time=False, type="datetime")
        
        apply_filter_btn = gr.Button("🔍 Applica Filtro & Aggiorna Grafici", variant="primary")

        _date_filter_selector.change(
            fn=handle_toggle_custom_date_pickers,
            inputs=[_date_filter_selector],
            outputs=[_custom_start_date_picker, _custom_end_date_picker]
        )
        
        with gr.Row(equal_height=False):
            with gr.Column(scale=8) as plots_area_col:
                # Call the existing UI generator for plots
                # This function needs to populate _plot_ui_objects and _section_titles_map
                # For simplicity, assume build_analytics_tab_plot_area is adapted or its results are processed here
                ui_elements_tuple = build_analytics_tab_plot_area(PLOT_CONFIGS)
                if isinstance(ui_elements_tuple, tuple) and len(ui_elements_tuple) == 2:
                    _plot_ui_objects, _section_titles_map = ui_elements_tuple
                    if not all(sec_name in _section_titles_map for sec_name in UNIQUE_ORDERED_SECTIONS):
                        logger.error("section_titles_map from build_analytics_tab_plot_area is incomplete.")
                        # Ensure _section_titles_map has all keys for safety in handlers
                        for sec_name in UNIQUE_ORDERED_SECTIONS:
                            if sec_name not in _section_titles_map:
                                _section_titles_map[sec_name] = gr.Markdown(f"### {sec_name} (Error Placeholder)")
                else: # Fallback if the function signature changes or an error occurs
                    logger.error("build_analytics_tab_plot_area did not return a tuple of (plot_ui_objects, section_titles_map).")
                    _plot_ui_objects = ui_elements_tuple if isinstance(ui_elements_tuple, dict) else {}
                    for sec_name in UNIQUE_ORDERED_SECTIONS:
                         _section_titles_map[sec_name] = gr.Markdown(f"### {sec_name} (Error Placeholder)")
                    # Ensure all plot IDs have a placeholder in _plot_ui_objects for safety
                    for pc_cfg in PLOT_CONFIGS:
                        if pc_cfg['id'] not in _plot_ui_objects:
                             _plot_ui_objects[pc_cfg['id']] = {
                                "plot_component": gr.Plot(label=pc_cfg['label']), # Placeholder
                                "panel_component": gr.Group(visible=True), # Placeholder
                                "bomb_button": gr.Button(value=BOMB_ICON, size="sm", min_width=10),
                                "formula_button": gr.Button(value=FORMULA_ICON, size="sm", min_width=10),
                                "explore_button": gr.Button(value=EXPLORE_ICON, size="sm", min_width=10)
                             }


            _global_actions_column_ui = gr.Column(scale=4, visible=False) # Assign to module-level var
            with _global_actions_column_ui:
                gr.Markdown("### 💡 Azioni Contestuali Grafico")
                _insights_chatbot_ui = gr.Chatbot(
                    label="Chat Insights", type="messages", height=450,
                    bubble_full_width=False, visible=False, show_label=False,
                    placeholder="L'analisi AI del grafico apparirà qui. Fai domande di approfondimento!"
                )
                _insights_chat_input_ui = gr.Textbox(
                    label="La tua domanda:", placeholder="Chiedi all'AI riguardo a questo grafico...",
                    lines=2, visible=False, show_label=False
                )
                _insights_suggestions_row_ui = gr.Row(visible=False)
                with _insights_suggestions_row_ui:
                    _insights_suggestion_1_btn = gr.Button(value="Suggerimento 1", size="sm", min_width=50)
                    _insights_suggestion_2_btn = gr.Button(value="Suggerimento 2", size="sm", min_width=50)
                    _insights_suggestion_3_btn = gr.Button(value="Suggerimento 3", size="sm", min_width=50)

                _formula_display_markdown_ui = gr.Markdown(
                    "I dettagli sulla formula/metodologia appariranno qui.", visible=False
                )
                _formula_close_hint_md = gr.Markdown(
                    "<p style='font-size:0.9em; text-align:center; margin-top:10px;'><em>Click the active ƒ button on the plot again to close this panel.</em></p>",
                    visible=False
                )
        
        # --- Outputs for handle_refresh_analytics_graphs ---
        # Order: analytics_status_md
        #        plot_components (from _plot_ui_objects)
        #        global_actions_column_ui, insights_chatbot_ui (vis), insights_chatbot_ui (val), insights_chat_input_ui, insights_suggestions_row_ui, s1,s2,s3, formula_display_md (vis), formula_display_md (val), formula_close_hint
        #        active_panel_action_state, current_chat_plot_id_st, chat_histories_st, plot_data_for_chatbot_st
        #        bomb_buttons, formula_buttons, explore_buttons, panel_components (from _plot_ui_objects)
        #        explored_plot_id_state
        #        section_title_markdowns (from _section_titles_map)
        
        for pc_cfg in PLOT_CONFIGS: # plot_components
            components_for_refresh_outputs.append(_plot_ui_objects.get(pc_cfg["id"], {}).get("plot_component", gr.Plot()))
        
        components_for_refresh_outputs.extend([ # UI resets for global action panel
            _global_actions_column_ui, _insights_chatbot_ui, _insights_chat_input_ui, 
            _insights_suggestions_row_ui, _insights_suggestion_1_btn, _insights_suggestion_2_btn, 
            _insights_suggestion_3_btn, _formula_display_markdown_ui, _formula_close_hint_md
        ])
        # Note: For components like _insights_chatbot_ui that need separate visibility and value updates,
        # handle_refresh_analytics_graphs provides two gr.update() calls. The outputs list here should map to that.
        # The current handle_refresh_analytics_graphs structure implies the value for _insights_chatbot_ui is part of its visibility update.
        # This needs to be consistent. The original code had `insights_chatbot_ui` twice in `_base_action_panel_ui_outputs`.
        # Let's assume for now that `gr.update(value=[], visible=False)` handles both for `_insights_chatbot_ui`.

        # States are not components, they are updated directly by handlers.
        # The list `components_for_refresh_outputs` is for Gradio `outputs=[...]` argument.

        for pc_cfg in PLOT_CONFIGS: # plot action buttons and panels
            plot_obj = _plot_ui_objects.get(pc_cfg["id"], {})
            components_for_refresh_outputs.extend([
                plot_obj.get("bomb_button", gr.Button()),
                plot_obj.get("formula_button", gr.Button()),
                plot_obj.get("explore_button", gr.Button()),
                plot_obj.get("panel_component", gr.Group())
            ])
        
        for sec_name in UNIQUE_ORDERED_SECTIONS: # section titles
            components_for_refresh_outputs.append(_section_titles_map.get(sec_name, gr.Markdown()))


        # --- Outputs for handle_panel_action & handle_explore_click ---
        # These lists are constructed inside the handlers themselves using the module-level component variables.
        # What app.py needs is the list of components that these handlers will update.
        
        action_panel_event_outputs = [
            _global_actions_column_ui, _insights_chatbot_ui, _insights_chatbot_ui, # vis, val
            _insights_chat_input_ui, _insights_suggestions_row_ui,
            _insights_suggestion_1_btn, _insights_suggestion_2_btn, _insights_suggestion_3_btn,
            _formula_display_markdown_ui, _formula_display_markdown_ui, # vis, val
            _formula_close_hint_md,
            # States: active_panel_action_state, current_chat_plot_id_st, chat_histories_st, explored_plot_id_state
        ]
        # Add plot-specific components (panels, buttons)
        for pc in PLOT_CONFIGS:
            ui_obj = _plot_ui_objects.get(pc["id"], {})
            action_panel_event_outputs.extend([
                ui_obj.get("panel_component", gr.Group()), ui_obj.get("bomb_button", gr.Button()),
                ui_obj.get("formula_button", gr.Button()), ui_obj.get("explore_button", gr.Button())
            ])
        # Add section titles
        for s_name in UNIQUE_ORDERED_SECTIONS:
            action_panel_event_outputs.append(_section_titles_map.get(s_name, gr.Markdown()))


        explore_event_outputs = [
            # States: explored_plot_id_state, active_panel_action_state
            _global_actions_column_ui, _formula_close_hint_md
        ]
        # Add plot-specific components (panels, buttons)
        for pc in PLOT_CONFIGS:
            ui_obj = _plot_ui_objects.get(pc["id"], {})
            explore_event_outputs.extend([
                ui_obj.get("panel_component", gr.Group()), ui_obj.get("explore_button", gr.Button()),
                ui_obj.get("bomb_button", gr.Button()), ui_obj.get("formula_button", gr.Button())
            ])
        # Add section titles
        for s_name in UNIQUE_ORDERED_SECTIONS:
            explore_event_outputs.append(_section_titles_map.get(s_name, gr.Markdown()))

        # --- Event Wiring ---
        action_click_inputs = [active_panel_action_state, chat_histories_st, current_chat_plot_id_st, plot_data_for_chatbot_st, explored_plot_id_state]
        explore_click_inputs = [explored_plot_id_state, active_panel_action_state]

        def create_panel_action_handler_closure(p_id, action_type_str): # Renamed from original to avoid conflict
            async def _handler(curr_active_val, curr_chats_val, curr_chat_pid, curr_plot_data, curr_explored_id):
                return await handle_panel_action(p_id, action_type_str, curr_active_val, curr_chats_val, curr_chat_pid, curr_plot_data, curr_explored_id)
            return _handler

        for config_item in PLOT_CONFIGS:
            plot_id = config_item["id"]
            if plot_id in _plot_ui_objects:
                ui_obj = _plot_ui_objects[plot_id]
                # The outputs list for these handlers needs to include the state variables as well.
                # The handlers themselves return updates for states.
                # Gradio's .click() outputs should be components + states.
                
                # Corrected output lists for action/explore handlers to include states
                # These are the components that receive updates, PLUS the state objects themselves.
                # The `handle_panel_action` and `handle_explore_click` functions are designed to return a list
                # where the state updates are correctly positioned.

                # Outputs for panel actions (insights/formula)
                panel_action_outputs_plus_states = action_panel_event_outputs[:11] + \
                                               [active_panel_action_state, current_chat_plot_id_st, chat_histories_st, explored_plot_id_state] + \
                                               action_panel_event_outputs[11:]
                
                # Outputs for explore actions
                explore_action_outputs_plus_states = [explored_plot_id_state] + \
                                                 explore_event_outputs[:1] + \
                                                 [active_panel_action_state] + \
                                                 explore_event_outputs[1:]


                if ui_obj.get("bomb_button"):
                    ui_obj["bomb_button"].click(
                        fn=create_panel_action_handler_closure(plot_id, "insights"),
                        inputs=action_click_inputs,
                        outputs=panel_action_outputs_plus_states, # Pass the combined list
                        api_name=f"action_insights_{plot_id}"
                    )
                if ui_obj.get("formula_button"):
                    ui_obj["formula_button"].click(
                        fn=create_panel_action_handler_closure(plot_id, "formula"),
                        inputs=action_click_inputs,
                        outputs=panel_action_outputs_plus_states, # Pass the combined list
                        api_name=f"action_formula_{plot_id}"
                    )
                if ui_obj.get("explore_button"):
                    ui_obj["explore_button"].click(
                        fn=lambda current_explored_val, current_active_panel_val, p_id=plot_id: handle_explore_click(p_id, current_explored_val, current_active_panel_val),
                        inputs=explore_click_inputs,
                        outputs=explore_action_outputs_plus_states, # Pass the combined list
                        api_name=f"action_explore_{plot_id}"
                    )
            else:
                logger.warning(f"UI object for plot_id '{plot_id}' not found for click handlers.")

        chat_submission_outputs = [_insights_chatbot_ui, _insights_chat_input_ui, chat_histories_st]
        chat_submission_inputs = [_insights_chat_input_ui, current_chat_plot_id_st, chat_histories_st, plot_data_for_chatbot_st]
        
        _insights_chat_input_ui.submit(
            fn=handle_chat_message_submission,
            inputs=chat_submission_inputs,
            outputs=chat_submission_outputs,
            api_name="submit_chat_message"
        )
        
        suggestion_click_inputs_base = [current_chat_plot_id_st, chat_histories_st, plot_data_for_chatbot_st]
        _insights_suggestion_1_btn.click(
            fn=handle_suggested_question_click,
            inputs=[_insights_suggestion_1_btn] + suggestion_click_inputs_base,
            outputs=chat_submission_outputs, api_name="click_suggestion_1"
        )
        _insights_suggestion_2_btn.click(
            fn=handle_suggested_question_click,
            inputs=[_insights_suggestion_2_btn] + suggestion_click_inputs_base,
            outputs=chat_submission_outputs, api_name="click_suggestion_2"
        )
        _insights_suggestion_3_btn.click(
            fn=handle_suggested_question_click,
            inputs=[_insights_suggestion_3_btn] + suggestion_click_inputs_base,
            outputs=chat_submission_outputs, api_name="click_suggestion_3"
        )

        # This button's event is handled by app.py's .then chain calling handle_refresh_analytics_graphs
        # So, build_and_wire_tab needs to return this button and the list of components its handler updates.
        # The handle_refresh_analytics_graphs is now part of this module.
        # So, apply_filter_btn.click can be wired here directly.

        # The output list for handle_refresh_analytics_graphs needs to include states as well.
        refresh_outputs_plus_states = components_for_refresh_outputs[:1+len(PLOT_CONFIGS)+9] + \
                                      [active_panel_action_state, current_chat_plot_id_st, chat_histories_st, plot_data_for_chatbot_st] + \
                                      components_for_refresh_outputs[1+len(PLOT_CONFIGS)+9 : 1+len(PLOT_CONFIGS)+9 + 4*len(PLOT_CONFIGS)] + \
                                      [explored_plot_id_state] + \
                                      components_for_refresh_outputs[1+len(PLOT_CONFIGS)+9 + 4*len(PLOT_CONFIGS):]


        apply_filter_btn.click(
            fn=handle_refresh_analytics_graphs,
            inputs=[token_state, _date_filter_selector, _custom_start_date_picker, _custom_end_date_picker, chat_histories_st],
            outputs=refresh_outputs_plus_states, # Use the constructed list
            show_progress="full"
        )

    # Return components that app.py might need for .then() chains or direct interaction.
    # For now, app.py mainly needs the list of components that handle_refresh_analytics_graphs updates,
    # if that handler is called from app.py. Since it's now wired internally, this might be simpler.
    return (apply_filter_btn, _date_filter_selector, _custom_start_date_picker, _custom_end_date_picker, 
            _analytics_status_md, # For initial load
            components_for_refresh_outputs, # The full list of components for refresh
            refresh_outputs_plus_states # The list including states for refresh
           )