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
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
import datetime
from typing import Dict, List, Any, Union, Optional
import random
import gradio as gr
import json
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict

# Import utilities
from utils.storage import load_data, save_data, safe_get
from utils.state import generate_id, get_timestamp, record_activity
from utils.ai_models import generate_daily_plan, generate_motivational_quote
from utils.ui_components import create_progress_ring, create_deadline_item, create_card, create_stat_card

# Import new modules
from utils.config import FILE_PATHS
from utils.logging import setup_logger
from utils.error_handling import handle_exceptions

# Initialize logger
logger = setup_logger(__name__)

# SMART Goals criteria
SMART_CRITERIA = {
    "Specific": "Is your goal clearly defined and specific?",
    "Measurable": "Can you measure progress and know when it's achieved?",
    "Achievable": "Is this goal realistic and attainable?",
    "Relevant": "Does this goal align with your values and priorities?",
    "Time-bound": "Does your goal have a clear deadline?"
}

# Achievement badges
ACHIEVEMENT_BADGES = {
    "first_goal": {"name": "Goal Setter", "icon": "🎯", "description": "Created your first goal"},
    "goal_achiever": {"name": "Achiever", "icon": "πŸ†", "description": "Completed your first goal"},
    "streak_master": {"name": "Streak Master", "icon": "πŸ”₯", "description": "Maintained a 7-day habit streak"},
    "planner": {"name": "Master Planner", "icon": "πŸ“‹", "description": "Created 5 weekly plans"},
    "reflector": {"name": "Reflective Mind", "icon": "πŸ€”", "description": "Completed 10 weekly reflections"},
    "milestone_master": {"name": "Milestone Master", "icon": "πŸš€", "description": "Achieved 5 milestones"},
    "habit_builder": {"name": "Habit Builder", "icon": "⚑", "description": "Created 10 habits"},
    "analytics_pro": {"name": "Analytics Pro", "icon": "πŸ“Š", "description": "Viewed analytics 20 times"}
}

@handle_exceptions
def initialize_goals_data(state: Dict[str, Any]) -> None:
    """Initialize goals-related data structures"""
    if "goals" not in state:
        state["goals"] = []
    if "habits" not in state:
        state["habits"] = []
    if "milestones" not in state:
        state["milestones"] = []
    if "weekly_plans" not in state:
        state["weekly_plans"] = []
    if "monthly_plans" not in state:
        state["monthly_plans"] = []
    if "reflections" not in state:
        state["reflections"] = []
    if "achievements" not in state:
        state["achievements"] = []
    if "goal_analytics" not in state:
        state["goal_analytics"] = {"views": 0, "goals_created": 0, "goals_completed": 0}

@handle_exceptions
def create_smart_goal_form() -> tuple:
    """Create SMART goal creation form"""
    with gr.Group() as smart_form:
        gr.Markdown("### 🎯 Create SMART Goal")
        
        goal_title = gr.Textbox(label="Goal Title", placeholder="Enter a clear, specific goal title")
        goal_description = gr.Textbox(label="Description", lines=3, placeholder="Describe your goal in detail")
        
        # SMART criteria checklist
        gr.Markdown("#### SMART Criteria Check")
        smart_checks = {}
        for criterion, question in SMART_CRITERIA.items():
            smart_checks[criterion] = gr.Checkbox(label=f"{criterion}: {question}")
        
        # Goal details
        with gr.Row():
            goal_category = gr.Dropdown(
                choices=["Personal", "Professional", "Health", "Learning", "Financial", "Relationships", "Other"],
                label="Category",
                value="Personal"
            )
            goal_priority = gr.Dropdown(
                choices=["High", "Medium", "Low"],
                label="Priority",
                value="Medium"
            )
        
        with gr.Row():
            start_date = gr.Textbox(
                label="Start Date",
                value=datetime.datetime.now().strftime("%Y-%m-%d")
            )
            target_date = gr.Textbox(
                label="Target Date",
                placeholder="YYYY-MM-DD"
            )
        
        # Milestones
        gr.Markdown("#### Milestones")
        milestone_input = gr.Textbox(
            label="Add Milestone",
            placeholder="Enter milestone description"
        )
        milestones_list = gr.Textbox(
            label="Milestones",
            lines=3,
            placeholder="Milestones will appear here...",
            interactive=False
        )
        add_milestone_btn = gr.Button("Add Milestone", size="sm")
        
        # Success metrics
        success_metrics = gr.Textbox(
            label="Success Metrics",
            lines=2,
            placeholder="How will you measure success?"
        )
        
        create_goal_btn = gr.Button("Create SMART Goal", variant="primary")
    
    return (smart_form, goal_title, goal_description, smart_checks, goal_category, 
            goal_priority, start_date, target_date, milestone_input, milestones_list, 
            add_milestone_btn, success_metrics, create_goal_btn)

