diff --git "a/agents/flutter_screen_generator.py" "b/agents/flutter_screen_generator.py" new file mode 100644--- /dev/null +++ "b/agents/flutter_screen_generator.py" @@ -0,0 +1,4660 @@ +""" +AC3: Flutter Screen Generator Agent + +Generates Flutter/Dart screen code using AI Planning (Llama 3.1) + Jinja2 templates. +Takes design themes from AC2 and generates runnable Dart code for DartPad. +""" + +import os +import json +from typing import Dict, Any, List +from jinja2 import Environment, FileSystemLoader, select_autoescape +from huggingface_hub import InferenceClient + + +class FlutterScreenGenerator: + """ + Agent that generates Flutter screen code using AI planning and templates + """ + + # BACKGROUND CATALOG - 30 unique variations + BACKGROUND_CATALOG = { + # GRADIENTS (6) + "gradient_linear": {"category": "gradients", "name": "Linear Gradient", "complexity": "simple"}, + "gradient_radial": {"category": "gradients", "name": "Radial Gradient", "complexity": "simple"}, + "gradient_angular": {"category": "gradients", "name": "Angular Gradient", "complexity": "medium"}, + "gradient_sweep": {"category": "gradients", "name": "Sweep Gradient", "complexity": "medium"}, + "gradient_mesh": {"category": "gradients", "name": "Mesh Gradient", "complexity": "complex"}, + "gradient_diagonal": {"category": "gradients", "name": "Diagonal Gradient", "complexity": "simple"}, + + # WAVES (5) + "waves_smooth": {"category": "waves", "name": "Smooth Waves", "complexity": "medium"}, + "waves_sharp": {"category": "waves", "name": "Sharp Waves", "complexity": "medium"}, + "waves_layered": {"category": "waves", "name": "Layered Waves", "complexity": "complex"}, + "waves_curved": {"category": "waves", "name": "Curved Waves", "complexity": "medium"}, + "waves_minimal": {"category": "waves", "name": "Minimal Wave", "complexity": "simple"}, + + # GEOMETRIC (6) + "geometric_circles": {"category": "geometric", "name": "Floating Circles", "complexity": "medium"}, + "geometric_triangles": {"category": "geometric", "name": "Triangle Pattern", "complexity": "medium"}, + "geometric_hexagons": {"category": "geometric", "name": "Hexagon Grid", "complexity": "complex"}, + "geometric_grid": {"category": "geometric", "name": "Dot Grid", "complexity": "simple"}, + "geometric_stripes": {"category": "geometric", "name": "Diagonal Stripes", "complexity": "simple"}, + "geometric_diamonds": {"category": "geometric", "name": "Diamond Shapes", "complexity": "medium"}, + + # ORGANIC (4) + "organic_blobs": {"category": "organic", "name": "Blob Shapes", "complexity": "complex"}, + "organic_fluid": {"category": "organic", "name": "Fluid Effect", "complexity": "complex"}, + "organic_noise": {"category": "organic", "name": "Noise Texture", "complexity": "medium"}, + "organic_clouds": {"category": "organic", "name": "Cloud Shapes", "complexity": "medium"}, + + # PATTERNS (4) + "pattern_dots": {"category": "patterns", "name": "Dot Pattern", "complexity": "simple"}, + "pattern_lines": {"category": "patterns", "name": "Line Pattern", "complexity": "simple"}, + "pattern_chevron": {"category": "patterns", "name": "Chevron Pattern", "complexity": "medium"}, + "pattern_zigzag": {"category": "patterns", "name": "Zigzag Pattern", "complexity": "medium"}, + + # ABSTRACT (5) + "abstract_crystalline": {"category": "abstract", "name": "Crystalline", "complexity": "complex"}, + "abstract_voronoi": {"category": "abstract", "name": "Voronoi Diagram", "complexity": "complex"}, + "abstract_particles": {"category": "abstract", "name": "Particle Field", "complexity": "medium"}, + "abstract_rays": {"category": "abstract", "name": "Light Rays", "complexity": "medium"}, + "abstract_constellation": {"category": "abstract", "name": "Star Constellation", "complexity": "medium"}, + } + + def __init__(self): + self.name = "flutter_screen_generator" + self.description = "Generates Flutter/Dart screen code for DartPad" + + # HuggingFace Inference API + self.hf_token = os.getenv("HF_TOKEN", "") + # Explicitly use HF provider (not third-party like Hyperbolic) + self.client = InferenceClient(token=self.hf_token, provider="hf-inference") + self.model = "meta-llama/Meta-Llama-3.1-70B-Instruct" + + # Jinja2 setup with custom delimiters (to avoid conflict with Dart ${}) + template_dir = os.path.join(os.path.dirname(__file__), '..', 'templates', 'dart') + self.jinja_env = Environment( + loader=FileSystemLoader(template_dir) if os.path.exists(template_dir) else FileSystemLoader('.'), + autoescape=select_autoescape(), + variable_start_string='<{', + variable_end_string='}>', + block_start_string='<{%', + block_end_string='%}>', + comment_start_string='<{#', + comment_end_string='#}>', + trim_blocks=True, + lstrip_blocks=True, + ) + + def process(self, input_data: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate Flutter screen code from design theme + + Args: + input_data: { + "theme": {...}, # Complete theme from AC2 + "app_type": "fitness|banking|rider|ecommerce|social", + "screens": ["home", "detail", "profile"] + } + + Returns: + { + "screens": [ + { + "name": "home", + "code": "...", # Complete Dart code + "lines": 450, + "components": ["StatsCard", "FeatureGrid"] + } + ] + } + """ + + try: + theme = input_data.get("theme", {}) + app_type = input_data.get("app_type", "generic") + screen_types = input_data.get("screens", ["home"]) + + # GENERA SOLO 1 SCHERMATA (sempre home) + screen_type = "home" + + try: + # Step 1: AI generates 4 intelligent variants based on theme + app_type + print(f"πŸ€– AI generating 4 intelligent variants for {app_type}...") + + if self.hf_token: + variants = self._generate_variants_with_ai(theme, app_type) + else: + print("⚠️ No HF_TOKEN - using fallback variants") + variants = self._get_fallback_variants(app_type) + + # Step 2: Generate Dart code for each variant + screens = [] + for i, variant in enumerate(variants): + print(f" 🎨 Generating variant {i+1}: {variant['name']}") + + dart_code = self._generate_complete_screen( + theme=theme, + app_type=app_type, + variant=variant + ) + + screens.append({ + "name": variant["name"], + "description": variant.get("description", ""), + "code": dart_code, + "lines": len(dart_code.split('\n')), + "bg_style": variant["background"], + "header_type": variant["header"], + "footer_type": variant["footer"], + "reasoning": variant.get("reasoning", ""), + "status": "generated" + }) + + print(f" βœ… Generated: {variant['name']}") + + except Exception as e: + print(f"❌ Error generating screen: {e}") + import traceback + traceback.print_exc() + + # Fallback + screens = [{ + "name": screen_type, + "code": self._generate_simple_fallback(theme, screen_type), + "lines": 200, + "components": [], + "status": "error" + }] + + return { + "screens": screens, + "theme_name": theme.get("name", "Unknown"), + "app_type": app_type, + "total_lines": sum(s.get("lines", 0) for s in screens) + } + + except Exception as e: + print(f"❌ Critical error in process(): {e}") + import traceback + traceback.print_exc() + + # Even on critical error, try to generate at least one fallback screen + try: + theme = input_data.get("theme", {}) + app_type = input_data.get("app_type", "generic") + screens = input_data.get("screens", ["home"]) + + fallback_screens = [{ + "name": screens[0] if screens else "home", + "code": self._generate_simple_fallback(theme, screens[0] if screens else "home"), + "lines": 200, + "components": [], + "status": "critical_error_fallback" + }] + + return { + "screens": fallback_screens, + "error": str(e), + "theme_name": theme.get("name", "Error"), + "app_type": app_type, + "total_lines": 200 + } + except: + # Last resort - return minimal structure + return { + "screens": [], + "error": f"Critical error: {str(e)}", + "theme_name": "Error", + "app_type": "unknown", + "total_lines": 0 + } + + def _generate_plan(self, theme: Dict[str, Any], app_type: str, screen_type: str) -> Dict[str, Any]: + """ + Use Llama 3.1 70B to generate architectural plan for the screen + + Returns JSON plan with sections, components, and layout decisions + """ + + prompt = self._build_planning_prompt(theme, app_type, screen_type) + + try: + # Call Llama 3.1 70B via HuggingFace Inference API + generated_text = self.client.text_generation( + prompt=prompt, + model=self.model, + max_new_tokens=1000, + temperature=0.7, + top_p=0.9, + ) + + # Extract JSON from response + return self._extract_json_from_text(generated_text) + + except Exception as e: + print(f"AI Planning error: {e}") + return None + + def _build_planning_prompt(self, theme: Dict[str, Any], app_type: str, screen_type: str) -> str: + """Build prompt for Llama 3.1 to generate screen plan""" + + theme_summary = { + "name": theme.get("name", ""), + "style": theme.get("style", ""), + "primary_color": theme.get("palette", {}).get("primary", "#007AFF"), + "typography": theme.get("typography", {}).get("display", {}).get("font_family", "System") + } + + prompt = f"""You are an expert Flutter UI architect. Create a detailed plan for generating a {screen_type} screen for a {app_type} mobile app. + +Theme Information: +- Name: {theme_summary['name']} +- Style: {theme_summary['style']} +- Primary Color: {theme_summary['primary_color']} +- Font: {theme_summary['typography']} + +Task: Generate a JSON plan with appropriate components and layout for this screen. + +Requirements: +1. Components must be relevant to {app_type} apps +2. Layout should match the {theme_summary['style']} style +3. Use Flutter Material 3 widgets +4. Include mock data structure + +Output ONLY valid JSON in this format: +{{ + "screen_type": "{screen_type}", + "layout": "column_scroll", + "sections": [ + {{ + "type": "appbar", + "component": "AppBar", + "params": {{"title": "...", "style": "..."}} + }}, + {{ + "type": "hero", + "component": "HeroBanner", + "params": {{"height": 200, "background": "gradient"}} + }} + ], + "components": ["StatsCard", "FeatureGrid"], + "mock_data": {{ + "user_name": "Marco Rossi", + "stats": {{"value1": 100, "value2": 200}} + }} +}} + +JSON Plan:""" + + return prompt + + def _generate_variants_with_ai(self, theme: Dict[str, Any], app_type: str) -> list: + """ + Use Llama 3.1 70B to generate 4 intelligent UI variants + Each variant combines background + header + footer appropriately + """ + + theme_summary = { + "name": theme.get("name", ""), + "style": theme.get("style", ""), + "primary": theme.get("palette", {}).get("primary", "#007AFF"), + "secondary": theme.get("palette", {}).get("secondary", "#5856D6") + } + + # Get all background names for AI + bg_list = "\n".join([f"- {bg_id} ({info['name']}, {info['complexity']})" for bg_id, info in self.BACKGROUND_CATALOG.items()]) + + prompt = f"""You are a UX/UI expert. Generate 4 different screen layout variants for a {app_type} mobile app. + +THEME INFO: +- Name: {theme_summary['name']} +- Style: {theme_summary['style']} +- Primary Color: {theme_summary['primary']} +- Secondary Color: {theme_summary['secondary']} + +AVAILABLE COMPONENTS: + +BACKGROUNDS (30 options): +{bg_list} + +HEADERS: +- minimal (title only, clean) +- avatar_search (avatar + search bar, social) +- tabs (horizontal tabs, navigation) +- collapsible (expandable on scroll, dynamic) +- stats_header (shows key metrics, data-focused) + +FOOTERS: +- minimal_icons (icons only, no labels) +- floating_fab (center FAB button, action-focused) +- animated_pills (smooth animations, premium) +- classic_expanded (icons + labels, traditional) +- gesture_bar (iOS-style swipe, minimal) + +Generate 4 DIFFERENT variants, each optimized for different use cases. +Consider theme style + app type to make smart combinations. + +IMPORTANT RULES: +1. Use a DIFFERENT background for each variant (choose from 30 options above) +2. Vary the complexity: mix simple, medium, and complex backgrounds +3. Match background category to use case (gradients=clean, waves=dynamic, geometric=modern, organic=creative, patterns=structured, abstract=premium) +4. **PERSONALIZE TEXT** content based on app_type (e.g., fitness="Workout Tracker", banking="Account Overview") + +Output ONLY valid JSON: +{{ + "variants": [ + {{ + "name": "Variant Name", + "description": "Short description", + "background": "waves_smooth", + "header": "stats_header", + "footer": "floating_fab", + "texts": {{ + "header_title": "Personalized title for {app_type}", + "header_subtitle": "Optional subtitle", + "footer_labels": ["Label1", "Label2", "Label3", "Label4", "Label5"] + }}, + "reasoning": "Why this combination works" + }}, + {{ + "name": "Another Variant", + "description": "Different approach", + "background": "gradient_mesh", + "header": "minimal", + "footer": "animated_pills", + "texts": {{ + "header_title": "Different title for {app_type}", + "header_subtitle": "Different subtitle", + "footer_labels": ["Home", "Explore", "Settings", "Profile", "More"] + }}, + "reasoning": "Different background and components" + }}, + ...2 more variants with DIFFERENT backgrounds and personalized texts + ] +}} + +JSON:""" + + try: + generated_text = self.client.text_generation( + prompt=prompt, + model=self.model, + max_new_tokens=800, + temperature=0.8, + top_p=0.9, + ) + + result = self._extract_json_from_text(generated_text) + if result and "variants" in result: + variants = result["variants"][:4] # Max 4 + print(f"βœ… AI generated {len(variants)} variants") + return variants + else: + print("⚠️ AI response invalid, using fallback") + return self._get_fallback_variants(app_type) + + except Exception as e: + print(f"❌ AI variant generation error: {e}") + return self._get_fallback_variants(app_type) + + def _get_fallback_variants(self, app_type: str) -> list: + """ + Fallback variants if AI fails or no HF_TOKEN + Pre-configured smart combinations per app type + """ + + fallback_map = { + "fitness": [ + { + "name": "High Energy Action", + "description": "Dynamic design for active users", + "background": "waves_smooth", + "header": "stats_header", + "footer": "floating_fab", + "texts": { + "header_title": "Workout Tracker", + "header_subtitle": "Today's Progress", + "footer_labels": ["Train", "Stats", "Goals", "Profile", "More"] + }, + "reasoning": "Movement + always-visible stats + quick action" + }, + { + "name": "Focus Mode", + "description": "Minimal UI during workout", + "background": "gradient_linear", + "header": "minimal", + "footer": "gesture_bar", + "texts": { + "header_title": "Active Session", + "header_subtitle": "", + "footer_labels": ["Home", "Activity", "Settings", "Profile", "Menu"] + }, + "reasoning": "Clean gradient + minimal distractions" + }, + { + "name": "Progress Dashboard", + "description": "Data-focused tracking", + "background": "geometric_circles", + "header": "tabs", + "footer": "animated_pills", + "texts": { + "header_title": "Fitness Hub", + "header_subtitle": "Your Weekly Goals", + "footer_labels": ["Workouts", "Nutrition", "Progress", "Social", "More"] + }, + "reasoning": "Geometric patterns + category navigation" + }, + { + "name": "Gamified Tracker", + "description": "Playful achievement system", + "background": "abstract_particles", + "header": "avatar_search", + "footer": "classic_expanded", + "texts": { + "header_title": "Level Up", + "header_subtitle": "Achievements & Rewards", + "footer_labels": ["Challenges", "Leaderboard", "Rewards", "Friends", "Profile"] + }, + "reasoning": "Particle effects = gamification + social features" + } + ], + "banking": [ + { + "name": "Trust & Security", + "description": "Professional and secure", + "background": "gradient_radial", + "header": "minimal", + "footer": "minimal_icons", + "texts": { + "header_title": "My Accounts", + "header_subtitle": "Secure Banking", + "footer_labels": ["Home", "Payments", "Cards", "Account", "More"] + }, + "reasoning": "Focus + trust + minimal distractions" + }, + { + "name": "Financial Overview", + "description": "Organized account management", + "background": "gradient_linear", + "header": "tabs", + "footer": "classic_expanded", + "texts": { + "header_title": "Financial Hub", + "header_subtitle": "Account Overview", + "footer_labels": ["Accounts", "Transfers", "Invest", "Budget", "Settings"] + }, + "reasoning": "Clean + category tabs + clear navigation" + }, + { + "name": "Premium Banking", + "description": "Elegant wealth management", + "background": "waves_minimal", + "header": "collapsible", + "footer": "animated_pills", + "texts": { + "header_title": "Wealth Manager", + "header_subtitle": "Premium Services", + "footer_labels": ["Portfolio", "Insights", "Advisory", "Profile", "Support"] + }, + "reasoning": "Subtle motion + premium animations" + }, + { + "name": "Modern Finance", + "description": "Contemporary digital banking", + "background": "pattern_lines", + "header": "avatar_search", + "footer": "gesture_bar", + "texts": { + "header_title": "Smart Banking", + "header_subtitle": "Quick Actions", + "footer_labels": ["Dashboard", "Pay", "Save", "Rewards", "Menu"] + }, + "reasoning": "Modern patterns + search + gestures" + } + ], + "rider": [ + { + "name": "Active Delivery", + "description": "On-the-go delivery tracking", + "background": "waves_sharp", + "header": "stats_header", + "footer": "floating_fab", + "texts": { + "header_title": "On Delivery", + "header_subtitle": "Today's Earnings", + "footer_labels": ["Orders", "Map", "Earnings", "Profile", "Help"] + }, + "reasoning": "Movement + earnings visible + quick accept" + }, + { + "name": "Map Focus", + "description": "Navigation-first design", + "background": "gradient_diagonal", + "header": "collapsible", + "footer": "minimal_icons", + "texts": { + "header_title": "Navigate", + "header_subtitle": "Active Route", + "footer_labels": ["Home", "Orders", "Map", "Stats", "Menu"] + }, + "reasoning": "Clean map view + collapsing header" + }, + { + "name": "Earnings Dashboard", + "description": "Income tracking focus", + "background": "abstract_crystalline", + "header": "tabs", + "footer": "classic_expanded", + "texts": { + "header_title": "Rider Hub", + "header_subtitle": "Weekly Performance", + "footer_labels": ["Dashboard", "Deliveries", "Income", "Rankings", "Settings"] + }, + "reasoning": "Spotlight on earnings + clear navigation" + }, + { + "name": "Social Rider", + "description": "Community and rankings", + "background": "geometric_stripes", + "header": "avatar_search", + "footer": "animated_pills", + "texts": { + "header_title": "Rider Community", + "header_subtitle": "Leaderboard & Friends", + "footer_labels": ["Feed", "Challenges", "Leaderboard", "Friends", "Profile"] + }, + "reasoning": "Playful + social features + leaderboard" + } + ], + "ecommerce": [ + { + "name": "Product Showcase", + "description": "Visual product gallery", + "background": "gradient_mesh", + "header": "avatar_search", + "footer": "floating_fab", + "texts": { + "header_title": "Shop", + "header_subtitle": "Discover Products", + "footer_labels": ["Home", "Categories", "Cart", "Orders", "Account"] + }, + "reasoning": "Rich visuals + search + quick cart access" + }, + { + "name": "Clean Shopping", + "description": "Minimal product browsing", + "background": "pattern_dots", + "header": "minimal", + "footer": "classic_expanded", + "texts": { + "header_title": "Store", + "header_subtitle": "Featured Collection", + "footer_labels": ["Browse", "Search", "Favorites", "Cart", "Profile"] + }, + "reasoning": "Clean focus on products + clear navigation" + }, + { + "name": "Premium Store", + "description": "Luxury shopping experience", + "background": "abstract_rays", + "header": "collapsible", + "footer": "animated_pills", + "texts": { + "header_title": "Luxury Collection", + "header_subtitle": "Exclusive Items", + "footer_labels": ["Collections", "New Arrivals", "Wishlist", "VIP", "Profile"] + }, + "reasoning": "Premium feel + smooth animations" + }, + { + "name": "Dynamic Deals", + "description": "Engaging promotions", + "background": "waves_curved", + "header": "tabs", + "footer": "gesture_bar", + "texts": { + "header_title": "Flash Deals", + "header_subtitle": "Limited Time Offers", + "footer_labels": ["Deals", "Shop", "Cart", "Orders", "More"] + }, + "reasoning": "Movement + category tabs + gestures" + } + ], + "social": [ + { + "name": "Community Feed", + "description": "Social content stream", + "background": "organic_fluid", + "header": "avatar_search", + "footer": "minimal_icons", + "texts": { + "header_title": "Feed", + "header_subtitle": "What's Happening", + "footer_labels": ["Home", "Explore", "Notifications", "Messages", "Profile"] + }, + "reasoning": "Organic flow + search + simple navigation" + }, + { + "name": "Stories Focus", + "description": "Ephemeral content first", + "background": "gradient_sweep", + "header": "minimal", + "footer": "gesture_bar", + "texts": { + "header_title": "Stories", + "header_subtitle": "24h Updates", + "footer_labels": ["Feed", "Stories", "Reels", "Live", "Menu"] + }, + "reasoning": "Dynamic gradient + minimal UI + gestures" + }, + { + "name": "Creator Platform", + "description": "Content creation tools", + "background": "geometric_hexagons", + "header": "tabs", + "footer": "floating_fab", + "texts": { + "header_title": "Create", + "header_subtitle": "Your Studio", + "footer_labels": ["Studio", "Content", "Analytics", "Community", "Profile"] + }, + "reasoning": "Modern patterns + tools tabs + create button" + }, + { + "name": "Activity Hub", + "description": "Notifications and updates", + "background": "abstract_constellation", + "header": "collapsible", + "footer": "animated_pills", + "texts": { + "header_title": "Activity", + "header_subtitle": "Your Network", + "footer_labels": ["Feed", "Activity", "Friends", "Groups", "More"] + }, + "reasoning": "Connected dots + collapsing header + smooth nav" + } + ] + } + + # Default fallback for unknown app types + default_variants = [ + { + "name": "Clean Minimal", + "background": "gradient_linear", + "header": "minimal", + "footer": "minimal_icons", + "description": "Simple and clean", + "texts": { + "header_title": "Home", + "header_subtitle": "Welcome", + "footer_labels": ["Home", "Explore", "Search", "Settings", "Profile"] + }, + "reasoning": "Minimal approach" + }, + { + "name": "Dynamic Engaging", + "background": "waves_layered", + "header": "avatar_search", + "footer": "floating_fab", + "description": "Active and social", + "texts": { + "header_title": "Dashboard", + "header_subtitle": "Activity", + "footer_labels": ["Dashboard", "Activity", "Favorites", "Profile", "More"] + }, + "reasoning": "Engaging design" + }, + { + "name": "Modern Premium", + "background": "abstract_voronoi", + "header": "tabs", + "footer": "animated_pills", + "description": "Professional look", + "texts": { + "header_title": "Overview", + "header_subtitle": "Premium", + "footer_labels": ["Overview", "Features", "Premium", "Account", "Settings"] + }, + "reasoning": "Premium feel" + }, + { + "name": "Creative Playful", + "background": "organic_blobs", + "header": "collapsible", + "footer": "classic_expanded", + "description": "Fun and creative", + "texts": { + "header_title": "Creative Hub", + "header_subtitle": "Express Yourself", + "footer_labels": ["Create", "Gallery", "Explore", "Community", "Profile"] + }, + "reasoning": "Playful design" + } + ] + + return fallback_map.get(app_type, default_variants) + + def _generate_random_content(self, app_type: str, seed: int) -> Dict[str, Any]: + """ + Generate RANDOM variations of content (no AI needed) + Uses seed for reproducibility during testing + """ + import random + random.seed(seed) + + # Variazioni per ogni app type + variations = { + "rider": { + "greetings": ["Ciao,", "Hey,", "Benvenuto,", "Buongiorno,"], + "subtitles": ["Pronto per consegnare?", "Inizia il tuo turno!", "Nuove consegne disponibili", "Zona attiva oggi"], + "main_card_titles": ["Prossima consegna", "Ordine in arrivo", "Nuova richiesta", "Consegna urgente"], + "main_texts": ["Ritiro pizza margherita", "Pacco da ritirare", "Ordine supermercato", "Consegna express"], + "main_details": ["Cliente Marco - Via Roma 21", "Distanza 2.3 km", "Paga alla consegna", "Consegna entro 15 min"], + "stat_labels": [ + ["Consegne", "Guadagno", "Km percorsi", "Rating"], + ["Ordini", "Incasso", "Tempo attivo", "Stelle"], + ["Corse", "€ oggi", "Ore online", "Feedback"], + ], + "suggestions": [ + ("Zona calda!", "Molte richieste in centro ora"), + ("Orario di punta", "Attiva il turno per guadagnare di piΓΉ"), + ("Percorso ottimale", "Risparmia 5 min unendo 2 consegne"), + ], + "chart_titles": ["Guadagno settimanale", "Consegne per giorno", "Performance settimana", "Andamento €"], + "map_titles": ["Mappa consegne", "Zona di lavoro", "Area attiva", "Percorso oggi"], + "status_sets": [ + ["Online", "Pausa", "Supporto"], + ["Disponibile", "Riposo", "Aiuto"], + ["Attivo", "Offline", "Assistenza"], + ] + }, + "fitness": { + "greetings": ["Ciao,", "Hey,", "Forza,", "Bentornato,"], + "subtitles": ["Pronto ad allenarti?", "Nuovo workout disponibile", "Obiettivo giornaliero", "Inizia ora"], + "main_card_titles": ["Prossimo allenamento", "Workout del giorno", "Sfida attiva", "Sessione consigliata"], + "main_texts": ["HIIT 30 minuti", "Corsa mattutina", "Yoga serale", "Strength training"], + "main_details": ["Brucia 450 cal", "5 km in 30 min", "Relax e stretching", "Upper body focus"], + "stat_labels": [ + ["Calorie", "Passi", "Minuti attivi", "Obiettivo"], + ["kcal bruciate", "Steps", "Workout time", "Target"], + ["Energia", "Distanza", "Allenamenti", "Streak"], + ], + "suggestions": [ + ("Sei vicino!", "Solo 500 passi al tuo obiettivo"), + ("Momento perfetto", "Allenati ora per massimizzare energia"), + ("Nuovo record", "Hai superato il tuo best settimanale!"), + ], + "chart_titles": ["Calorie settimana", "AttivitΓ  giornaliera", "Progress 7 giorni", "Trend fitness"], + "map_titles": ["Percorso corsa", "Tracciato attivitΓ ", "Mappa allenamento", "Run map"], + "status_sets": [ + ["Attivo", "Riposo", "Aiuto"], + ["Training", "Rest day", "Supporto"], + ["On fire", "Pausa", "Info"], + ] + }, + "banking": { + "greetings": ["Benvenuto,", "Ciao,", "Buongiorno,", "Hey,"], + "subtitles": ["Gestisci il tuo denaro", "I tuoi conti", "Panoramica finanziaria", "Dashboard"], + "main_card_titles": ["Ultima transazione", "Movimento recente", "Operazione recente", "Pagamento"], + "main_texts": ["Pagamento Spotify", "Bonifico ricevuto", "Prelievo ATM", "Amazon acquisto"], + "main_details": ["-€9.99 β€’ Oggi 14:32", "+€1.200 β€’ Stipendio", "-€50.00 β€’ Via Roma 15", "-€42.50 β€’ Consegna prevista"], + "stat_labels": [ + ["Saldo", "Spese mese", "Risparmi", "Transazioni"], + ["Disponibile", "Uscite", "Salvadanaio", "Movimenti"], + ["Conto", "Budget usato", "Obiettivo", "Operazioni"], + ], + "suggestions": [ + ("Risparmio smart", "Metti da parte €50 questo mese"), + ("Spesa ridotta", "Hai speso -15% rispetto al mese scorso"), + ("Nuovo obiettivo", "Crea un piano risparmio per le vacanze"), + ], + "chart_titles": ["Spese settimana", "Bilancio 7 giorni", "Uscite recenti", "Trend mensile"], + "map_titles": ["ATM vicini", "Filiali", "Punti prelievo", "Sportelli area"], + "status_sets": [ + ["Principale", "Risparmio", "Aiuto"], + ["Conto base", "Salvadanaio", "Supporto"], + ["Attivo", "Investimenti", "Info"], + ] + }, + "ecommerce": { + "greetings": ["Ciao,", "Hey,", "Bentornato,", "Buongiorno,"], + "subtitles": ["Trova il prodotto perfetto", "Nuove offerte", "Scopri novitΓ ", "Shopping time"], + "main_card_titles": ["Offerta del giorno", "Deal speciale", "Sconto flash", "Promozione"], + "main_texts": ["iPhone 15 Pro -20%", "Scarpe Nike scontate", "Laptop Gaming", "Cuffie wireless"], + "main_details": ["€999 invece di €1.249", "Solo oggi -30%", "Prestazioni top", "Cancellazione rumore"], + "stat_labels": [ + ["Ordini", "Speso", "Punti", "Preferiti"], + ["Acquisti", "Totale €", "Loyalty", "Wishlist"], + ["Carrelli", "Budget", "Rewards", "Salvati"], + ], + "suggestions": [ + ("Spedizione gratis", "Aggiungi €15 per sbloccare la spedizione"), + ("Sconto attivo", "Usa il codice SAVE20 entro stasera"), + ("Prodotto in sconto", "Un articolo della wishlist Γ¨ scontato!"), + ], + "chart_titles": ["Spese settimana", "Ordini 7 giorni", "Shopping trend", "Acquisti recenti"], + "map_titles": ["Negozi vicini", "Punti ritiro", "Store fisici", "Pickup points"], + "status_sets": [ + ["Shopping", "Wishlist", "Ordini"], + ["Catalogo", "Preferiti", "Tracking"], + ["NovitΓ ", "Salvati", "Storico"], + ] + }, + "social": { + "greetings": ["Ciao,", "Hey,", "Welcome back,", "Bentornato,"], + "subtitles": ["Cosa c'Γ¨ di nuovo?", "Feed aggiornato", "Nuove storie", "Scopri"], + "main_card_titles": ["Post in evidenza", "Trending ora", "Hot topic", "Story del giorno"], + "main_texts": ["@marco_design nuovo post", "Video virale", "Foto travel goals", "Meme epico"], + "main_details": ["2.4k like β€’ 340 commenti", "1.2M views", "145 condivisioni", "Trending #1"], + "stat_labels": [ + ["Post", "Follower", "Like", "Messaggi"], + ["Contenuti", "Following", "Reactions", "Chat"], + ["Stories", "Amici", "Engagement", "DM"], + ], + "suggestions": [ + ("Nuovi follower", "5 persone hanno iniziato a seguirti"), + ("Post virale", "Il tuo ultimo post ha 2k like!"), + ("Amici attivi", "Marco e altri 12 sono online ora"), + ], + "chart_titles": ["Engagement settimana", "Like ricevuti", "AttivitΓ  7 giorni", "Trend profilo"], + "map_titles": ["Amici vicini", "Check-in", "Luoghi taggati", "Mappa social"], + "status_sets": [ + ["Online", "Assente", "Invisibile"], + ["Attivo", "Via", "Offline"], + ["Disponibile", "Non disturbare", "Nascosto"], + ] + } + } + + # Get variations for this app type (or use generic) + app_vars = variations.get(app_type, variations["fitness"]) + + # Random selection + return { + "variant_id": seed, + "greeting": random.choice(app_vars["greetings"]), + "subtitle": random.choice(app_vars["subtitles"]), + "main_card_title": random.choice(app_vars["main_card_titles"]), + "main_card_text": random.choice(app_vars["main_texts"]), + "main_card_detail": random.choice(app_vars["main_details"]), + "stat_labels_set": random.choice(app_vars["stat_labels"]), + "suggestion": random.choice(app_vars["suggestions"]), + "chart_title": random.choice(app_vars["chart_titles"]), + "map_title": random.choice(app_vars["map_titles"]), + "status_labels": random.choice(app_vars["status_sets"]) + } + + def _generate_content_ideas(self, theme: Dict[str, Any], app_type: str) -> Dict[str, Any]: + """ + Use AI to generate DYNAMIC content ideas (texts, labels, titles) + Different from hardcoded templates! + """ + + prompt = f"""You are a UX copywriter. Generate creative, varied content for a {app_type} mobile app home screen. + +App Type: {app_type} +Theme: {theme.get("name", "Modern")} + +Generate DIVERSE content ideas (not generic!). Output ONLY valid JSON: + +{{ + "greeting": "Ciao,", + "subtitle": "...", + "main_card_title": "...", + "main_card_text": "...", + "main_card_detail": "...", + "stat1_label": "...", + "stat2_label": "...", + "stat3_label": "...", + "stat4_label": "...", + "suggestion_title": "...", + "suggestion_text": "...", + "chart_title": "...", + "map_title": "...", + "status_labels": ["...", "...", "..."] +}} + +Make it specific to {app_type} apps. Be creative and varied! + +JSON:""" + + try: + generated_text = self.client.text_generation( + prompt=prompt, + model=self.model, + max_new_tokens=500, + temperature=0.9, # High temperature for variety + top_p=0.95, + ) + + result = self._extract_json_from_text(generated_text) + if result: + print(f"βœ… Generated dynamic content: {list(result.keys())}") + return result + else: + print("⚠️ Failed to extract JSON from AI response") + return {} + + except Exception as e: + print(f"❌ Content generation error: {e}") + return {} + + def _extract_json_from_text(self, text: str) -> Dict[str, Any]: + """Extract JSON object from generated text""" + + try: + # Try to find JSON in the text + start = text.find('{') + end = text.rfind('}') + 1 + + if start >= 0 and end > start: + json_str = text[start:end] + return json.loads(json_str) + except: + pass + + return None + + def _compile_screen( + self, + theme: Dict[str, Any], + app_type: str, + screen_type: str, + plan: Dict[str, Any] + ) -> str: + """ + Use Jinja2 to compile Dart code from plan and theme + """ + + # For now, generate inline since we don't have template files yet + # This will be replaced with actual Jinja2 templates + return self._generate_inline_dart(theme, app_type, screen_type, plan) + + def _generate_background_only( + self, + theme: Dict[str, Any], + app_type: str, + bg_style: str + ) -> str: + """ + Generate ONLY background with 4 style variations using theme colors + """ + + palette = theme.get("palette", {}) + + # Extract colors from theme + primary = palette.get("primary", "#FF6D00").replace("#", "FF") + secondary = palette.get("secondary", "#FFE082").replace("#", "FF") + accent = palette.get("accent", "#FFA726").replace("#", "FF") + background = palette.get("background", "#FFF7F1").replace("#", "FF") + + # Build minimal Dart code with ONLY background using router (supports all 30 backgrounds) + painter_code = self._get_background_painter(bg_style, primary, secondary, accent) + + code = f'''import 'package:flutter/material.dart'; + +void main() {{ + runApp(const MyApp()); +}} + +class MyApp extends StatelessWidget {{ + const MyApp({{super.key}}); + + @override + Widget build(BuildContext context) {{ + return MaterialApp( + title: 'Background Demo', + debugShowCheckedModeBanner: false, + home: Scaffold( + body: Container( + color: Colors.black, + child: Center( + child: ClipRRect( + borderRadius: BorderRadius.circular(32), + child: SizedBox( + width: 430, + height: 932, + child: CustomPaint( + painter: _BackgroundPainter(), + child: Column( + children: [ + const SizedBox(height: 10), + const _FakeNotch(), + Expanded( + child: Container(), + ), + ], + ), + ), + ), + ), + ), + ), + ), + ); + }} +}} + +/* ───────────────────────────── NOTCH FINTA ────────────────────────���──── */ + +class _FakeNotch extends StatelessWidget {{ + const _FakeNotch(); + + @override + Widget build(BuildContext context) {{ + return Center( + child: Container( + width: 180, + height: 30, + decoration: BoxDecoration( + color: Colors.black, + borderRadius: BorderRadius.circular(20), + border: Border.all( + color: Colors.white.withOpacity(0.1), + width: 0.7, + ), + ), + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + width: 10, + height: 10, + decoration: const BoxDecoration( + color: Colors.black54, + shape: BoxShape.circle, + ), + ), + Container( + width: 70, + height: 4, + decoration: BoxDecoration( + color: Colors.grey[300], + borderRadius: BorderRadius.circular(10), + ), + ), + const SizedBox(width: 10), + ], + ), + ), + ); + }} +}} + +{painter_code} +''' + + return code + + def _get_waves_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── WAVES BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint() + ..shader = LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + Color(0x{primary}).withOpacity(0.1), + Color(0x{secondary}).withOpacity(0.2), + Color(0x{accent}).withOpacity(0.1), + ], + ).createShader(Rect.fromLTWH(0, 0, size.width, size.height)); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + final paintTop = Paint() + ..color = Color(0x{primary}).withOpacity(0.4) + ..style = PaintingStyle.fill; + + final pathTop = Path() + ..moveTo(0, size.height * 0.15) + ..quadraticBezierTo( + size.width * 0.25, + size.height * 0.08, + size.width * 0.5, + size.height * 0.15, + ) + ..quadraticBezierTo( + size.width * 0.75, + size.height * 0.22, + size.width, + size.height * 0.14, + ) + ..lineTo(size.width, 0) + ..lineTo(0, 0) + ..close(); + + canvas.drawPath(pathTop, paintTop); + + final paintMid = Paint() + ..color = Color(0x{secondary}).withOpacity(0.35) + ..style = PaintingStyle.fill; + + final pathMid = Path() + ..moveTo(0, size.height * 0.5) + ..quadraticBezierTo( + size.width * 0.3, + size.height * 0.45, + size.width * 0.5, + size.height * 0.52, + ) + ..quadraticBezierTo( + size.width * 0.7, + size.height * 0.59, + size.width, + size.height * 0.5, + ) + ..lineTo(size.width, size.height * 0.3) + ..lineTo(0, size.height * 0.3) + ..close(); + + canvas.drawPath(pathMid, paintMid); + + final paintBottom = Paint() + ..color = Color(0x{accent}).withOpacity(0.3) + ..style = PaintingStyle.fill; + + final pathBottom = Path() + ..moveTo(0, size.height * 0.88) + ..quadraticBezierTo( + size.width * 0.25, + size.height * 0.82, + size.width * 0.5, + size.height * 0.86, + ) + ..quadraticBezierTo( + size.width * 0.75, + size.height * 0.91, + size.width, + size.height * 0.85, + ) + ..lineTo(size.width, size.height) + ..lineTo(0, size.height) + ..close(); + + canvas.drawPath(pathBottom, paintBottom); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_gradient_linear_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── LINEAR GRADIENT BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final paint = Paint() + ..shader = LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + Color(0x{primary}), + Color(0x{secondary}), + Color(0x{accent}), + ], + stops: [0.0, 0.5, 1.0], + ).createShader(Rect.fromLTWH(0, 0, size.width, size.height)); + + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_gradient_radial_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── RADIAL GRADIENT BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final paint = Paint() + ..shader = RadialGradient( + center: Alignment.center, + radius: 1.0, + colors: [ + Color(0x{primary}), + Color(0x{secondary}), + Color(0x{accent}), + ], + stops: [0.0, 0.6, 1.0], + ).createShader(Rect.fromLTWH(0, 0, size.width, size.height)); + + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_geometric_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── GEOMETRIC BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + // Base gradient + final basePaint = Paint() + ..shader = LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + Color(0x{primary}).withOpacity(0.2), + Color(0x{secondary}).withOpacity(0.3), + ], + ).createShader(Rect.fromLTWH(0, 0, size.width, size.height)); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + // Large circle top left + final circlePaint1 = Paint() + ..color = Color(0x{primary}).withOpacity(0.3) + ..style = PaintingStyle.fill; + canvas.drawCircle( + Offset(size.width * 0.2, size.height * 0.15), + size.width * 0.4, + circlePaint1, + ); + + // Medium circle bottom right + final circlePaint2 = Paint() + ..color = Color(0x{accent}).withOpacity(0.25) + ..style = PaintingStyle.fill; + canvas.drawCircle( + Offset(size.width * 0.75, size.height * 0.7), + size.width * 0.35, + circlePaint2, + ); + + // Small circle center + final circlePaint3 = Paint() + ..color = Color(0x{secondary}).withOpacity(0.2) + ..style = PaintingStyle.fill; + canvas.drawCircle( + Offset(size.width * 0.5, size.height * 0.45), + size.width * 0.25, + circlePaint3, + ); + + // Rectangle top right + final rectPaint = Paint() + ..color = Color(0x{accent}).withOpacity(0.15) + ..style = PaintingStyle.fill; + canvas.drawRRect( + RRect.fromRectAndRadius( + Rect.fromLTWH( + size.width * 0.6, + size.height * 0.1, + size.width * 0.3, + size.height * 0.2, + ), + Radius.circular(20), + ), + rectPaint, + ); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + # ═══════════════════════════════════════════════════════════════════════ + # GRADIENT BACKGROUNDS (6 total) + # ═══════════════════════════════════════════════════════════════════════ + + def _get_gradient_angular_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── ANGULAR GRADIENT BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final paint = Paint() + ..shader = SweepGradient( + center: Alignment.center, + startAngle: 0.0, + endAngle: 6.28, // 2*PI + colors: [ + Color(0x{primary}), + Color(0x{secondary}), + Color(0x{accent}), + Color(0x{primary}), + ], + stops: [0.0, 0.33, 0.66, 1.0], + ).createShader(Rect.fromLTWH(0, 0, size.width, size.height)); + + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_gradient_sweep_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── SWEEP GRADIENT BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final paint = Paint() + ..shader = SweepGradient( + center: Alignment(0.3, -0.5), // Offset center for dynamic effect + colors: [ + Color(0x{primary}), + Color(0x{accent}), + Color(0x{secondary}), + Color(0x{primary}), + ], + ).createShader(Rect.fromLTWH(0, 0, size.width, size.height)); + + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_gradient_mesh_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── MESH GRADIENT BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + // Create overlapping radial gradients for mesh effect + final gradient1 = Paint() + ..shader = RadialGradient( + center: Alignment.topLeft, + radius: 1.5, + colors: [Color(0x{primary}), Colors.transparent], + ).createShader(Rect.fromLTWH(0, 0, size.width, size.height)); + + final gradient2 = Paint() + ..shader = RadialGradient( + center: Alignment.topRight, + radius: 1.2, + colors: [Color(0x{secondary}), Colors.transparent], + ).createShader(Rect.fromLTWH(0, 0, size.width, size.height)) + ..blendMode = BlendMode.screen; + + final gradient3 = Paint() + ..shader = RadialGradient( + center: Alignment.bottomCenter, + radius: 1.0, + colors: [Color(0x{accent}), Colors.transparent], + ).createShader(Rect.fromLTWH(0, 0, size.width, size.height)) + ..blendMode = BlendMode.screen; + + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), gradient1); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), gradient2); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), gradient3); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_gradient_diagonal_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── DIAGONAL GRADIENT BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final paint = Paint() + ..shader = LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + Color(0x{primary}), + Color(0x{secondary}), + ], + ).createShader(Rect.fromLTWH(0, 0, size.width, size.height)); + + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + # ═══════════════════════════════════════════════════════════════════════ + # WAVE BACKGROUNDS (5 total) + # ═══════════════════════════════════════════════════════════════════════ + + def _get_waves_smooth_painter(self, primary: str, secondary: str, accent: str) -> str: + # This is the existing waves painter - keeping same implementation + return self._get_waves_painter(primary, secondary, accent) + + def _get_waves_sharp_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── SHARP WAVES BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint() + ..color = Color(0x{primary}).withOpacity(0.15); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + // Sharp zigzag wave 1 + final paint1 = Paint() + ..color = Color(0x{primary}).withOpacity(0.5) + ..style = PaintingStyle.fill; + + final path1 = Path() + ..moveTo(0, size.height * 0.2); + for (double i = 0; i <= size.width; i += size.width / 8) {{ + path1.lineTo(i, size.height * 0.15); + path1.lineTo(i + size.width / 16, size.height * 0.25); + }} + path1.lineTo(size.width, 0)..lineTo(0, 0)..close(); + canvas.drawPath(path1, paint1); + + // Sharp zigzag wave 2 + final paint2 = Paint() + ..color = Color(0x{secondary}).withOpacity(0.4) + ..style = PaintingStyle.fill; + + final path2 = Path() + ..moveTo(0, size.height * 0.55); + for (double i = 0; i <= size.width; i += size.width / 10) {{ + path2.lineTo(i, size.height * 0.5); + path2.lineTo(i + size.width / 20, size.height * 0.6); + }} + path2.lineTo(size.width, size.height * 0.35)..lineTo(0, size.height * 0.35)..close(); + canvas.drawPath(path2, paint2); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_waves_layered_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── LAYERED WAVES BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint() + ..shader = LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0x{primary}).withOpacity(0.1), Color(0x{accent}).withOpacity(0.1)], + ).createShader(Rect.fromLTWH(0, 0, size.width, size.height)); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + // Layer 1 - Bottom + final paint1 = Paint()..color = Color(0x{accent}).withOpacity(0.25); + final path1 = Path() + ..moveTo(0, size.height * 0.7) + ..quadraticBezierTo(size.width * 0.25, size.height * 0.65, size.width * 0.5, size.height * 0.72) + ..quadraticBezierTo(size.width * 0.75, size.height * 0.79, size.width, size.height * 0.7) + ..lineTo(size.width, size.height)..lineTo(0, size.height)..close(); + canvas.drawPath(path1, paint1); + + // Layer 2 - Middle + final paint2 = Paint()..color = Color(0x{secondary}).withOpacity(0.3); + final path2 = Path() + ..moveTo(0, size.height * 0.5) + ..quadraticBezierTo(size.width * 0.3, size.height * 0.45, size.width * 0.5, size.height * 0.52) + ..quadraticBezierTo(size.width * 0.7, size.height * 0.58, size.width, size.height * 0.5) + ..lineTo(size.width, size.height)..lineTo(0, size.height)..close(); + canvas.drawPath(path2, paint2); + + // Layer 3 - Top + final paint3 = Paint()..color = Color(0x{primary}).withOpacity(0.35); + final path3 = Path() + ..moveTo(0, size.height * 0.3) + ..quadraticBezierTo(size.width * 0.25, size.height * 0.25, size.width * 0.5, size.height * 0.32) + ..quadraticBezierTo(size.width * 0.75, size.height * 0.38, size.width, size.height * 0.3) + ..lineTo(size.width, size.height)..lineTo(0, size.height)..close(); + canvas.drawPath(path3, paint3); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_waves_curved_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── CURVED WAVES BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.1); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + // Curved wave from top + final paint1 = Paint()..color = Color(0x{primary}).withOpacity(0.4); + final path1 = Path() + ..moveTo(0, 0) + ..lineTo(0, size.height * 0.2) + ..cubicTo(size.width * 0.3, size.height * 0.1, size.width * 0.7, size.height * 0.3, size.width, size.height * 0.18) + ..lineTo(size.width, 0)..close(); + canvas.drawPath(path1, paint1); + + // Curved wave from bottom + final paint2 = Paint()..color = Color(0x{secondary}).withOpacity(0.35); + final path2 = Path() + ..moveTo(0, size.height) + ..lineTo(0, size.height * 0.75) + ..cubicTo(size.width * 0.25, size.height * 0.85, size.width * 0.75, size.height * 0.65, size.width, size.height * 0.78) + ..lineTo(size.width, size.height)..close(); + canvas.drawPath(path2, paint2); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_waves_minimal_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── MINIMAL WAVE BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.05); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + // Single subtle wave + final paint = Paint()..color = Color(0x{secondary}).withOpacity(0.15); + final path = Path() + ..moveTo(0, size.height * 0.4) + ..quadraticBezierTo(size.width * 0.5, size.height * 0.35, size.width, size.height * 0.4) + ..lineTo(size.width, size.height) + ..lineTo(0, size.height) + ..close(); + canvas.drawPath(path, paint); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + # ═══════════════════════════════════════════════════════════════��═══════ + # GEOMETRIC BACKGROUNDS (6 total) + # ═══════════════════════════════════════════════════════════════════════ + + def _get_geometric_circles_painter(self, primary: str, secondary: str, accent: str) -> str: + # This is the existing geometric painter - keeping same implementation + return self._get_geometric_painter(primary, secondary, accent) + + def _get_geometric_triangles_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── TRIANGLE PATTERN BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.1); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + // Triangle 1 - Top + final paint1 = Paint()..color = Color(0x{primary}).withOpacity(0.3); + final path1 = Path() + ..moveTo(size.width * 0.5, size.height * 0.05) + ..lineTo(size.width * 0.2, size.height * 0.4) + ..lineTo(size.width * 0.8, size.height * 0.4) + ..close(); + canvas.drawPath(path1, paint1); + + // Triangle 2 - Left + final paint2 = Paint()..color = Color(0x{secondary}).withOpacity(0.25); + final path2 = Path() + ..moveTo(size.width * 0.1, size.height * 0.5) + ..lineTo(size.width * 0.05, size.height * 0.8) + ..lineTo(size.width * 0.35, size.height * 0.65) + ..close(); + canvas.drawPath(path2, paint2); + + // Triangle 3 - Right + final paint3 = Paint()..color = Color(0x{accent}).withOpacity(0.28); + final path3 = Path() + ..moveTo(size.width * 0.9, size.height * 0.6) + ..lineTo(size.width * 0.65, size.height * 0.75) + ..lineTo(size.width * 0.95, size.height * 0.85) + ..close(); + canvas.drawPath(path3, paint3); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_geometric_hexagons_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── HEXAGON GRID BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.08); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + void drawHexagon(Offset center, double radius, Color color) {{ + final paint = Paint() + ..color = color + ..style = PaintingStyle.stroke + ..strokeWidth = 2.0; + + final path = Path(); + for (int i = 0; i < 6; i++) {{ + final angle = (3.14159 / 3) * i; + final x = center.dx + radius * cos(angle); + final y = center.dy + radius * sin(angle); + if (i == 0) {{ + path.moveTo(x, y); + }} else {{ + path.lineTo(x, y); + }} + }} + path.close(); + canvas.drawPath(path, paint); + }} + + // Draw hexagon grid + final hexSize = size.width * 0.15; + for (double row = 0; row < 8; row++) {{ + for (double col = 0; col < 4; col++) {{ + final x = col * hexSize * 1.8 + (row % 2) * hexSize * 0.9; + final y = row * hexSize * 0.9; + final colors = [ + Color(0x{primary}).withOpacity(0.25), + Color(0x{secondary}).withOpacity(0.2), + Color(0x{accent}).withOpacity(0.22), + ]; + drawHexagon(Offset(x, y), hexSize * 0.5, colors[(row.toInt() + col.toInt()) % 3]); + }} + }} + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}} + +import 'dart:math' show cos, sin;''' + + def _get_geometric_grid_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── DOT GRID BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.05); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + final dotPaint = Paint()..color = Color(0x{secondary}).withOpacity(0.3); + final spacing = size.width / 12; + + for (double x = spacing; x < size.width; x += spacing) {{ + for (double y = spacing; y < size.height; y += spacing) {{ + canvas.drawCircle(Offset(x, y), 3.0, dotPaint); + }} + }} + + // Accent dots + final accentPaint = Paint()..color = Color(0x{accent}).withOpacity(0.5); + for (double x = spacing * 3; x < size.width; x += spacing * 3) {{ + for (double y = spacing * 3; y < size.height; y += spacing * 3) {{ + canvas.drawCircle(Offset(x, y), 5.0, accentPaint); + }} + }} + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_geometric_stripes_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── DIAGONAL STRIPES BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.1); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + final paint1 = Paint() + ..color = Color(0x{secondary}).withOpacity(0.25) + ..style = PaintingStyle.fill; + + final stripeWidth = size.width * 0.15; + for (double i = -size.height; i < size.width + size.height; i += stripeWidth * 2) {{ + final path = Path() + ..moveTo(i, 0) + ..lineTo(i + stripeWidth, 0) + ..lineTo(i + stripeWidth - size.height, size.height) + ..lineTo(i - size.height, size.height) + ..close(); + canvas.drawPath(path, paint1); + }} + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_geometric_diamonds_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── DIAMOND SHAPES BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.08); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + void drawDiamond(Offset center, double size, Color color) {{ + final paint = Paint()..color = color; + final path = Path() + ..moveTo(center.dx, center.dy - size) + ..lineTo(center.dx + size, center.dy) + ..lineTo(center.dx, center.dy + size) + ..lineTo(center.dx - size, center.dy) + ..close(); + canvas.drawPath(path, paint); + }} + + // Large diamond top-left + drawDiamond( + Offset(size.width * 0.25, size.height * 0.2), + size.width * 0.25, + Color(0x{primary}).withOpacity(0.25), + ); + + // Medium diamond center-right + drawDiamond( + Offset(size.width * 0.7, size.height * 0.5), + size.width * 0.18, + Color(0x{secondary}).withOpacity(0.22), + ); + + // Small diamond bottom-left + drawDiamond( + Offset(size.width * 0.3, size.height * 0.75), + size.width * 0.15, + Color(0x{accent}).withOpacity(0.28), + ); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + # ═══════════════════════════════════════════════════════════════════════ + # ORGANIC BACKGROUNDS (4 total) + # ═══════════════════════════════════════════════════════════════════════ + + def _get_organic_blobs_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── BLOB SHAPES BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.05); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + // Blob 1 + final paint1 = Paint()..color = Color(0x{primary}).withOpacity(0.25); + final path1 = Path() + ..moveTo(size.width * 0.3, size.height * 0.15) + ..cubicTo(size.width * 0.1, size.height * 0.2, size.width * 0.05, size.height * 0.35, size.width * 0.15, size.height * 0.45) + ..cubicTo(size.width * 0.25, size.height * 0.55, size.width * 0.45, size.height * 0.5, size.width * 0.5, size.height * 0.35) + ..cubicTo(size.width * 0.55, size.height * 0.2, size.width * 0.45, size.height * 0.1, size.width * 0.3, size.height * 0.15) + ..close(); + canvas.drawPath(path1, paint1); + + // Blob 2 + final paint2 = Paint()..color = Color(0x{secondary}).withOpacity(0.22); + final path2 = Path() + ..moveTo(size.width * 0.7, size.height * 0.6) + ..cubicTo(size.width * 0.5, size.height * 0.65, size.width * 0.55, size.height * 0.8, size.width * 0.7, size.height * 0.85) + ..cubicTo(size.width * 0.85, size.height * 0.9, size.width * 0.95, size.height * 0.75, size.width * 0.9, size.height * 0.6) + ..cubicTo(size.width * 0.85, size.height * 0.55, size.width * 0.75, size.height * 0.57, size.width * 0.7, size.height * 0.6) + ..close(); + canvas.drawPath(path2, paint2); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_organic_fluid_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── FLUID EFFECT BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + // Smooth flowing shapes with gradients + final paint1 = Paint() + ..shader = RadialGradient( + center: Alignment.topLeft, + radius: 1.2, + colors: [Color(0x{primary}), Color(0x{primary}).withOpacity(0.0)], + ).createShader(Rect.fromLTWH(0, 0, size.width, size.height)); + + final path1 = Path() + ..moveTo(0, 0) + ..cubicTo(size.width * 0.3, size.height * 0.1, size.width * 0.4, size.height * 0.3, size.width * 0.2, size.height * 0.5) + ..cubicTo(size.width * 0.0, size.height * 0.7, 0, size.height * 0.4, 0, size.height * 0.5) + ..lineTo(0, 0) + ..close(); + canvas.drawPath(path1, paint1); + + final paint2 = Paint() + ..shader = RadialGradient( + center: Alignment.bottomRight, + radius: 1.0, + colors: [Color(0x{secondary}), Color(0x{secondary}).withOpacity(0.0)], + ).createShader(Rect.fromLTWH(0, 0, size.width, size.height)); + + final path2 = Path() + ..moveTo(size.width, size.height) + ..cubicTo(size.width * 0.7, size.height * 0.9, size.width * 0.6, size.height * 0.7, size.width * 0.8, size.height * 0.5) + ..cubicTo(size.width, size.height * 0.3, size.width, size.height * 0.6, size.width, size.height * 0.5) + ..lineTo(size.width, size.height) + ..close(); + canvas.drawPath(path2, paint2); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_organic_noise_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── NOISE TEXTURE BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint() + ..shader = LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0x{primary}).withOpacity(0.2), Color(0x{secondary}).withOpacity(0.15)], + ).createShader(Rect.fromLTWH(0, 0, size.width, size.height)); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + // Simulated noise with random circles + final paint = Paint()..color = Color(0x{accent}).withOpacity(0.1); + final random = [0.1, 0.3, 0.5, 0.7, 0.9, 0.15, 0.35, 0.55, 0.75, 0.95]; + + for (int i = 0; i < 50; i++) {{ + final x = size.width * random[i % 10]; + final y = size.height * random[(i * 3) % 10]; + final radius = 2.0 + (i % 5); + canvas.drawCircle(Offset(x, y), radius, paint); + }} + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_organic_clouds_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── CLOUD SHAPES BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.08); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + void drawCloud(Offset center, double scale, Color color) {{ + final paint = Paint()..color = color; + + // Cloud made of overlapping circles + canvas.drawCircle(Offset(center.dx, center.dy), 30 * scale, paint); + canvas.drawCircle(Offset(center.dx + 25 * scale, center.dy - 10 * scale), 35 * scale, paint); + canvas.drawCircle(Offset(center.dx + 50 * scale, center.dy), 28 * scale, paint); + canvas.drawCircle(Offset(center.dx + 25 * scale, center.dy + 10 * scale), 32 * scale, paint); + }} + + drawCloud(Offset(size.width * 0.25, size.height * 0.2), 1.2, Color(0x{primary}).withOpacity(0.2)); + drawCloud(Offset(size.width * 0.7, size.height * 0.35), 1.0, Color(0x{secondary}).withOpacity(0.18)); + drawCloud(Offset(size.width * 0.4, size.height * 0.65), 0.9, Color(0x{accent}).withOpacity(0.16)); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + # ════════════════════════════════════════════════════���══════════════════ + # PATTERN BACKGROUNDS (4 total) + # ═══════════════════════════════════════════════════════════════════════ + + def _get_pattern_dots_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── DOT PATTERN BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.05); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + final paint1 = Paint()..color = Color(0x{secondary}).withOpacity(0.25); + final paint2 = Paint()..color = Color(0x{accent}).withOpacity(0.2); + + final spacing = size.width / 15; + for (double x = spacing; x < size.width; x += spacing) {{ + for (double y = spacing; y < size.height; y += spacing) {{ + final paint = ((x / spacing).toInt() + (y / spacing).toInt()) % 2 == 0 ? paint1 : paint2; + canvas.drawCircle(Offset(x, y), 4.0, paint); + }} + }} + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_pattern_lines_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── LINE PATTERN BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.08); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + final paint = Paint() + ..color = Color(0x{secondary}).withOpacity(0.25) + ..strokeWidth = 2.0 + ..style = PaintingStyle.stroke; + + final spacing = size.height / 20; + for (double y = 0; y < size.height; y += spacing) {{ + canvas.drawLine(Offset(0, y), Offset(size.width, y), paint); + }} + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_pattern_chevron_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── CHEVRON PATTERN BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.08); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + final paint1 = Paint()..color = Color(0x{secondary}).withOpacity(0.22); + final paint2 = Paint()..color = Color(0x{accent}).withOpacity(0.18); + + final chevronHeight = size.height / 12; + for (double y = 0; y < size.height; y += chevronHeight * 2) {{ + final paint = (y / (chevronHeight * 2)).toInt() % 2 == 0 ? paint1 : paint2; + + final path = Path() + ..moveTo(0, y) + ..lineTo(size.width / 2, y + chevronHeight) + ..lineTo(size.width, y) + ..lineTo(size.width, y + chevronHeight * 2) + ..lineTo(size.width / 2, y + chevronHeight * 3) + ..lineTo(0, y + chevronHeight * 2) + ..close(); + canvas.drawPath(path, paint); + }} + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_pattern_zigzag_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── ZIGZAG PATTERN BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.08); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + final paint = Paint() + ..color = Color(0x{secondary}).withOpacity(0.3) + ..strokeWidth = 3.0 + ..style = PaintingStyle.stroke; + + final spacing = size.height / 15; + for (double y = spacing; y < size.height; y += spacing) {{ + final path = Path()..moveTo(0, y); + for (double x = 0; x < size.width; x += size.width / 10) {{ + path.lineTo(x + size.width / 20, y - spacing / 2); + path.lineTo(x + size.width / 10, y); + }} + canvas.drawPath(path, paint); + }} + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + # ════════════════════════════════════════════��══════════════════════════ + # ABSTRACT BACKGROUNDS (5 total) + # ═══════════════════════════════════════════════════════════════════════ + + def _get_abstract_crystalline_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── CRYSTALLINE BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.05); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + final paint1 = Paint() + ..color = Color(0x{primary}).withOpacity(0.2) + ..style = PaintingStyle.fill; + + // Crystal facets + final paths = [ + Path() + ..moveTo(size.width * 0.3, size.height * 0.2) + ..lineTo(size.width * 0.5, size.height * 0.1) + ..lineTo(size.width * 0.6, size.height * 0.3) + ..lineTo(size.width * 0.4, size.height * 0.4) + ..close(), + Path() + ..moveTo(size.width * 0.2, size.height * 0.5) + ..lineTo(size.width * 0.4, size.height * 0.4) + ..lineTo(size.width * 0.5, size.height * 0.6) + ..lineTo(size.width * 0.3, size.height * 0.7) + ..close(), + Path() + ..moveTo(size.width * 0.6, size.height * 0.5) + ..lineTo(size.width * 0.8, size.height * 0.4) + ..lineTo(size.width * 0.9, size.height * 0.6) + ..lineTo(size.width * 0.7, size.height * 0.7) + ..close(), + ]; + + final colors = [ + Color(0x{primary}).withOpacity(0.25), + Color(0x{secondary}).withOpacity(0.22), + Color(0x{accent}).withOpacity(0.28), + ]; + + for (int i = 0; i < paths.length; i++) {{ + canvas.drawPath(paths[i], Paint()..color = colors[i]); + }} + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_abstract_voronoi_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── VORONOI DIAGRAM BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.05); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + // Simplified Voronoi cells + final cells = [ + (Offset(size.width * 0.2, size.height * 0.2), Color(0x{primary}).withOpacity(0.2)), + (Offset(size.width * 0.7, size.height * 0.3), Color(0x{secondary}).withOpacity(0.18)), + (Offset(size.width * 0.5, size.height * 0.6), Color(0x{accent}).withOpacity(0.22)), + (Offset(size.width * 0.3, size.height * 0.75), Color(0x{primary}).withOpacity(0.15)), + (Offset(size.width * 0.8, size.height * 0.7), Color(0x{secondary}).withOpacity(0.2)), + ]; + + for (final cell in cells) {{ + final paint = Paint()..color = cell.$2; + final path = Path() + ..addOval(Rect.fromCircle(center: cell.$1, radius: size.width * 0.25)); + canvas.drawPath(path, paint); + }} + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_abstract_particles_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── PARTICLE FIELD BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.05); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + // Particle positions (pseudo-random but consistent) + final particles = [ + (0.1, 0.2), (0.3, 0.15), (0.5, 0.25), (0.7, 0.18), (0.9, 0.22), + (0.15, 0.4), (0.35, 0.45), (0.55, 0.42), (0.75, 0.48), (0.85, 0.43), + (0.2, 0.6), (0.4, 0.65), (0.6, 0.62), (0.8, 0.68), + (0.25, 0.8), (0.45, 0.82), (0.65, 0.78), (0.85, 0.85), + ]; + + final paint1 = Paint()..color = Color(0x{primary}).withOpacity(0.3); + final paint2 = Paint()..color = Color(0x{secondary}).withOpacity(0.25); + final paint3 = Paint()..color = Color(0x{accent}).withOpacity(0.28); + final paints = [paint1, paint2, paint3]; + + // Draw particles + for (int i = 0; i < particles.length; i++) {{ + final pos = particles[i]; + final paint = paints[i % 3]; + canvas.drawCircle( + Offset(size.width * pos.$1, size.height * pos.$2), + 3.0 + (i % 4), + paint, + ); + }} + + // Draw connections + final linePaint = Paint() + ..color = Color(0x{secondary}).withOpacity(0.15) + ..strokeWidth = 1.0; + + for (int i = 0; i < particles.length - 1; i++) {{ + final p1 = particles[i]; + final p2 = particles[i + 1]; + canvas.drawLine( + Offset(size.width * p1.$1, size.height * p1.$2), + Offset(size.width * p2.$1, size.height * p2.$2), + linePaint, + ); + }} + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + def _get_abstract_rays_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── LIGHT RAYS BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.1); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + final center = Offset(size.width * 0.5, size.height * 0.3); + final paint = Paint() + ..color = Color(0x{secondary}).withOpacity(0.15) + ..style = PaintingStyle.fill; + + // Radiating rays + for (double angle = 0; angle < 6.28; angle += 0.52) {{ + final path = Path() + ..moveTo(center.dx, center.dy) + ..lineTo( + center.dx + size.width * cos(angle), + center.dy + size.height * sin(angle), + ) + ..lineTo( + center.dx + size.width * cos(angle + 0.26), + center.dy + size.height * sin(angle + 0.26), + ) + ..close(); + canvas.drawPath(path, paint); + }} + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}} + +import 'dart:math' show cos, sin;''' + + def _get_abstract_constellation_painter(self, primary: str, secondary: str, accent: str) -> str: + return f'''/* ────────────────────── STAR CONSTELLATION BACKGROUND ───────────────────────── */ + +class _BackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint()..color = Color(0x{primary}).withOpacity(0.08); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + // Star positions + final stars = [ + (0.2, 0.2), (0.3, 0.25), (0.5, 0.18), (0.7, 0.22), (0.8, 0.3), + (0.25, 0.5), (0.4, 0.55), (0.6, 0.48), (0.75, 0.52), + (0.3, 0.75), (0.5, 0.8), (0.7, 0.78), + ]; + + // Draw stars + final starPaint = Paint()..color = Color(0x{accent}).withOpacity(0.5); + for (final star in stars) {{ + canvas.drawCircle( + Offset(size.width * star.$1, size.height * star.$2), + 4.0, + starPaint, + ); + }} + + // Draw constellation lines + final linePaint = Paint() + ..color = Color(0x{secondary}).withOpacity(0.25) + ..strokeWidth = 1.5; + + final connections = [(0, 1), (1, 2), (2, 3), (3, 4), (5, 6), (6, 7), (7, 8), (9, 10), (10, 11)]; + + for (final conn in connections) {{ + final p1 = stars[conn.$1]; + final p2 = stars[conn.$2]; + canvas.drawLine( + Offset(size.width * p1.$1, size.height * p1.$2), + Offset(size.width * p2.$1, size.height * p2.$2), + linePaint, + ); + }} + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}}''' + + # ═══════════════════════════════════════════════════════════════════════ + # BACKGROUND ROUTER - Maps background IDs to painter functions + # ═══════════════════════════════════════════════════════════════════════ + + def _get_background_painter(self, bg_id: str, primary: str, secondary: str, accent: str) -> str: + """Route background ID to correct painter function""" + + painter_map = { + # GRADIENTS + "gradient_linear": self._get_gradient_linear_painter, + "gradient_radial": self._get_gradient_radial_painter, + "gradient_angular": self._get_gradient_angular_painter, + "gradient_sweep": self._get_gradient_sweep_painter, + "gradient_mesh": self._get_gradient_mesh_painter, + "gradient_diagonal": self._get_gradient_diagonal_painter, + + # WAVES + "waves_smooth": self._get_waves_smooth_painter, + "waves_sharp": self._get_waves_sharp_painter, + "waves_layered": self._get_waves_layered_painter, + "waves_curved": self._get_waves_curved_painter, + "waves_minimal": self._get_waves_minimal_painter, + + # GEOMETRIC + "geometric_circles": self._get_geometric_circles_painter, + "geometric_triangles": self._get_geometric_triangles_painter, + "geometric_hexagons": self._get_geometric_hexagons_painter, + "geometric_grid": self._get_geometric_grid_painter, + "geometric_stripes": self._get_geometric_stripes_painter, + "geometric_diamonds": self._get_geometric_diamonds_painter, + + # ORGANIC + "organic_blobs": self._get_organic_blobs_painter, + "organic_fluid": self._get_organic_fluid_painter, + "organic_noise": self._get_organic_noise_painter, + "organic_clouds": self._get_organic_clouds_painter, + + # PATTERNS + "pattern_dots": self._get_pattern_dots_painter, + "pattern_lines": self._get_pattern_lines_painter, + "pattern_chevron": self._get_pattern_chevron_painter, + "pattern_zigzag": self._get_pattern_zigzag_painter, + + # ABSTRACT + "abstract_crystalline": self._get_abstract_crystalline_painter, + "abstract_voronoi": self._get_abstract_voronoi_painter, + "abstract_particles": self._get_abstract_particles_painter, + "abstract_rays": self._get_abstract_rays_painter, + "abstract_constellation": self._get_abstract_constellation_painter, + + # Legacy aliases for backwards compatibility + "waves": self._get_waves_smooth_painter, + "geometric": self._get_geometric_circles_painter, + } + + painter_func = painter_map.get(bg_id) + if painter_func: + return painter_func(primary, secondary, accent) + else: + # Fallback to gradient if unknown ID + print(f"⚠️ Unknown background ID '{bg_id}', using gradient_linear fallback") + return self._get_gradient_linear_painter(primary, secondary, accent) + + def _generate_complete_screen( + self, + theme: Dict[str, Any], + app_type: str, + variant: Dict[str, Any] + ) -> str: + """ + Generate complete Flutter screen with background + header + footer + Based on AI-selected variant and FULL theme styles + """ + + palette = theme.get("palette", {}) + typography = theme.get("typography", {}) + borders = theme.get("borders", {}) + shadows = theme.get("shadows", {}) + spacing = theme.get("spacing", {}) + component_style = theme.get("component_style", {}) + theme_style = theme.get("style", "modern") # bold, minimalist, elegant, etc. + + # Extract ALL colors from palette + primary = palette.get("primary", "#FF6D00").replace("#", "FF") + secondary = palette.get("secondary", "#FFE082").replace("#", "FF") + accent = palette.get("accent", palette.get("warning", "#FFA726")).replace("#", "FF") + bg_color = palette.get("background", "#FFFFFF").replace("#", "FF") + surface_color = palette.get("surface", "#F5F5F5").replace("#", "FF") + text_primary = palette.get("text_primary", "#000000").replace("#", "FF") + text_secondary = palette.get("text_secondary", "#8E8E93").replace("#", "FF") + border_color = palette.get("border", "#E0E0E0").replace("#", "FF") + + # Extract typography + display_font = typography.get("display", {}).get("font_family", "Roboto") + body_font = typography.get("body", {}).get("font_family", "Roboto") + numbers_font = typography.get("numbers", {}).get("font_family", body_font) + display_weight = typography.get("display", {}).get("weight", 700) + body_weight = typography.get("body", {}).get("weight", 400) + + # Extract borders + border_radius_small = borders.get("radius", {}).get("small", "4px").replace("px", "") + border_radius_medium = borders.get("radius", {}).get("medium", "8px").replace("px", "") + border_radius_large = borders.get("radius", {}).get("large", "12px").replace("px", "") + border_width = borders.get("width", {}).get("regular", "2px").replace("px", "") + + # Extract shadows (convert CSS to Flutter BoxShadow params) + shadow_medium = shadows.get("medium", "0 4px 8px rgba(0,0,0,0.25)") + + # Extract spacing unit + spacing_unit = spacing.get("unit", 8) + + # Create theme data object to pass to components + theme_data = { + "primary": primary, + "secondary": secondary, + "accent": accent, + "bg_color": bg_color, + "surface_color": surface_color, + "text_primary": text_primary, + "text_secondary": text_secondary, + "border_color": border_color, + "display_font": display_font, + "body_font": body_font, + "numbers_font": numbers_font, + "display_weight": display_weight, + "body_weight": body_weight, + "border_radius_small": border_radius_small, + "border_radius_medium": border_radius_medium, + "border_radius_large": border_radius_large, + "border_width": border_width, + "spacing_unit": spacing_unit, + "style": theme_style + } + + # Get background painter using router (supports all 30 backgrounds) + bg_style = variant["background"] + painter_code = self._get_background_painter(bg_style, primary, secondary, accent) + + # Extract theme values for use in Dart code generation + is_bold = (theme_style == "bold") + numbers_font = theme_data["numbers_font"] + + # Get text customizations from variant + variant_texts = variant.get("texts", {}) + + # Get header code with theme data and text customizations + header_code = self._get_header_code(variant["header"], theme_data, app_type, variant_texts) + + # Get footer code with theme data and text customizations + footer_code = self._get_footer_code(variant["footer"], theme_data, variant_texts) + + # Build complete Dart code + code = f'''import 'package:flutter/material.dart'; + +void main() {{ + runApp(const MyApp()); +}} + +class MyApp extends StatelessWidget {{ + const MyApp({{super.key}}); + + @override + Widget build(BuildContext context) {{ + return MaterialApp( + title: '{variant["name"]}', + debugShowCheckedModeBanner: false, + theme: ThemeData( + useMaterial3: true, + colorScheme: ColorScheme.fromSeed( + seedColor: const Color(0x{primary}), + brightness: Brightness.light, + ), + fontFamily: '{body_font}', + ), + home: const HomePage(), + builder: (context, child) {{ + return Container( + color: Colors.black, + child: Center( + child: ClipRRect( + borderRadius: BorderRadius.circular(32), + child: SizedBox( + width: 430, + height: 932, + child: child ?? const SizedBox(), + ), + ), + ), + ); + }}, + ); + }} +}} + +class HomePage extends StatelessWidget {{ + const HomePage({{super.key}}); + + @override + Widget build(BuildContext context) {{ + return Scaffold( + backgroundColor: Colors.transparent, + body: CustomPaint( + painter: _BackgroundPainter(), + child: Column( + children: [ + const SizedBox(height: 10), + const _FakeNotch(), + const SizedBox(height: 8), + {header_code}, + Expanded( + child: SingleChildScrollView( + padding: EdgeInsets.all({spacing_unit * 2.5}), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _ContentCard( + title: '{variant["name"]}', + subtitle: '{variant.get("description", "AI-generated variant")}', + accentColor: Color(0x{primary}), + bgColor: Color(0x{surface_color}), + textColor: Color(0x{text_primary}), + subtitleColor: Color(0x{text_secondary}), + borderRadius: {border_radius_medium}.0, + borderWidth: {border_width}.0, + isBold: {str(theme_style == "bold").lower()}, + ), + SizedBox(height: {spacing_unit * 2}.0), + _ContentCard( + title: 'Feature 1', + subtitle: 'Primary content area', + accentColor: Color(0x{secondary}), + bgColor: Color(0x{surface_color}), + textColor: Color(0x{text_primary}), + subtitleColor: Color(0x{text_secondary}), + borderRadius: {border_radius_medium}.0, + borderWidth: {border_width}.0, + isBold: {str(theme_style == "bold").lower()}, + ), + SizedBox(height: {spacing_unit * 2}.0), + _ContentCard( + title: 'Feature 2', + subtitle: 'Secondary content area', + accentColor: Color(0x{accent}), + bgColor: Color(0x{surface_color}), + textColor: Color(0x{text_primary}), + subtitleColor: Color(0x{text_secondary}), + borderRadius: {border_radius_medium}.0, + borderWidth: {border_width}.0, + isBold: {str(theme_style == "bold").lower()}, + ), + ], + ), + ), + ), + ], + ), + ), + {footer_code}, + ); + }} +}} + +class _FakeNotch extends StatelessWidget {{ + const _FakeNotch(); + + @override + Widget build(BuildContext context) {{ + return Center( + child: Container( + width: 180, + height: 30, + decoration: BoxDecoration( + color: Colors.black, + borderRadius: BorderRadius.circular(20), + border: Border.all( + color: Colors.white.withOpacity(0.1), + width: 0.7, + ), + ), + ), + ); + }} +}} + +// Helper widget for content cards (theme-aware) +class _ContentCard extends StatelessWidget {{ + final String title; + final String subtitle; + final Color accentColor; + final Color bgColor; + final Color textColor; + final Color subtitleColor; + final double borderRadius; + final double borderWidth; + final bool isBold; + + const _ContentCard({{ + required this.title, + required this.subtitle, + required this.accentColor, + required this.bgColor, + required this.textColor, + required this.subtitleColor, + required this.borderRadius, + required this.borderWidth, + required this.isBold, + }}); + + @override + Widget build(BuildContext context) {{ + return Container( + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + color: bgColor, + borderRadius: BorderRadius.circular(borderRadius), + border: isBold ? Border.all( + color: accentColor.withOpacity(0.3), + width: borderWidth, + ) : null, + boxShadow: [ + BoxShadow( + color: isBold ? accentColor.withOpacity(0.2) : Colors.black.withOpacity(0.1), + blurRadius: isBold ? 12 : 8, + offset: Offset(0, isBold ? 6 : 4), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: isBold ? 6 : 4, + height: 40, + decoration: BoxDecoration( + color: accentColor, + borderRadius: BorderRadius.circular(isBold ? 3 : 2), + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: TextStyle( + fontSize: isBold ? 20 : 18, + fontWeight: isBold ? FontWeight.w700 : FontWeight.w600, + color: textColor, + ), + ), + const SizedBox(height: 4), + Text( + subtitle, + style: TextStyle( + fontSize: 14, + color: subtitleColor, + ), + ), + ], + ), + ), + ], + ), + ], + ), + ); + }} +}} + +// Helper widget for tab items (used in tabs header) +class _TabItem extends StatelessWidget {{ + final String label; + final bool isActive; + + const _TabItem(this.label, this.isActive); + + @override + Widget build(BuildContext context) {{ + return Container( + margin: const EdgeInsets.only(right: 12), + padding: EdgeInsets.symmetric(horizontal: {spacing_unit * 2.5}, vertical: {spacing_unit * 1.25}), + decoration: BoxDecoration( + color: isActive ? Color(0x{primary}) : Colors.white.withOpacity(0.2), + borderRadius: BorderRadius.circular({border_radius_large}), + {("border: Border.all(color: Color(0x" + primary + "), width: " + str(border_width) + ")," if is_bold else "")} + ), + child: Text( + label, + style: TextStyle( + fontFamily: '{display_font}', + color: Colors.white, + fontSize: {16 if is_bold else 14}, + fontWeight: isActive ? FontWeight.{("w700" if is_bold else "w600")} : FontWeight.normal, + ), + ), + ); + }} +}} + +// Helper widget for stat items (used in stats_header) +class _StatItem extends StatelessWidget {{ + final String value; + final String label; + + const _StatItem(this.value, this.label); + + @override + Widget build(BuildContext context) {{ + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + value, + style: TextStyle( + fontFamily: '{numbers_font}', + fontSize: {32 if is_bold else 24}, + fontWeight: FontWeight.{("w700" if is_bold else "w600")}, + color: Colors.white, + ), + ), + SizedBox(height: {spacing_unit * 0.5}), + Text( + label, + style: TextStyle( + fontFamily: '{body_font}', + fontSize: {14 if is_bold else 12}, + color: Colors.white.withOpacity(0.7), + ), + ), + ], + ); + }} +}} + +// Helper widget for animated pills footer +class _NavPill extends StatelessWidget {{ + final IconData icon; + final String label; + final bool isActive; + + const _NavPill(this.icon, this.label, this.isActive); + + @override + Widget build(BuildContext context) {{ + return Container( + padding: EdgeInsets.symmetric(horizontal: {spacing_unit * 2}, vertical: {spacing_unit}), + decoration: BoxDecoration( + color: isActive ? Color(0x{primary}) : Colors.transparent, + borderRadius: BorderRadius.circular({border_radius_large}), + {("border: Border.all(color: Color(0x" + primary + ").withOpacity(0.3), width: " + str(border_width) + ")," if is_bold and not "isActive" else "")} + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + icon, + size: {26 if is_bold else 22}, + color: isActive ? Colors.white : Color(0x{text_primary}).withOpacity(0.6), + ), + if (isActive) ...[ + SizedBox(width: {spacing_unit * 0.75}), + Text( + label, + style: TextStyle( + fontFamily: '{body_font}', + color: Colors.white, + fontSize: {15 if is_bold else 13}, + fontWeight: FontWeight.{("w700" if is_bold else "w600")}, + ), + ), + ], + ], + ), + ); + }} +}} + +{painter_code} +''' + + return code + + def _get_header_code(self, header_type: str, theme_data: Dict[str, Any], app_type: str, texts: Dict[str, Any] = None) -> str: + """Generate header widget code based on type and theme""" + + # Extract text customizations or use defaults + if texts is None: + texts = {} + header_title = texts.get("header_title", app_type.capitalize()) + header_subtitle = texts.get("header_subtitle", "Welcome") + + primary = theme_data["primary"] + text_primary = theme_data["text_primary"] + display_font = theme_data["display_font"] + border_radius_medium = theme_data["border_radius_medium"] + spacing_unit = theme_data["spacing_unit"] + is_bold = theme_data["style"] == "bold" + + headers = { + "minimal": f'''Container( + padding: EdgeInsets.all({spacing_unit * 2.5}), + child: Text( + '{header_title}', + style: TextStyle( + fontFamily: '{display_font}', + fontSize: {28 if is_bold else 24}, + fontWeight: FontWeight.{("w700" if is_bold else "w600")}, + color: Colors.white, + ), + textAlign: TextAlign.center, + ), + )''', + + "avatar_search": f'''Container( + padding: EdgeInsets.symmetric(horizontal: {spacing_unit * 2.5}, vertical: {spacing_unit * 1.25}), + child: Row( + children: [ + CircleAvatar( + radius: 20, + backgroundColor: Color(0x{primary}), + child: const Icon(Icons.person, color: Colors.white, size: 20), + ), + const SizedBox(width: 12), + Expanded( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.2), + borderRadius: BorderRadius.circular(24), + ), + child: const Row( + children: [ + Icon(Icons.search, color: Colors.white70, size: 20), + SizedBox(width: 8), + Text('Search...', style: TextStyle(color: Colors.white70)), + ], + ), + ), + ), + const SizedBox(width: 12), + Icon(Icons.notifications_none, color: Colors.white, size: 24), + ], + ), + )''', + + "tabs": f'''Column( + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.all(20), + child: Text( + '{header_title}', + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Colors.white), + ), + ), + SizedBox( + height: 48, + child: ListView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 20), + children: [ + _TabItem('Home', true), + _TabItem('Activity', false), + _TabItem('Profile', false), + ], + ), + ), + ], + )''', + + "collapsible": f'''Container( + padding: const EdgeInsets.all(20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '{header_title}', + style: const TextStyle(fontSize: 28, fontWeight: FontWeight.bold, color: Colors.white), + ), + const SizedBox(height: 4), + Text( + '{header_subtitle}', + style: TextStyle(fontSize: 14, color: Colors.white.withOpacity(0.7)), + ), + ], + ), + )''', + + "stats_header": f'''Container( + padding: const EdgeInsets.all(20), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + _StatItem('24', 'Active'), + _StatItem('156', 'Total'), + _StatItem('4.8', 'Rating'), + ], + ), + )''' + } + + return headers.get(header_type, headers["minimal"]) + + def _get_footer_code(self, footer_type: str, theme_data: Dict[str, Any], texts: Dict[str, Any] = None) -> str: + """Generate footer navigation code based on type and theme""" + + # Extract text customizations or use defaults + if texts is None: + texts = {} + footer_labels = texts.get("footer_labels", ["Home", "Search", "Favorites", "Profile", "Menu"]) + + primary = theme_data["primary"] + surface_color = theme_data["surface_color"] + text_primary = theme_data["text_primary"] + border_radius_large = theme_data["border_radius_large"] + spacing_unit = theme_data["spacing_unit"] + is_bold = theme_data["style"] == "bold" + + footers = { + "minimal_icons": f'''bottomNavigationBar: Container( + margin: EdgeInsets.all({spacing_unit * 2}), + padding: EdgeInsets.symmetric(vertical: {spacing_unit * 1.5}), + decoration: BoxDecoration( + color: Color(0x{surface_color}), + borderRadius: BorderRadius.circular({border_radius_large}), + {("border: Border.all(color: Color(0x" + primary + ").withOpacity(0.2), width: 2)," if is_bold else "")} + boxShadow: [ + BoxShadow( + color: Color(0x{primary}).withOpacity({0.15 if is_bold else 0.08}), + blurRadius: {10 if is_bold else 6}, + offset: Offset(0, {4 if is_bold else 2}), + ), + ], + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + Icon(Icons.home, size: {32 if is_bold else 28}, color: Color(0x{primary})), + Icon(Icons.search, size: {32 if is_bold else 28}, color: Color(0x{text_primary}).withOpacity(0.6)), + Icon(Icons.favorite_border, size: {32 if is_bold else 28}, color: Color(0x{text_primary}).withOpacity(0.6)), + Icon(Icons.person_outline, size: {32 if is_bold else 28}, color: Color(0x{text_primary}).withOpacity(0.6)), + ], + ), + )''', + + "floating_fab": f'''bottomNavigationBar: Container( + margin: const EdgeInsets.all(16), + height: 70, + child: Stack( + children: [ + Container( + padding: const EdgeInsets.symmetric(vertical: 12), + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.95), + borderRadius: BorderRadius.circular(24), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: const [ + Icon(Icons.home, size: 28), + Icon(Icons.search, size: 28), + SizedBox(width: 60), + Icon(Icons.favorite_border, size: 28), + Icon(Icons.person_outline, size: 28), + ], + ), + ), + Center( + child: FloatingActionButton( + onPressed: () {{}}, + backgroundColor: Color(0x{primary}), + child: const Icon(Icons.add, size: 32), + ), + ), + ], + ), + )''', + + "animated_pills": f'''bottomNavigationBar: Container( + margin: const EdgeInsets.all(16), + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.95), + borderRadius: BorderRadius.circular(24), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + _NavPill(Icons.home, 'Home', true), + _NavPill(Icons.search, 'Search', false), + _NavPill(Icons.favorite_border, 'Likes', false), + _NavPill(Icons.person_outline, 'Profile', false), + ], + ), + )''', + + "classic_expanded": f'''bottomNavigationBar: BottomNavigationBar( + type: BottomNavigationBarType.fixed, + selectedItemColor: Color(0x{primary}), + items: const [ + BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'), + BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Search'), + BottomNavigationBarItem(icon: Icon(Icons.favorite_border), label: 'Likes'), + BottomNavigationBarItem(icon: Icon(Icons.person_outline), label: 'Profile'), + ], + )''', + + "gesture_bar": f'''bottomNavigationBar: Container( + height: 34, + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.95), + ), + child: Center( + child: Container( + width: 134, + height: 5, + decoration: BoxDecoration( + color: Colors.grey[400], + borderRadius: BorderRadius.circular(3), + ), + ), + ), + )''' + } + + return footers.get(footer_type, footers["minimal_icons"]) + + def _generate_inline_dart( + self, + theme: Dict[str, Any], + app_type: str, + screen_type: str, + content_ideas: Dict[str, Any] + ) -> str: + """ + Generate complex Dart code with Material 3, custom painters, charts, maps, etc. + Uses DYNAMIC content from AI, not hardcoded templates! + """ + + palette = theme.get("palette", {}) + typography = theme.get("typography", {}) + spacing = theme.get("spacing", {}) + + # Extract colors + primary = palette.get("primary", "#FF6D00").replace("#", "FF") + secondary = palette.get("secondary", "#FFE082").replace("#", "FF") + background = palette.get("background", "#FFF7F1").replace("#", "FF") + + # Generate light variations for gradients + primary_light = self._lighten_color(primary) + secondary_light = self._lighten_color(secondary) + + # Extract typography + display_font = typography.get("display", {}).get("font_family", "Roboto") + body_font = typography.get("body", {}).get("font_family", "Roboto") + + # Generate screen name + screen_class_name = f"{screen_type.capitalize()}Screen" + + # Use RANDOM content variations + static_data = self._get_app_specific_data(app_type) + stat_labels = content_ideas.get("stat_labels_set", ["Val1", "Val2", "Val3", "Val4"]) + suggestion = content_ideas.get("suggestion", ("Suggerimento", "Testo")) + + app_data = { + "app_class": f"{app_type.capitalize()}App", + "title": f"{app_type.capitalize()} App", + "greeting": content_ideas.get("greeting", "Ciao,"), + "subtitle": content_ideas.get("subtitle", "Benvenuto!"), + "main_card_title": content_ideas.get("main_card_title", "Azione"), + "main_card_text": content_ideas.get("main_card_text", "Info"), + "main_card_detail": content_ideas.get("main_card_detail", "Dettagli"), + "stat1_label": stat_labels[0], + "stat1_value": static_data.get("stat1_value", "100"), + "stat1_icon": static_data.get("stat1_icon", "Icons.favorite_rounded"), + "stat2_label": stat_labels[1], + "stat2_value": static_data.get("stat2_value", "200"), + "stat2_icon": static_data.get("stat2_icon", "Icons.star_rounded"), + "stat3_label": stat_labels[2], + "stat3_value": static_data.get("stat3_value", "300"), + "stat3_icon": static_data.get("stat3_icon", "Icons.timer_rounded"), + "stat4_label": stat_labels[3], + "stat4_value": static_data.get("stat4_value", "400"), + "stat4_icon": static_data.get("stat4_icon", "Icons.flag_rounded"), + "suggestion_title": suggestion[0], + "suggestion_text": suggestion[1], + "chart_title": content_ideas.get("chart_title", "Grafico"), + "map_title": content_ideas.get("map_title", "Mappa"), + "status_labels": content_ideas.get("status_labels", ["A", "B", "C"]) + } + + user_name = "Utente" + + # Build complex Dart code + code = f'''import 'package:flutter/material.dart'; + +void main() {{ + runApp(const {app_data['app_class']}()); +}} + +class {app_data['app_class']} extends StatelessWidget {{ + const {app_data['app_class']}({{super.key}}); + + @override + Widget build(BuildContext context) {{ + return MaterialApp( + title: '{app_data['title']}', + debugShowCheckedModeBanner: false, + theme: ThemeData( + useMaterial3: true, + colorScheme: ColorScheme.fromSeed( + seedColor: const Color(0x{primary}), + brightness: Brightness.light, + ), + fontFamily: '{body_font}', + scaffoldBackgroundColor: const Color(0x{background}), + ), + home: const {screen_class_name}(), + + // πŸ“± MOCKUP iPhone + NOTCH + SFONDO WAVES + builder: (context, child) {{ + return Container( + color: Colors.black, + child: Center( + child: ClipRRect( + borderRadius: BorderRadius.circular(32), + child: SizedBox( + width: 430, + height: 932, + child: CustomPaint( + painter: _WavesBackgroundPainter(), + child: Column( + children: [ + const SizedBox(height: 10), + const _FakeNotch(), + const SizedBox(height: 8), + Expanded( + child: child ?? const SizedBox(), + ), + ], + ), + ), + ), + ), + ), + ); + }}, + ); + }} +}} + +/* ──────────────────────────────── HOME PAGE ─────────────────────────────── */ + +class {screen_class_name} extends StatefulWidget {{ + const {screen_class_name}({{super.key}}); + + @override + State<{screen_class_name}> createState() => _{screen_class_name}State(); +}} + +class _{screen_class_name}State extends State<{screen_class_name}> {{ + int _currentTab = 0; + + @override + Widget build(BuildContext context) {{ + final theme = Theme.of(context); + + return Scaffold( + backgroundColor: Colors.transparent, + appBar: AppBar( + elevation: 0, + backgroundColor: Colors.transparent, + surfaceTintColor: Colors.transparent, + title: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '{app_data['greeting']} {user_name} πŸ‘‹', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + color: Colors.grey[900], + ), + ), + Text( + '{app_data['subtitle']}', + style: theme.textTheme.bodySmall?.copyWith( + color: Colors.grey[700], + ), + ), + ], + ), + actions: [ + IconButton( + onPressed: () {{}}, + icon: const Icon(Icons.notifications_none_rounded), + ), + ], + ), + + body: _buildBody(theme), + + bottomNavigationBar: Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 16), + child: _BottomNavBar( + currentIndex: _currentTab, + onItemSelected: (index) {{ + setState(() {{ + _currentTab = index; + }}); + }}, + ), + ), + ); + }} + + Widget _buildBody(ThemeData theme) {{ + return SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '{app_data['main_card_title']}', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w600, + color: Colors.grey[900], + ), + ), + const SizedBox(height: 12), + _MainActionCard(), + + const SizedBox(height: 24), + + Text( + 'Oggi', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w600, + color: Colors.grey[900], + ), + ), + const SizedBox(height: 12), + Row( + children: [ + Expanded( + child: _StatCard( + label: '{app_data['stat1_label']}', + value: '{app_data['stat1_value']}', + icon: {app_data['stat1_icon']}, + tag: 'oggi', + ), + ), + const SizedBox(width: 12), + Expanded( + child: _StatCard( + label: '{app_data['stat2_label']}', + value: '{app_data['stat2_value']}', + icon: {app_data['stat2_icon']}, + tag: 'oggi', + ), + ), + ], + ), + + const SizedBox(height: 12), + Row( + children: [ + Expanded( + child: _StatCard( + label: '{app_data['stat3_label']}', + value: '{app_data['stat3_value']}', + icon: {app_data['stat3_icon']}, + tag: 'oggi', + ), + ), + const SizedBox(width: 12), + Expanded( + child: _StatCard( + label: '{app_data['stat4_label']}', + value: '{app_data['stat4_value']}', + icon: {app_data['stat4_icon']}, + tag: 'totale', + ), + ), + ], + ), + + const SizedBox(height: 24), + + Text( + 'Suggerimento', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w600, + color: Colors.grey[900], + ), + ), + const SizedBox(height: 12), + const _IllustrationCard(), + + const SizedBox(height: 24), + + Text( + 'Andamento settimanale', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w600, + color: Colors.grey[900], + ), + ), + const SizedBox(height: 12), + const _ChartCard(), + + const SizedBox(height: 24), + + Text( + '{app_data['map_title']}', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w600, + color: Colors.grey[900], + ), + ), + const SizedBox(height: 8), + Text( + 'Anteprima non interattiva - solo visualizzazione.', + style: theme.textTheme.bodySmall?.copyWith( + color: Colors.grey[700], + ), + ), + const SizedBox(height: 12), + const _MapPreview(), + + const SizedBox(height: 24), + + Text( + 'Stato', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w600, + color: Colors.grey[900], + ), + ), + const SizedBox(height: 12), + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + _StatusChip( + label: '{app_data['status_labels'][0]}', + selected: true, + icon: Icons.radio_button_checked_rounded, + ), + _StatusChip( + label: '{app_data['status_labels'][1]}', + selected: false, + icon: Icons.free_breakfast_rounded, + ), + _StatusChip( + label: '{app_data['status_labels'][2]}', + selected: false, + icon: Icons.support_agent_rounded, + ), + ], + ), + ], + ), + ); + }} +}} + +/* ───────────────────────────── NOTCH FINTA ───────────────────────────── */ + +class _FakeNotch extends StatelessWidget {{ + const _FakeNotch(); + + @override + Widget build(BuildContext context) {{ + return Center( + child: Container( + width: 180, + height: 30, + decoration: BoxDecoration( + color: Colors.black, + borderRadius: BorderRadius.circular(20), + border: Border.all( + color: Colors.white.withOpacity(0.1), + width: 0.7, + ), + ), + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + width: 10, + height: 10, + decoration: const BoxDecoration( + color: Colors.black54, + shape: BoxShape.circle, + ), + ), + Container( + width: 70, + height: 4, + decoration: BoxDecoration( + color: Colors.grey[300], + borderRadius: BorderRadius.circular(10), + ), + ), + const SizedBox(width: 10), + ], + ), + ), + ); + }} +}} + +/* ───────────────────── CARD AZIONE PRINCIPALE (MODERNA) ─────────────────── */ + +class _MainActionCard extends StatelessWidget {{ + @override + Widget build(BuildContext context) {{ + final theme = Theme.of(context); + + return Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(22), + gradient: const LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + Color(0xFFFFF3E0), + Color(0xFFFFE0B2), + ], + ), + boxShadow: [ + BoxShadow( + color: Colors.black12.withOpacity(0.05), + blurRadius: 18, + offset: const Offset(0, 10), + ), + ], + border: Border.all( + color: Colors.black.withOpacity(0.04), + width: 0.8, + ), + ), + padding: const EdgeInsets.all(18), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.85), + borderRadius: BorderRadius.circular(999), + border: Border.all( + color: Colors.black.withOpacity(0.03), + width: 0.7, + ), + ), + child: Row( + children: [ + Container( + width: 8, + height: 8, + decoration: BoxDecoration( + color: theme.colorScheme.primary, + shape: BoxShape.circle, + ), + ), + const SizedBox(width: 6), + Text( + 'Attivo', + style: theme.textTheme.labelSmall?.copyWith( + fontWeight: FontWeight.w600, + color: Colors.grey[800], + ), + ), + ], + ), + ), + Row( + children: [ + Icon( + Icons.access_time_rounded, + size: 16, + color: Colors.grey[800], + ), + const SizedBox(width: 4), + Text( + 'Ora', + style: theme.textTheme.labelMedium?.copyWith( + fontWeight: FontWeight.w500, + color: Colors.grey[900], + ), + ), + ], + ), + ], + ), + + const SizedBox(height: 14), + + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: 28, + height: 28, + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.9), + shape: BoxShape.circle, + border: Border.all( + color: Colors.black.withOpacity(0.03), + width: 0.7, + ), + ), + child: Icon( + Icons.stars_rounded, + size: 18, + color: theme.colorScheme.primary, + ), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '{app_data['main_card_text']}', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w700, + color: Colors.grey[900], + ), + ), + const SizedBox(height: 4), + Text( + '{app_data['main_card_detail']}', + style: theme.textTheme.bodySmall?.copyWith( + color: Colors.grey[700], + ), + ), + ], + ), + ), + ], + ), + + const SizedBox(height: 16), + + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: const [ + _MiniInfoPill( + icon: Icons.info_outline_rounded, + label: 'Info 1', + ), + SizedBox(width: 8), + _MiniInfoPill( + icon: Icons.check_circle_outline_rounded, + label: 'Info 2', + ), + ], + ), + TextButton.icon( + onPressed: () {{}}, + style: TextButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), + foregroundColor: Colors.grey[900], + ), + icon: const Icon(Icons.arrow_forward_rounded, size: 18), + label: Text( + 'Dettagli', + style: theme.textTheme.labelMedium?.copyWith( + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + ], + ), + ); + }} +}} + +class _MiniInfoPill extends StatelessWidget {{ + final IconData icon; + final String label; + + const _MiniInfoPill({{ + required this.icon, + required this.label, + }}); + + @override + Widget build(BuildContext context) {{ + final theme = Theme.of(context); + + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.9), + borderRadius: BorderRadius.circular(999), + border: Border.all( + color: Colors.black.withOpacity(0.04), + width: 0.7, + ), + ), + child: Row( + children: [ + Icon( + icon, + size: 14, + color: theme.colorScheme.primary, + ), + const SizedBox(width: 4), + Text( + label, + style: theme.textTheme.labelSmall?.copyWith( + fontWeight: FontWeight.w500, + color: Colors.grey[800], + ), + ), + ], + ), + ); + }} +}} + +/* ───────────────────────────── STAT CARD MODERNA ─────────────────────────────── */ + +class _StatCard extends StatelessWidget {{ + final String label; + final String value; + final IconData icon; + final String tag; + + const _StatCard({{ + required this.label, + required this.value, + required this.icon, + required this.tag, + }}); + + @override + Widget build(BuildContext context) {{ + final theme = Theme.of(context); + + return Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(20), + gradient: const LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + Color(0xFFFFFFFF), + Color(0xFFFFF3E0), + ], + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.03), + blurRadius: 14, + offset: const Offset(0, 8), + ), + ], + border: Border.all( + color: Colors.black.withOpacity(0.04), + width: 0.8, + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Container( + width: 32, + height: 32, + decoration: BoxDecoration( + color: const Color(0xFFFFE0B2), + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: Colors.black.withOpacity(0.04), + width: 0.7, + ), + ), + child: Icon( + icon, + size: 18, + color: theme.colorScheme.primary, + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(999), + border: Border.all( + color: Colors.black.withOpacity(0.04), + width: 0.7, + ), + ), + child: Text( + tag, + style: theme.textTheme.labelSmall?.copyWith( + fontWeight: FontWeight.w600, + color: Colors.grey[700], + ), + ), + ), + ], + ), + + const SizedBox(height: 10), + + Text( + value, + style: theme.textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.w800, + color: Colors.grey[900], + ), + ), + const SizedBox(height: 4), + + Text( + label, + style: theme.textTheme.bodySmall?.copyWith( + color: Colors.grey[600], + ), + ), + ], + ), + ); + }} +}} + +/* ───────────────────────── ILLUSTRAZIONE FLAT CARD ─────────────────────── */ + +class _IllustrationCard extends StatelessWidget {{ + const _IllustrationCard(); + + @override + Widget build(BuildContext context) {{ + final theme = Theme.of(context); + + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(22), + gradient: const LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + Color(0xFFFFFFFF), + Color(0xFFFFF0E3), + ], + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.03), + blurRadius: 16, + offset: const Offset(0, 8), + ), + ], + border: Border.all( + color: Colors.black.withOpacity(0.04), + width: 0.8, + ), + ), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '{app_data['suggestion_title']}', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w700, + color: Colors.grey[900], + ), + ), + const SizedBox(height: 6), + Text( + '{app_data['suggestion_text']}', + style: theme.textTheme.bodySmall?.copyWith( + color: Colors.grey[700], + ), + ), + const SizedBox(height: 8), + Text( + 'Suggerimento auto-generato', + style: theme.textTheme.labelSmall?.copyWith( + color: Colors.grey[600], + ), + ), + ], + ), + ), + const SizedBox(width: 12), + SizedBox( + width: 88, + height: 88, + child: Stack( + alignment: Alignment.center, + children: [ + Positioned( + top: 10, + child: Container( + width: 72, + height: 72, + decoration: BoxDecoration( + color: const Color(0xFFFFCC80), + shape: BoxShape.circle, + border: Border.all( + color: Colors.black.withOpacity(0.04), + width: 0.8, + ), + ), + ), + ), + Positioned( + bottom: 8, + child: Container( + width: 64, + height: 18, + decoration: BoxDecoration( + color: Colors.black.withOpacity(0.06), + borderRadius: BorderRadius.circular(20), + ), + ), + ), + Positioned( + top: 20, + child: Icon( + Icons.lightbulb_outline_rounded, + size: 40, + color: theme.colorScheme.primary, + ), + ), + Positioned( + right: 4, + top: 8, + child: Container( + width: 18, + height: 18, + decoration: BoxDecoration( + color: const Color(0xFFFFF59D), + shape: BoxShape.circle, + border: Border.all( + color: Colors.black.withOpacity(0.05), + width: 0.7, + ), + ), + child: const Icon( + Icons.flash_on_rounded, + size: 14, + color: Colors.orange, + ), + ), + ), + ], + ), + ), + ], + ), + ); + }} +}} + +/* ───────────────────────── GRAFICO (BAR CHART) ───────────────────────────── */ + +class _ChartCard extends StatelessWidget {{ + const _ChartCard(); + + @override + Widget build(BuildContext context) {{ + final theme = Theme.of(context); + + final days = ['L', 'M', 'M', 'G', 'V', 'S', 'D']; + final heights = [40.0, 58.0, 32.0, 72.0, 64.0, 50.0, 80.0]; + final selectedIndex = 6; + + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(22), + gradient: const LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + Color(0xFFFFFFFF), + Color(0xFFFFF3E0), + ], + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.03), + blurRadius: 16, + offset: const Offset(0, 8), + ), + ], + border: Border.all( + color: Colors.black.withOpacity(0.04), + width: 0.8, + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + '{app_data['chart_title']}', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w700, + color: Colors.grey[900], + ), + ), + Text( + 'Ultimi 7 giorni', + style: theme.textTheme.bodySmall?.copyWith( + color: Colors.grey[600], + ), + ), + ], + ), + + const SizedBox(height: 16), + + SizedBox( + height: 90, + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: List.generate(days.length, (index) {{ + final isSelected = index == selectedIndex; + final h = heights[index]; + + return Expanded( + child: Column( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + AnimatedContainer( + duration: const Duration(milliseconds: 250), + curve: Curves.easeOutQuad, + height: h, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(999), + gradient: LinearGradient( + begin: Alignment.bottomCenter, + end: Alignment.topCenter, + colors: isSelected + ? [ + Theme.of(context).colorScheme.primary, + const Color(0xFFFFE0B2), + ] + : [ + const Color(0xFFB0BEC5), + const Color(0xFFECEFF1), + ], + ), + border: Border.all( + color: Colors.black.withOpacity(0.03), + width: 0.6, + ), + ), + ), + ], + ), + ); + }}), + ), + ), + + const SizedBox(height: 8), + + Row( + children: List.generate(days.length, (index) {{ + final isSelected = index == selectedIndex; + return Expanded( + child: Center( + child: Text( + days[index], + style: theme.textTheme.labelSmall?.copyWith( + fontWeight: isSelected ? FontWeight.w700 : FontWeight.w500, + color: isSelected + ? theme.colorScheme.primary + : Colors.grey[600], + ), + ), + ), + ); + }}), + ), + ], + ), + ); + }} +}} + +/* ───────────────────────── MAPPA FINTA ────────────────────────── */ + +class _MapPreview extends StatelessWidget {{ + const _MapPreview(); + + @override + Widget build(BuildContext context) {{ + final theme = Theme.of(context); + + return Container( + height: 260, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(24), + gradient: const LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + Color(0xFFFFF3E0), + Color(0xFFFFEBEE), + ], + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.08), + blurRadius: 18, + offset: const Offset(0, 10), + ), + ], + border: Border.all( + color: Colors.black.withOpacity(0.05), + width: 0.9, + ), + ), + child: Stack( + children: [ + Positioned.fill( + child: CustomPaint( + painter: _MapRoadsPainter(), + ), + ), + + const Positioned( + left: 40, + top: 60, + child: _MapMarker( + label: 'Punto A', + color: Colors.deepOrange, + icon: Icons.location_on_rounded, + ), + ), + + const Positioned( + right: 40, + bottom: 70, + child: _MapMarker( + label: 'Punto B', + color: Colors.brown, + icon: Icons.flag_rounded, + ), + ), + + Positioned( + left: 16, + right: 16, + top: 16, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.9), + borderRadius: BorderRadius.circular(999), + border: Border.all( + color: Colors.black.withOpacity(0.05), + width: 0.7, + ), + ), + child: Row( + children: [ + Icon(Icons.route_rounded, + size: 18, color: theme.colorScheme.primary), + const SizedBox(width: 8), + Text( + 'Percorso stimato 3.2 km β€’ 9 min', + style: theme.textTheme.bodySmall?.copyWith( + fontWeight: FontWeight.w500, + color: Colors.grey[800], + ), + ), + ], + ), + ), + ), + + Positioned( + left: 16, + right: 16, + bottom: 16, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Mappa demo', + style: theme.textTheme.labelMedium?.copyWith( + color: Colors.grey[800], + ), + ), + Row( + children: [ + Icon(Icons.zoom_in_map_rounded, + size: 18, color: Colors.grey[700]), + const SizedBox(width: 4), + Text( + 'Non interattiva', + style: theme.textTheme.labelSmall?.copyWith( + color: Colors.grey[700], + ), + ), + ], + ), + ], + ), + ), + ], + ), + ); + }} +}} + +class _MapMarker extends StatelessWidget {{ + final String label; + final Color color; + final IconData icon; + + const _MapMarker({{ + required this.label, + required this.color, + required this.icon, + }}); + + @override + Widget build(BuildContext context) {{ + final theme = Theme.of(context); + + return Column( + children: [ + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.95), + borderRadius: BorderRadius.circular(999), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.1), + blurRadius: 10, + offset: const Offset(0, 4), + ), + ], + border: Border.all( + color: Colors.black.withOpacity(0.05), + width: 0.7, + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 16, color: color), + const SizedBox(width: 4), + Text( + label, + style: theme.textTheme.labelSmall?.copyWith( + fontWeight: FontWeight.w600, + color: Colors.grey[900], + ), + ), + ], + ), + ), + const SizedBox(height: 4), + Container( + width: 18, + height: 18, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + boxShadow: [ + BoxShadow( + color: color.withOpacity(0.6), + blurRadius: 14, + offset: const Offset(0, 4), + ), + ], + border: Border.all( + color: Colors.black.withOpacity(0.08), + width: 0.7, + ), + ), + ), + ], + ); + }} +}} + +class _MapRoadsPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final paintMain = Paint() + ..color = Colors.white.withOpacity(0.9) + ..style = PaintingStyle.stroke + ..strokeWidth = 8 + ..strokeCap = StrokeCap.round; + + final paintSecondary = Paint() + ..color = Colors.white.withOpacity(0.7) + ..style = PaintingStyle.stroke + ..strokeWidth = 5 + ..strokeCap = StrokeCap.round; + + final pathMain = Path() + ..moveTo(size.width * 0.15, size.height * 0.2) + ..quadraticBezierTo( + size.width * 0.4, + size.height * 0.1, + size.width * 0.65, + size.height * 0.3, + ) + ..quadraticBezierTo( + size.width * 0.9, + size.height * 0.5, + size.width * 0.7, + size.height * 0.8, + ); + + final pathSecondary = Path() + ..moveTo(size.width * 0.05, size.height * 0.7) + ..quadraticBezierTo( + size.width * 0.3, + size.height * 0.55, + size.width * 0.55, + size.height * 0.6, + ) + ..quadraticBezierTo( + size.width * 0.8, + size.height * 0.65, + size.width * 0.95, + size.height * 0.5, + ); + + canvas.drawPath(pathMain, paintMain); + canvas.drawPath(pathSecondary, paintSecondary); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}} + +/* ───────────────────────── STATUS CHIP ─────────────────────────────── */ + +class _StatusChip extends StatelessWidget {{ + final String label; + final bool selected; + final IconData icon; + + const _StatusChip({{ + required this.label, + required this.selected, + required this.icon, + }}); + + @override + Widget build(BuildContext context) {{ + final theme = Theme.of(context); + + final bgColor = selected + ? theme.colorScheme.primary.withOpacity(0.12) + : Colors.white; + final borderColor = selected + ? theme.colorScheme.primary + : Colors.grey[300]!; + + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(999), + color: bgColor, + border: Border.all(color: borderColor, width: 0.9), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + icon, + size: 18, + color: selected ? theme.colorScheme.primary : Colors.grey[700], + ), + const SizedBox(width: 6), + Text( + label, + style: theme.textTheme.bodyMedium?.copyWith( + fontWeight: FontWeight.w500, + ), + ), + if (selected) ...[ + const SizedBox(width: 4), + Container( + width: 6, + height: 6, + decoration: BoxDecoration( + color: theme.colorScheme.primary, + shape: BoxShape.circle, + ), + ), + ] + ], + ), + ); + }} +}} + +/* ───────────────────────── BOTTOM NAV ANIMATA ─────────────────────── */ + +class _BottomNavBar extends StatelessWidget {{ + final int currentIndex; + final ValueChanged onItemSelected; + + const _BottomNavBar({{ + super.key, + required this.currentIndex, + required this.onItemSelected, + }}); + + @override + Widget build(BuildContext context) {{ + final theme = Theme.of(context); + + const items = [ + _NavItemData(icon: Icons.home_rounded, label: 'Home'), + _NavItemData(icon: Icons.grid_view_rounded, label: 'Esplora'), + _NavItemData(icon: Icons.favorite_rounded, label: 'Preferiti'), + _NavItemData(icon: Icons.person_rounded, label: 'Profilo'), + ]; + + return Container( + height: 64, + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.96), + borderRadius: BorderRadius.circular(24), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.06), + blurRadius: 18, + offset: const Offset(0, 8), + ), + ], + border: Border.all( + color: Colors.black.withOpacity(0.05), + width: 0.9, + ), + ), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: List.generate(items.length, (index) {{ + final item = items[index]; + final selected = index == currentIndex; + + return _NavItem( + icon: item.icon, + label: item.label, + selected: selected, + onTap: () => onItemSelected(index), + theme: theme, + ); + }}), + ), + ); + }} +}} + +class _NavItemData {{ + final IconData icon; + final String label; + const _NavItemData({{required this.icon, required this.label}}); +}} + +class _NavItem extends StatelessWidget {{ + final IconData icon; + final String label; + final bool selected; + final VoidCallback onTap; + final ThemeData theme; + + const _NavItem({{ + required this.icon, + required this.label, + required this.selected, + required this.onTap, + required this.theme, + }}); + + @override + Widget build(BuildContext context) {{ + return InkWell( + borderRadius: BorderRadius.circular(999), + onTap: onTap, + child: AnimatedContainer( + duration: const Duration(milliseconds: 220), + curve: Curves.easeOutQuad, + padding: EdgeInsets.symmetric( + horizontal: selected ? 16 : 10, + vertical: 8, + ), + decoration: BoxDecoration( + color: selected + ? theme.colorScheme.primary.withOpacity(0.10) + : Colors.transparent, + borderRadius: BorderRadius.circular(999), + border: Border.all( + color: selected + ? theme.colorScheme.primary.withOpacity(0.3) + : Colors.transparent, + width: 0.9, + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + icon, + size: 22, + color: selected ? theme.colorScheme.primary : Colors.grey[600], + ), + if (selected) ...[ + const SizedBox(width: 6), + Text( + label, + style: theme.textTheme.labelMedium?.copyWith( + fontWeight: FontWeight.w600, + color: theme.colorScheme.primary, + ), + ), + ], + ], + ), + ), + ); + }} +}} + +/* ────────────────────── SFONDO WAVES BACKGROUND ───────────────────────── */ + +class _WavesBackgroundPainter extends CustomPainter {{ + @override + void paint(Canvas canvas, Size size) {{ + final basePaint = Paint() + ..shader = const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + Color(0xFFFFF8F3), + Color(0xFFFFF0E3), + Color(0xFFFFF8F0), + ], + ).createShader(Rect.fromLTWH(0, 0, size.width, size.height)); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), basePaint); + + final paintTop = Paint() + ..color = const Color(0xFFFFCC80).withOpacity(0.55) + ..style = PaintingStyle.fill; + + final pathTop = Path() + ..moveTo(0, size.height * 0.12) + ..quadraticBezierTo( + size.width * 0.25, + size.height * 0.05, + size.width * 0.5, + size.height * 0.12, + ) + ..quadraticBezierTo( + size.width * 0.78, + size.height * 0.19, + size.width, + size.height * 0.11, + ) + ..lineTo(size.width, 0) + ..lineTo(0, 0) + ..close(); + + canvas.drawPath(pathTop, paintTop); + + final paintMid = Paint() + ..color = const Color(0xFFFFAB91).withOpacity(0.40) + ..style = PaintingStyle.fill; + + final pathMid = Path() + ..moveTo(0, size.height * 0.45) + ..quadraticBezierTo( + size.width * 0.25, + size.height * 0.40, + size.width * 0.5, + size.height * 0.46, + ) + ..quadraticBezierTo( + size.width * 0.78, + size.height * 0.52, + size.width, + size.height * 0.44, + ) + ..lineTo(size.width, size.height * 0.25) + ..lineTo(0, size.height * 0.25) + ..close(); + + canvas.drawPath(pathMid, paintMid); + + final paintBottom = Paint() + ..color = const Color(0xFFFFE082).withOpacity(0.38) + ..style = PaintingStyle.fill; + + final pathBottom = Path() + ..moveTo(0, size.height * 0.85) + ..quadraticBezierTo( + size.width * 0.2, + size.height * 0.78, + size.width * 0.45, + size.height * 0.83, + ) + ..quadraticBezierTo( + size.width * 0.75, + size.height * 0.89, + size.width, + size.height * 0.82, + ) + ..lineTo(size.width, size.height) + ..lineTo(0, size.height) + ..close(); + + canvas.drawPath(pathBottom, paintBottom); + }} + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +}} +''' + + return code + + def _lighten_color(self, hex_color: str) -> str: + """Lighten a hex color (with FF prefix) for gradient effects""" + # Simple lightening: increase RGB values + if len(hex_color) != 8: + return hex_color + + try: + r = int(hex_color[2:4], 16) + g = int(hex_color[4:6], 16) + b = int(hex_color[6:8], 16) + + # Lighten by 30% + r = min(255, int(r + (255 - r) * 0.3)) + g = min(255, int(g + (255 - g) * 0.3)) + b = min(255, int(b + (255 - b) * 0.3)) + + return f"FF{r:02X}{g:02X}{b:02X}" + except: + return hex_color + + def _get_app_specific_data(self, app_type: str) -> Dict[str, Any]: + """Get app-specific data (titles, stats, icons) based on app type""" + + app_configs = { + "rider": { + "app_class": "RiderApp", + "title": "Rider Demo", + "greeting": "Ciao,", + "subtitle": "Pronto per consegnare?", + "main_card_title": "Prossima consegna", + "stat1_label": "Consegne", + "stat1_value": "8", + "stat1_icon": "Icons.delivery_dining_rounded", + "stat2_label": "Guadagno", + "stat2_value": "€42,50", + "stat2_icon": "Icons.euro_rounded", + "stat3_label": "Tempo online", + "stat3_value": "03:18 h", + "stat3_icon": "Icons.access_time_rounded", + "stat4_label": "Rating", + "stat4_value": "4.9β˜…", + "stat4_icon": "Icons.star_rate_rounded", + "map_title": "Mappa consegne" + }, + "fitness": { + "app_class": "FitnessApp", + "title": "Fitness Tracker", + "greeting": "Ciao,", + "subtitle": "Pronto ad allenarti?", + "main_card_title": "Prossimo allenamento", + "stat1_label": "Calorie", + "stat1_value": "1.240", + "stat1_icon": "Icons.local_fire_department_rounded", + "stat2_label": "Passi", + "stat2_value": "8.542", + "stat2_icon": "Icons.directions_walk_rounded", + "stat3_label": "Tempo attivo", + "stat3_value": "02:15 h", + "stat3_icon": "Icons.timer_rounded", + "stat4_label": "Obiettivo", + "stat4_value": "85%", + "stat4_icon": "Icons.flag_rounded", + "map_title": "Percorso allenamento" + }, + "banking": { + "app_class": "BankingApp", + "title": "Banking App", + "greeting": "Benvenuto,", + "subtitle": "Gestisci il tuo denaro", + "main_card_title": "Ultima transazione", + "stat1_label": "Saldo", + "stat1_value": "€3.420", + "stat1_icon": "Icons.account_balance_wallet_rounded", + "stat2_label": "Spese mese", + "stat2_value": "€1.240", + "stat2_icon": "Icons.trending_down_rounded", + "stat3_label": "Risparmi", + "stat3_value": "€5.680", + "stat3_icon": "Icons.savings_rounded", + "stat4_label": "Transazioni", + "stat4_value": "24", + "stat4_icon": "Icons.receipt_long_rounded", + "map_title": "ATM vicini" + }, + "ecommerce": { + "app_class": "ShopApp", + "title": "Shop App", + "greeting": "Ciao,", + "subtitle": "Trova il prodotto perfetto", + "main_card_title": "Offerta del giorno", + "stat1_label": "Ordini", + "stat1_value": "12", + "stat1_icon": "Icons.shopping_bag_rounded", + "stat2_label": "Totale speso", + "stat2_value": "€420", + "stat2_icon": "Icons.euro_rounded", + "stat3_label": "Punti fedeltΓ ", + "stat3_value": "1.240", + "stat3_icon": "Icons.loyalty_rounded", + "stat4_label": "Preferiti", + "stat4_value": "38", + "stat4_icon": "Icons.favorite_rounded", + "map_title": "Negozi vicini" + }, + "social": { + "app_class": "SocialApp", + "title": "Social App", + "greeting": "Ciao,", + "subtitle": "Cosa c'Γ¨ di nuovo?", + "main_card_title": "Post in evidenza", + "stat1_label": "Post", + "stat1_value": "142", + "stat1_icon": "Icons.post_add_rounded", + "stat2_label": "Follower", + "stat2_value": "1.2k", + "stat2_icon": "Icons.people_rounded", + "stat3_label": "Like ricevuti", + "stat3_value": "3.8k", + "stat3_icon": "Icons.favorite_rounded", + "stat4_label": "Messaggi", + "stat4_value": "24", + "stat4_icon": "Icons.chat_bubble_rounded", + "map_title": "Amici vicini" + } + } + + return app_configs.get(app_type, app_configs["fitness"]) + + def _generate_simple_fallback(self, theme: Dict[str, Any], screen_type: str) -> str: + """Generate simple fallback code when AI planning fails""" + + return f'''import 'package:flutter/material.dart'; + +void main() => runApp(MyApp()); + +class MyApp extends StatelessWidget {{ + @override + Widget build(BuildContext context) {{ + return MaterialApp( + home: Scaffold( + appBar: AppBar(title: Text('{screen_type.capitalize()}')), + body: Center( + child: Text('Screen: {screen_type}'), + ), + ), + ); + }} +}} +'''