@handle_exceptions
def create_habit_tracker() -> tuple:
    """Create habit tracking interface"""
    with gr.Group() as habit_tracker:
        gr.Markdown("### πŸ”„ Habit Tracker")
        
        # Add new habit
        with gr.Row():
            habit_name = gr.Textbox(label="Habit Name", placeholder="e.g., Drink 8 glasses of water")
            habit_frequency = gr.Dropdown(
                choices=["Daily", "Weekly", "Monthly"],
                label="Frequency",
                value="Daily"
            )
            habit_target = gr.Number(label="Target (days)", value=21, minimum=1)
        
        add_habit_btn = gr.Button("Add Habit", variant="primary")
        
        # Habits list with streak tracking
        habits_display = gr.Dataframe(
            headers=["Habit", "Current Streak", "Best Streak", "Target", "Progress %", "Actions"],
            datatype=["str", "number", "number", "number", "number", "str"],
            label="Your Habits"
        )
        
        # Habit calendar view
        gr.Markdown("#### Habit Calendar")
        habit_calendar = gr.HTML("<div id='habit-calendar'>Calendar will load here</div>")
        
        # Quick habit check-in
        gr.Markdown("#### Quick Check-in")
        with gr.Row():
            checkin_habit = gr.Dropdown(label="Select Habit", choices=[])
            checkin_btn = gr.Button("Mark Complete", variant="secondary")
    
    return (habit_tracker, habit_name, habit_frequency, habit_target, add_habit_btn,
            habits_display, habit_calendar, checkin_habit, checkin_btn)

@handle_exceptions
def create_planning_tools() -> tuple:
    """Create planning and scheduling tools"""
    with gr.Group() as planning_tools:
        gr.Markdown("### πŸ“… Planning & Time Blocking")
        
        with gr.Tabs():
            # Daily Planning
            with gr.TabItem("Daily Planning"):
                plan_date = gr.Textbox(
                    label="Date",
                    value=datetime.datetime.now().strftime("%Y-%m-%d")
                )
                
                # AI-generated suggestions
                gr.Markdown("#### πŸ€– AI Suggestions")
                ai_suggestions = gr.Markdown("*Click 'Generate Suggestions' for AI-powered daily plan*")
                generate_suggestions_btn = gr.Button("Generate Suggestions")
                
                # Time blocking
                gr.Markdown("#### ⏰ Time Blocks")
                with gr.Row():
                    block_time = gr.Textbox(label="Time", placeholder="09:00-10:00")
                    block_activity = gr.Textbox(label="Activity", placeholder="Deep work on project X")
                    block_priority = gr.Dropdown(
                        choices=["High", "Medium", "Low"],
                        label="Priority",
                        value="Medium"
                    )
                add_block_btn = gr.Button("Add Time Block")
                
                time_blocks_display = gr.Dataframe(
                    headers=["Time", "Activity", "Priority", "Status"],
                    datatype=["str", "str", "str", "str"],
                    label="Today's Schedule"
                )
            
            # Weekly Planning
            with gr.TabItem("Weekly Planning"):
                week_start = gr.Textbox(
                    label="Week Starting",
                    value=datetime.datetime.now().strftime("%Y-%m-%d")
                )
                
                weekly_focus = gr.Textbox(
                    label="Weekly Focus Areas",
                    lines=3,
                    placeholder="What are your main priorities this week?"
                )
                
                weekly_goals_checklist = gr.CheckboxGroup(
                    label="Weekly Goals",
                    choices=[]
                )
                
                save_weekly_plan_btn = gr.Button("Save Weekly Plan")
            
            # Monthly Planning
            with gr.TabItem("Monthly Planning"):
                month_year = gr.Textbox(
                    label="Month/Year",
                    value=datetime.datetime.now().strftime("%B %Y")
                )
                
                monthly_theme = gr.Textbox(
                    label="Monthly Theme",
                    placeholder="What's the main theme for this month?"
                )
                
                monthly_objectives = gr.Textbox(
                    label="Key Objectives",
                    lines=5,
                    placeholder="List your main objectives for the month"
                )
                
                save_monthly_plan_btn = gr.Button("Save Monthly Plan")
    
    return (planning_tools, plan_date, ai_suggestions, generate_suggestions_btn,
            block_time, block_activity, block_priority, add_block_btn, time_blocks_display,
            week_start, weekly_focus, weekly_goals_checklist, save_weekly_plan_btn,
            month_year, monthly_theme, monthly_objectives, save_monthly_plan_btn)

@handle_exceptions
def create_reflection_journal() -> tuple:
    """Create reflection and review system"""
    with gr.Group() as reflection_journal:
        gr.Markdown("### πŸ€” Reflection Journal")
        
        with gr.Tabs():
            # Weekly Reflection
            with gr.TabItem("Weekly Reflection"):
                reflection_week = gr.Textbox(
                    label="Week of",
                    value=datetime.datetime.now().strftime("%Y-%m-%d")
                )
                
                # Reflection prompts
                gr.Markdown("#### Reflection Prompts")
                
                wins = gr.Textbox(
                    label="πŸ† What were your biggest wins this week?",
                    lines=3
                )
                
                challenges = gr.Textbox(
                    label="⚠️ What challenges did you face?",
                    lines=3
                )
                
                lessons = gr.Textbox(
                    label="πŸ“š What did you learn?",
                    lines=3
                )
                
                improvements = gr.Textbox(
                    label="πŸ”„ What would you do differently?",
                    lines=3
                )
                
                next_week_focus = gr.Textbox(
                    label="🎯 What will you focus on next week?",
                    lines=3
                )
                
                gratitude = gr.Textbox(
                    label="πŸ™ What are you grateful for?",
                    lines=2
                )
                
                save_reflection_btn = gr.Button("Save Reflection", variant="primary")
            
            # Monthly Review
            with gr.TabItem("Monthly Review"):
                review_month = gr.Textbox(
                    label="Month/Year",
                    value=datetime.datetime.now().strftime("%B %Y")
                )
                
                monthly_achievements = gr.Textbox(
                    label="πŸ† Major Achievements",
                    lines=4
                )
                
                goals_progress = gr.Textbox(
                    label="πŸ“ˆ Goals Progress Review",
                    lines=4
                )
                
                habits_review = gr.Textbox(
                    label="πŸ”„ Habits Review",
                    lines=3
                )
                
                next_month_goals = gr.Textbox(
                    label="🎯 Next Month's Goals",
                    lines=4
                )
                
                save_monthly_review_btn = gr.Button("Save Monthly Review", variant="primary")
        
        # Past reflections
        gr.Markdown("#### Past Reflections")
        reflections_history = gr.Dataframe(
            headers=["Date", "Type", "Key Insights"],
            datatype=["str", "str", "str"],
            label="Reflection History"
        )
    
    return (reflection_journal, reflection_week, wins, challenges, lessons, improvements,
            next_week_focus, gratitude, save_reflection_btn, review_month, monthly_achievements,
            goals_progress, habits_review, next_month_goals, save_monthly_review_btn,
            reflections_history)

@handle_exceptions
def create_achievement_system() -> tuple:
    """Create achievement badges and gamification"""
    with gr.Group() as achievement_system:
        gr.Markdown("### πŸ† Achievements & Badges")
        
        # Achievement overview
        achievement_stats = gr.HTML("""
        <div class="achievement-stats">
            <div class="stat-item">
                <span class="stat-number">0</span>
                <span class="stat-label">Badges Earned</span>
            </div>
            <div class="stat-item">
                <span class="stat-number">0</span>
                <span class="stat-label">Goals Completed</span>
            </div>
            <div class="stat-item">
                <span class="stat-number">0</span>
                <span class="stat-label">Streak Days</span>
            </div>
        </div>
        """)
        
        # Badges grid
        badges_display = gr.HTML("<div id='badges-grid'>Badges will load here</div>")
        
        # Progress towards next badge
        gr.Markdown("#### Next Badge Progress")
        next_badge_progress = gr.HTML("<div id='next-badge'>Progress will load here</div>")
    
    return achievement_system, achievement_stats, badges_display, next_badge_progress

@handle_exceptions
def create_goal_analytics() -> tuple:
    """Create analytics and insights dashboard"""
    with gr.Group() as analytics_dashboard:
        gr.Markdown("### πŸ“Š Goal Analytics & Insights")
        
        with gr.Tabs():
            # Progress Charts
            with gr.TabItem("Progress Charts"):
                # Goal completion rate
                completion_chart = gr.Plot(label="Goal Completion Rate")
                
                # Habit consistency
                habit_chart = gr.Plot(label="Habit Consistency")
                
                # Category breakdown
                category_chart = gr.Plot(label="Goals by Category")
            
            # Success Patterns
            with gr.TabItem("Success Patterns"):
                success_insights = gr.Markdown("*Analytics will appear here*")
                
                # Best performing categories
                performance_analysis = gr.Dataframe(
                    headers=["Category", "Success Rate", "Avg. Completion Time", "Insights"],
                    datatype=["str", "str", "str", "str"],
                    label="Performance Analysis"
                )
            
            # Time Analysis
            with gr.TabItem("Time Analysis"):
                time_insights = gr.Plot(label="Goal Completion Timeline")
                
                productivity_patterns = gr.Markdown("*Productivity patterns will appear here*")
        
        # AI Insights
        gr.Markdown("#### πŸ€– AI-Powered Insights")
        ai_insights = gr.Markdown("*AI insights will be generated based on your data*")
        generate_insights_btn = gr.Button("Generate AI Insights")
    
    return (analytics_dashboard, completion_chart, habit_chart, category_chart,
            success_insights, performance_analysis, time_insights, productivity_patterns,
            ai_insights, generate_insights_btn)

@handle_exceptions
def create_goals_page(state: Dict[str, Any]) -> None:
    """
    Create the comprehensive goals and planning page
    
    Args:
        state: Application state
    """
    logger.info("Creating comprehensive goals page")
    
    # Initialize data
    initialize_goals_data(state)
    
    # Create the goals page layout
    with gr.Column(elem_id="goals-page"):
        gr.Markdown("# 🎯 Goals & Planning System")
        gr.Markdown("*Comprehensive goal management with SMART framework, habit tracking, and AI insights*")
        
        # Quick stats overview
        with gr.Row():
            goals_stats = gr.HTML("""
            <div class="stats-overview">
                <div class="stat-card">
                    <h3>πŸ“ˆ Active Goals</h3>
                    <p class="stat-number">0</p>
                </div>
                <div class="stat-card">
                    <h3>πŸ”₯ Habit Streaks</h3>
                    <p class="stat-number">0</p>
                </div>
                <div class="stat-card">
                    <h3>πŸ† Completed</h3>
                    <p class="stat-number">0</p>
                </div>
                <div class="stat-card">
                    <h3>πŸ“Š Success Rate</h3>
                    <p class="stat-number">0%</p>
                </div>
            </div>
            """)
        
        # Main tabs
        with gr.Tabs(elem_id="goals-main-tabs"):
            # SMART Goals
            with gr.TabItem("🎯 SMART Goals", elem_id="smart-goals-tab"):
                smart_form, goal_title, goal_description, smart_checks, goal_category, goal_priority, start_date, target_date, milestone_input, milestones_list, add_milestone_btn, success_metrics, create_goal_btn = create_smart_goal_form()
                
                # Goals list
                gr.Markdown("### Current Goals")
                goals_display = gr.Dataframe(
                    headers=["Title", "Category", "Priority", "Progress", "Target Date", "Status"],
                    datatype=["str", "str", "str", "str", "str", "str"],
                    label="Your Goals"
                )
            
            # Habit Tracking
            with gr.TabItem("πŸ”„ Habit Tracker", elem_id="habits-tab"):
                habit_tracker, habit_name, habit_frequency, habit_target, add_habit_btn, habits_display, habit_calendar, checkin_habit, checkin_btn = create_habit_tracker()
            
            # Planning & Time Blocking
            with gr.TabItem("πŸ“… Planning", elem_id="planning-tab"):
                planning_tools, plan_date, ai_suggestions, generate_suggestions_btn, block_time, block_activity, block_priority, add_block_btn, time_blocks_display, week_start, weekly_focus, weekly_goals_checklist, save_weekly_plan_btn, month_year, monthly_theme, monthly_objectives, save_monthly_plan_btn = create_planning_tools()
            
            # Reflection Journal
            with gr.TabItem("πŸ€” Reflection", elem_id="reflection-tab"):
                reflection_journal, reflection_week, wins, challenges, lessons, improvements, next_week_focus, gratitude, save_reflection_btn, review_month, monthly_achievements, goals_progress, habits_review, next_month_goals, save_monthly_review_btn, reflections_history = create_reflection_journal()
            
            # Achievements
            with gr.TabItem("πŸ† Achievements", elem_id="achievements-tab"):
                achievement_system, achievement_stats, badges_display, next_badge_progress = create_achievement_system()
            
            # Analytics
            with gr.TabItem("πŸ“Š Analytics", elem_id="analytics-tab"):
                analytics_dashboard, completion_chart, habit_chart, category_chart, success_insights, performance_analysis, time_insights, productivity_patterns, ai_insights, generate_insights_btn = create_goal_analytics()
            
        
        # Event handlers and functionality will be added here
        # This includes all the interactive functions for:
        # - Creating and managing SMART goals
        # - Tracking habits and streaks
        # - Planning and time blocking
        # - Reflection and journaling
        # - Achievement system
        # - Analytics and insights
                       habit_calendar = gr.HTML(

                            "<div class='habit-calendar-placeholder'>Select a habit to view calendar</div>"
                        )
                        
                        # Habit details
                        habit_details = gr.Markdown(
                            "*Select a habit to see details*"
                        )
                        
                        # Check-in button
                        with gr.Row():
                            check_in_btn = gr.Button("βœ… Check In Today")
                            reset_habit_btn = gr.Button("πŸ”„ Reset Habit")
        
        # Goal detail modal (shown when a goal is selected)
        with gr.Group(elem_id="goal-detail-modal", visible=False) as goal_detail_modal:
            gr.Markdown("## Goal Details")
            
            # Goal information
            goal_title_display = gr.Textbox(label="Title", interactive=True)
            goal_description_display = gr.Textbox(label="Description", lines=3, interactive=True)
            goal_status_display = gr.Dropdown(
                choices=["Not Started", "In Progress", "Completed"],
                label="Status",
                interactive=True
            )
            goal_priority_display = gr.Dropdown(
                choices=["High", "Medium", "Low"],
                label="Priority",
                interactive=True
            )
            goal_deadline_display = gr.Textbox(
                label="Deadline (YYYY-MM-DD)",
                interactive=True
            )
            
            # Progress tracking
            goal_progress_display = gr.Slider(
                minimum=0,
                maximum=100,
                value=0,
                step=5,
                label="Progress (%)"
            )
            
            # Goal actions
            with gr.Row():
                save_goal_btn = gr.Button("Save Changes")
                delete_goal_btn = gr.Button("Delete Goal")
                close_detail_btn = gr.Button("Close")
            
            # Related tasks
            with gr.Group():
                gr.Markdown("### Related Tasks")
                related_tasks = gr.Dataframe(
                    headers=["Task", "Status"],
                    datatype=["str", "str"],
                    col_count=(2, "fixed"),
                    row_count=(0, "dynamic"),
                    elem_id="related-tasks-list"
                )
                link_task_btn = gr.Button("Link Task")
        
        # Add goal modal
        with gr.Group(elem_id="add-goal-modal", visible=False) as add_goal_modal:
            gr.Markdown("## Add New Goal")
            
            # Goal information inputs
            new_goal_title = gr.Textbox(label="Title", placeholder="Enter goal title")
            new_goal_description = gr.Textbox(
                label="Description", 
                placeholder="Enter goal description",
                lines=3
            )
            new_goal_status = gr.Dropdown(
                choices=["Not Started", "In Progress", "Completed"],
                label="Status",
                value="Not Started"
            )
            new_goal_priority = gr.Dropdown(
                choices=["High", "Medium", "Low"],
                label="Priority",
                value="Medium"
            )
            new_goal_deadline = gr.Textbox(
                label="Deadline (YYYY-MM-DD)",
                placeholder="YYYY-MM-DD"
            )
            
            # Goal categorization
            with gr.Accordion("Goal Details", open=False):
                gr.Markdown("### 🏷️ Category")
                new_goal_category = gr.Dropdown(
                    choices=["Personal", "Professional", "Health", "Financial", "Learning", "Other"],
                    label="Category",
                    value="Personal"
                )
                
                gr.Markdown("### πŸ“ Measurability")
                new_goal_measurable = gr.Checkbox(
                    label="Is this goal measurable?",
                    value=True
                )
                new_goal_target = gr.Number(
                    label="Target Value",
                    value=100
                )
                new_goal_unit = gr.Textbox(
                    label="Unit",
                    placeholder="e.g., kg, books, hours"
                )
            
            # Goal actions
            with gr.Row():
                create_goal_btn = gr.Button("Create Goal")
                cancel_add_btn = gr.Button("Cancel")
        
        # Function to render goals
        @handle_exceptions
        def render_goals(view):
            """Render goals based on the selected view"""
            logger.debug(f"Rendering goals with view: {view}")
            goals = safe_get(state, "goals", [])
            
            # Filter goals based on view
            if view == "Active Goals":
                filtered_goals = [g for g in goals if g.get("status", "") != "Completed"]
            elif view == "Completed Goals":
                filtered_goals = [g for g in goals if g.get("status", "") == "Completed"]
            else:  # All Goals
                filtered_goals = goals
            
            # Sort goals by priority and deadline
            priority_order = {"High": 0, "Medium": 1, "Low": 2}
            filtered_goals.sort(key=lambda x: (
                priority_order.get(x.get("priority", "Medium"), 1),
                x.get("deadline", "9999-12-31")
            ))
            
            # Create goal cards
            goal_cards = []
            for goal in filtered_goals:
                # Create goal card HTML
                title = safe_get(goal, "title", "Untitled Goal")
                description = safe_get(goal, "description", "")
                status = safe_get(goal, "status", "Not Started")
                priority = safe_get(goal, "priority", "Medium")
                progress = safe_get(goal, "progress", 0)
                
                # Format deadline
                deadline_str = "No deadline"
                if "deadline" in goal:
                    try:
                        deadline = datetime.datetime.fromisoformat(goal["deadline"])
                        deadline_str = deadline.strftime("%b %d, %Y")
                    except:
                        logger.warning(f"Failed to parse deadline for goal: {goal.get('id', 'unknown')}")
                
                # Status emoji
                status_emoji = "πŸ”΄" if status == "Not Started" else \
                              "🟑" if status == "In Progress" else "🟒"
                
                # Priority color
                priority_color = "red" if priority == "High" else \
                                "orange" if priority == "Medium" else "green"
                
                # Create card HTML
                card_html = f"""
                <div class="goal-card priority-{priority.lower()}" data-goal-id="{goal.get('id', '')}">
                    <div class="goal-header">
                        <h3>{title}</h3>
                        <span class="goal-status">{status_emoji} {status}</span>
                    </div>
                    <div class="goal-description">{description}</div>
                    <div class="goal-progress">
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: {progress}%;"></div>
                        </div>
                        <span class="progress-text">{progress}%</span>
                    </div>
                    <div class="goal-footer">
                        <span class="goal-deadline">πŸ“… {deadline_str}</span>
                        <span class="goal-priority" style="color: {priority_color};">⚑ {priority}</span>
                    </div>
                </div>
                """
                
                goal_cards.append(card_html)
            
            # Combine all cards
            if goal_cards:
                return "\n".join(goal_cards)
            else:
                return "<div class='no-goals-message'>No goals found. Click 'βž• Add Goal' to create one.</div>"
        
        # Set up view switching
        view_selector.change(
            render_goals,
            inputs=[view_selector],
            outputs=[goals_container]
        )
        
        # Function to show add goal modal
        @handle_exceptions
        def show_add_goal_modal():
            """Show the add goal modal"""
            logger.debug("Showing add goal modal")
            return gr.update(visible=True)
        
        # Function to hide add goal modal
        @handle_exceptions
        def hide_add_goal_modal():
            """Hide the add goal modal"""
            logger.debug("Hiding add goal modal")
            return gr.update(visible=False)
        
        # Set up add goal modal
        add_goal_btn.click(show_add_goal_modal, inputs=[], outputs=[add_goal_modal])
        cancel_add_btn.click(hide_add_goal_modal, inputs=[], outputs=[add_goal_modal])
        
        # Function to create a new goal
        @handle_exceptions
        def create_goal(title, description, status, priority, deadline, 
                       category, is_measurable, target, unit):
            """Create a new goal"""
            logger.debug("Creating new goal")
            if not title.strip():
                logger.warning("Attempted to create goal without title")
                return "Please enter a goal title", gr.update(visible=True)
            
            # Validate deadline format if provided
            deadline_iso = None
            if deadline.strip():
                try:
                    deadline_date = datetime.datetime.strptime(deadline.strip(), "%Y-%m-%d")
                    deadline_iso = deadline_date.isoformat()
                except ValueError:
                    logger.warning(f"Invalid date format for deadline: {deadline}")
                    return "Invalid date format. Use YYYY-MM-DD", gr.update(visible=True)
            
            # Create new goal
            new_goal = {
                "id": generate_id(),
                "title": title.strip(),
                "description": description.strip(),
                "status": status,
                "priority": priority,
                "progress": 0,
                "category": category,
                "created_at": get_timestamp()
            }
            
            if deadline_iso:
                new_goal["deadline"] = deadline_iso
            
            # Add measurability details if applicable
            if is_measurable:
                new_goal["measurable"] = True
                new_goal["target"] = float(target) if target else 100
                new_goal["current"] = 0
                if unit.strip():
                    new_goal["unit"] = unit.strip()
            
            # Add to state
            if "goals" not in state:
                state["goals"] = []
            state["goals"].append(new_goal)
            
            # Update stats
            if "stats" not in state:
                state["stats"] = {}
            if "goals_total" not in state["stats"]:
                state["stats"]["goals_total"] = 0
            state["stats"]["goals_total"] += 1
            
            # Record activity
            record_activity(state, {
                "type": "goal_created",
                "title": title,
                "timestamp": get_timestamp()
            })
            
            # Save to file
            save_data(FILE_PATHS["goals"], state["goals"])
            
            # Update goals display
            goals_html = render_goals(view_selector.value)
            
            # Reset form and hide modal
            return "Goal created successfully!", gr.update(visible=False), goals_html
        
        # Set up create goal action
        create_goal_btn.click(
            create_goal,
            inputs=[
                new_goal_title, new_goal_description, new_goal_status,
                new_goal_priority, new_goal_deadline, new_goal_category,
                new_goal_measurable, new_goal_target, new_goal_unit
            ],
            outputs=[gr.Markdown(visible=False), add_goal_modal, goals_container]
        )
        
        # Function to generate a daily plan
        @handle_exceptions
        def generate_plan():
            """Generate a daily plan using AI"""
            logger.debug("Generating daily plan")
            tasks = safe_get(state, "tasks", [])
            goals = safe_get(state, "goals", [])
            
            # Filter active tasks and goals
            active_tasks = [t for t in tasks if t.get("status", "") != "done"]
            active_goals = [g for g in goals if g.get("status", "") != "Completed"]
            
            # Generate plan
            plan = generate_daily_plan(active_tasks, active_goals)
            
            return plan
        
        # Set up generate plan button
        generate_plan_btn.click(
            generate_plan,
            inputs=[],
            outputs=[daily_plan]
        )
        
        # Function to save a manual plan
        @handle_exceptions
        def save_manual_plan(date, plan):
            """Save a manual daily plan"""
            logger.debug(f"Saving manual plan for date: {date}")
            if not plan.strip():
                logger.warning("Attempted to save empty plan")
                return "Please enter a plan"
            
            # Create or update plan
            if "plans" not in state:
                state["plans"] = {}
            
            state["plans"][date] = {
                "content": plan.strip(),
                "created_at": get_timestamp()
            }
            
            # Save to file
            save_data(FILE_PATHS["plans"], state["plans"])
            
            # Record activity
            record_activity(state, {
                "type": "plan_created",
                "title": f"Plan for {date}",
                "timestamp": get_timestamp()
            })
            
            return "Plan saved successfully!"
        
        # Set up save plan button
        save_plan_btn.click(
            save_manual_plan,
            inputs=[plan_date, manual_plan],
            outputs=[gr.Markdown(visible=False)]
        )
        
        # Function to generate a motivational quote
        @handle_exceptions
        def get_motivational_quote():
            """Get a motivational quote using AI"""
            logger.debug("Generating motivational quote")
            quote = generate_motivational_quote()
            return f"*\"{quote}\"*"
        
        # Set up new quote button
        new_quote_btn.click(
            get_motivational_quote,
            inputs=[],
            outputs=[motivation_quote]
        )
        
        # Function to add a habit
        @handle_exceptions
        def add_habit(name, target):
            """Add a new habit to track"""
            logger.debug(f"Adding new habit: {name}")
            if not name.strip():
                logger.warning("Attempted to add habit without name")
                return "Please enter a habit name"
            
            # Create new habit
            new_habit = {
                "id": generate_id(),
                "name": name.strip(),
                "target": int(target),
                "streak": 0,
                "history": {},
                "created_at": get_timestamp()
            }
            
            # Add to state
            if "habits" not in state:
                state["habits"] = []
            state["habits"].append(new_habit)
            
            # Save to file
            save_data(FILE_PATHS["habits"], state["habits"])
            
            # Record activity
            record_activity(state, {
                "type": "habit_created",
                "title": name,
                "timestamp": get_timestamp()
            })
            
            # Update habits list
            habits_data = []
            for habit in safe_get(state, "habits", []):
                habits_data.append([
                    safe_get(habit, "name", "Unnamed Habit"),
                    safe_get(habit, "streak", 0),
                    safe_get(habit, "target", 21)
                ])
            
            return "Habit added successfully!", habits_data
        
        # Set up add habit button
        add_habit_btn.click(
            add_habit,
            inputs=[new_habit_name, new_habit_target],
            outputs=[gr.Markdown(visible=False), habits_list]
        )
        
        # Initialize goals display
        goals_container.value = render_goals("Active Goals")
        
        # Initialize motivation quote
        motivation_quote.value = get_motivational_quote()
        
        # Initialize habits list
        habits_data = []
        for habit in safe_get(state, "habits", []):
            habits_data.append([
                safe_get(habit, "name", "Unnamed Habit"),
                safe_get(habit, "streak", 0),
                safe_get(habit, "target", 21)
            ])
        habits_list.value = habits_data