<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OllamaDiffuser Web UI</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 16px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .header p {
            opacity: 0.9;
            font-size: 1.1em;
        }
        
        .status-bar {
            background: #f8fafc;
            padding: 20px 30px;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .status-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
        }
        
        .status-loaded {
            background: #10b981;
        }
        
        .status-unloaded {
            background: #ef4444;
        }
        
        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            padding: 30px;
        }
        
        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }
        }
        
        .form-section {
            background: #f8fafc;
            padding: 25px;
            border-radius: 12px;
            border: 1px solid #e2e8f0;
        }
        
        .form-section h2 {
            color: #1e293b;
            margin-bottom: 20px;
            font-size: 1.5em;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #374151;
            font-weight: 500;
        }
        
        .form-group input, 
        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.2s;
        }
        
        .form-group input:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #4f46e5;
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }
        
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }
        
        .btn {
            background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
            width: 100%;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(79, 70, 229, 0.3);
        }
        
        .btn:disabled {
            background: #9ca3af;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        .result-section {
            text-align: center;
        }
        
        .result-image {
            max-width: 100%;
            border-radius: 12px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .error-message {
            background: #fee2e2;
            color: #dc2626;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 1px solid #fecaca;
        }
        
        .success-message {
            background: #d1fae5;
            color: #065f46;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 1px solid #a7f3d0;
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 40px;
            color: #6b7280;
        }
        
        .loading.show {
            display: block;
        }
        
        .spinner {
            border: 3px solid #f3f4f6;
            border-top: 3px solid #4f46e5;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .model-info {
            background: #e0f2fe;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 1px solid #b3e5fc;
        }
        
        .model-management {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 30px;
        }
        
        .model-controls {
            display: flex;
            gap: 10px;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .model-controls select {
            flex: 1;
            min-width: 200px;
            padding: 8px 12px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            background: white;
        }
        
        .btn-small {
            background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
            white-space: nowrap;
        }
        
        .btn-small:hover {
            transform: translateY(-1px);
            box-shadow: 0 5px 15px rgba(79, 70, 229, 0.3);
        }
        
        .btn-small.btn-danger {
            background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
        }
        
        .btn-small.btn-danger:hover {
            box-shadow: 0 5px 15px rgba(220, 38, 38, 0.3);
        }
        
        .controlnet-results {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }
        
        @media (max-width: 768px) {
            .controlnet-results {
                grid-template-columns: 1fr;
                gap: 15px;
            }
        }
        
        .controlnet-section {
            background: #f0f9ff;
            border: 1px solid #0ea5e9;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
        }
        
        .controlnet-title {
            color: #0369a1;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .file-input {
            width: 100%;
            padding: 12px;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 14px;
            background: white;
            cursor: pointer;
        }
        
        .file-input:hover {
            border-color: #4f46e5;
        }
        
        .help-text {
            color: #6b7280;
            margin-top: 5px;
            display: block;
            font-size: 12px;
        }
        
        .sample-item {
            cursor: pointer;
            border: 2px solid #e5e7eb;
            border-radius: 6px;
            padding: 8px;
            background: white;
            transition: all 0.2s;
        }
        
        .sample-item:hover {
            border-color: #7c3aed;
            box-shadow: 0 4px 8px -2px rgba(0, 0, 0, 0.1);
        }
        
        .sample-item img {
            width: 100%;
            height: 100px;
            object-fit: cover;
            border-radius: 4px;
            margin-bottom: 6px;
        }
        
        .sample-item div {
            text-align: center;
        }
        
        .sample-item div div {
            font-weight: 600;
            color: #374151;
            font-size: 14px;
            margin-bottom: 4px;
        }
        
        .sample-item div p {
            color: #6b7280;
            font-size: 12px;
            line-height: 1.3;
            margin-bottom: 6px;
        }
        
        .sample-item div div span {
            background: #e0e7ff;
            color: #3730a3;
            padding: 2px 6px;
            border-radius: 12px;
            font-size: 10px;
        }
        
        .control-tab {
            padding: 8px 12px;
            border: none;
            background: #f8fafc;
            border-bottom: 2px solid transparent;
            cursor: pointer;
            font-size: 13px;
            color: #6b7280;
            transition: all 0.2s;
        }
        
        .control-tab:hover {
            background: #e2e8f0;
        }
        
        .active-tab {
            border-bottom: 2px solid #7c3aed !important;
            color: #374151 !important;
            font-weight: 500;
        }
        
        .tab-content {
            min-height: 80px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎨 OllamaDiffuser</h1>
            <p>Image Generation Model Management Tool &mdash; v2.0.0</p>
        </div>
        
        <div class="status-bar">
            <div class="status-item">
                <div class="status-indicator {{ 'status-loaded' if model_loaded else 'status-unloaded' }}"></div>
                <span>Model Status: {{ 'Loaded' if model_loaded else 'Not Loaded' }}</span>
            </div>
            {% if current_model %}
            <div class="status-item">
                <span>Current Model: <strong>{{ current_model }}</strong></span>
                {% if is_controlnet_model %}
                <span style="color: #7c3aed; font-weight: bold; margin-left: 8px;">🎛️ ControlNet ({{ controlnet_type }})</span>
                {% endif %}
                {% if model_parameters %}
                <div style="margin-top: 5px; font-size: 12px; color: #6b7280;">
                    📋 Recommended: 
                    {% if model_parameters.num_inference_steps %}Steps: {{ model_parameters.num_inference_steps }}{% endif %}
                    {% if model_parameters.guidance_scale %} | Guidance: {{ model_parameters.guidance_scale }}{% endif %}
                </div>
                {% endif %}
            </div>
            {% endif %}
            <div class="status-item">
                <span>Installed Models: {{ installed_models|length }}</span>
            </div>
            <div class="status-item">
                <div class="status-indicator {{ 'status-loaded' if current_lora else 'status-unloaded' }}"></div>
                <span>LoRA Status: {{ 'Loaded' if current_lora else 'Not Loaded' }}</span>
            </div>
            {% if current_lora %}
            <div class="status-item">
                <span>Current LoRA: <strong>{{ current_lora }}</strong></span>
            </div>
            {% endif %}
            <div class="status-item">
                <span>Installed LoRAs: {{ installed_loras|length }}</span>
            </div>
        </div>
        
        <div class="model-management">
            <h3>🔧 Model Management</h3>
            {% if installed_models %}
            <form method="post" action="/load_model" style="margin-bottom: 15px;">
                <div class="model-controls">
                    <select name="model_name" required>
                        <option value="">Select model to load...</option>
                        {% for model in installed_models %}
                        <option value="{{ model }}" {{ 'selected' if model == current_model else '' }}>{{ model }}</option>
                        {% endfor %}
                    </select>
                    <button type="submit" class="btn-small">🚀 Load Model</button>
                </div>
            </form>
            {% endif %}
            
            {% if model_loaded %}
            <form method="post" action="/unload_model">
                <button type="submit" class="btn-small btn-danger">🔄 Unload Current Model</button>
            </form>
            {% endif %}
            
            {% if not installed_models %}
            <div class="model-info">
                <strong>📥 No installed models</strong><br>
                Please install models using CLI: <code>ollamadiffuser pull model-name</code>
            </div>
            {% endif %}
        </div>
        
        <div class="model-management">
            <h3>🔄 LoRA Management(style, content, or identity)</h3>
            
            <!-- Download LoRA Section -->
            <form method="post" action="/pull_lora" style="margin-bottom: 15px;">
                <div style="display: grid; grid-template-columns: 2fr 1fr 1fr auto; gap: 10px; align-items: end;">
                    <div>
                        <label for="repo_id" style="display: block; margin-bottom: 5px; font-size: 12px; color: #6b7280;">Hugging Face Repository ID</label>
                        <input type="text" name="repo_id" id="repo_id" placeholder="e.g.: openfree/flux-chatgpt-ghibli-lora" required style="width: 100%; padding: 8px 12px; border: 1px solid #d1d5db; border-radius: 6px; background: white; font-size: 14px;">
                    </div>
                    <div>
                        <label for="weight_name" style="display: block; margin-bottom: 5px; font-size: 12px; color: #6b7280;">Weight File Name (Optional)</label>
                        <input type="text" name="weight_name" id="weight_name" placeholder="e.g.: lora.safetensors" style="width: 100%; padding: 8px 12px; border: 1px solid #d1d5db; border-radius: 6px; background: white; font-size: 14px;">
                    </div>
                    <div>
                        <label for="alias" style="display: block; margin-bottom: 5px; font-size: 12px; color: #6b7280;">Alias (Optional)</label>
                        <input type="text" name="alias" id="alias" placeholder="e.g.: ghibli" style="width: 100%; padding: 8px 12px; border: 1px solid #d1d5db; border-radius: 6px; background: white; font-size: 14px;">
                    </div>
                    <button type="submit" class="btn-small">📥 Download LoRA</button>
                </div>
            </form>
            
            <!-- Load LoRA Section -->
            {% if installed_loras %}
            <form method="post" action="/load_lora" style="margin-bottom: 15px;">
                <div class="model-controls">
                    <select name="lora_name" required style="flex: 2;">
                        <option value="">Select LoRA to load...</option>
                        {% for lora_name, lora_info in installed_loras.items() %}
                        <option value="{{ lora_name }}" {{ 'selected' if lora_name == current_lora else '' }}>
                            {{ lora_name }} ({{ lora_info.get('repo_id', 'Unknown') }})
                        </option>
                        {% endfor %}
                    </select>
                    <div style="display: flex; flex-direction: column; min-width: 100px;">
                        <label for="scale" style="font-size: 12px; color: #6b7280; margin-bottom: 2px;">Strength</label>
                        <input type="number" name="scale" id="scale" value="1.0" min="0.1" max="2.0" step="0.1" style="padding: 8px 12px; border: 1px solid #d1d5db; border-radius: 6px; background: white; font-size: 14px;">
                    </div>
                    <button type="submit" class="btn-small" {{ 'disabled' if not model_loaded }}>🚀 Load LoRA</button>
                </div>
            </form>
            {% endif %}
            
            <!-- Unload LoRA Section -->
            {% if current_lora %}
            <form method="post" action="/unload_lora">
                <button type="submit" class="btn-small btn-danger">🔄 Unload Current LoRA</button>
            </form>
            {% endif %}
            
            <!-- LoRA Status -->
            {% if not installed_loras %}
            <div class="model-info">
                <strong>📥 No installed LoRAs</strong><br>
                Please enter a Hugging Face repository ID above to download LoRA, or use CLI: <code>ollamadiffuser lora pull repo-id</code>
            </div>
            {% endif %}
            
            {% if installed_loras and not model_loaded %}
            <div class="model-info">
                <strong>⚠️ Note:</strong> You need to load a model first before using LoRA
            </div>
            {% endif %}
        </div>
        
        <div class="main-content">
            <div class="form-section">
                <h2>Image Generation</h2>
                
                {% if not model_loaded %}
                <div class="model-info">
                    <strong>⚠️ Note:</strong> Please first load a model in the model management area above, or use CLI: <code>ollamadiffuser load model-name</code>
                </div>
                {% endif %}
                
                {% if success_message %}
                <div class="success-message">
                    {{ success_message }}
                </div>
                {% endif %}
                
                {% if error_message %}
                <div class="error-message">
                    {{ error_message }}
                </div>
                {% endif %}
                
                <form method="post" action="/generate" id="generateForm" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="prompt">Prompt</label>
                        <textarea name="prompt" id="prompt" rows="3" placeholder="Describe the image you want to generate..." required>{{ prompt or '' }}</textarea>
                    </div>
                    
                    <div class="form-group">
                        <label for="negative_prompt">Negative Prompt</label>
                        <textarea name="negative_prompt" id="negative_prompt" rows="2" placeholder="Describe what you don't want in the image...">{{ negative_prompt or 'low quality, bad anatomy, worst quality, low resolution' }}</textarea>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label for="width">Width</label>
                            <input type="number" name="width" id="width" value="{{ width or model_parameters.get('width', 1024) }}" min="512" max="2048" step="64">
                            {% if model_parameters.get('width') %}
                            <small class="help-text">📋 Recommended for {{ current_model }}: {{ model_parameters.width }}px</small>
                            {% endif %}
                        </div>
                        <div class="form-group">
                            <label for="height">Height</label>
                            <input type="number" name="height" id="height" value="{{ height or model_parameters.get('height', 1024) }}" min="512" max="2048" step="64">
                            {% if model_parameters.get('height') %}
                            <small class="help-text">📋 Recommended for {{ current_model }}: {{ model_parameters.height }}px</small>
                            {% endif %}
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label for="num_inference_steps">Inference Steps</label>
                            <input type="number" name="num_inference_steps" id="num_inference_steps" value="{{ num_inference_steps or model_parameters.get('num_inference_steps', 28) }}" min="1" max="100">
                            {% if model_parameters.get('num_inference_steps') %}
                            <small class="help-text">📋 Recommended for {{ current_model }}: {{ model_parameters.num_inference_steps }}</small>
                            {% endif %}
                        </div>
                        <div class="form-group">
                            <label for="guidance_scale">Guidance Scale</label>
                            <input type="number" name="guidance_scale" id="guidance_scale" value="{{ guidance_scale or model_parameters.get('guidance_scale', 3.5) }}" min="0" max="20" step="0.1">
                            {% if model_parameters.get('guidance_scale') %}
                            <small class="help-text">📋 Recommended for {{ current_model }}: {{ model_parameters.guidance_scale }}</small>
                            {% endif %}
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="seed">Seed (optional, leave empty for random)</label>
                        <input type="number" name="seed" id="seed" value="{{ seed or '' }}" min="0" max="4294967295" placeholder="Random">
                        <small class="help-text">Set a seed for reproducible results</small>
                    </div>
                    
                    <!-- ControlNet Section -->
                    {% if is_controlnet_model %}
                    <div class="controlnet-section">
                        <h3 class="controlnet-title">
                            🎛️ ControlNet Controls(structure, composition, and spatial layout) ({{ controlnet_type|title }})
                        </h3>
                        
                        <!-- ControlNet Status (Compact) -->
                        {% if not controlnet_initialized %}
                        <div style="background: #fef3c7; border: 1px solid #f59e0b; border-radius: 4px; padding: 8px; margin-bottom: 10px; font-size: 12px;">
                            <span style="color: #92400e;">⚠️ Not initialized</span>
                            <button type="button" onclick="initializeControlNet()" style="margin-left: 10px; padding: 4px 8px; background: #f59e0b; color: white; border: none; border-radius: 3px; cursor: pointer; font-size: 11px;">
                                Initialize
                            </button>
                        </div>
                        {% else %}
                        <div style="background: #d1fae5; border: 1px solid #10b981; border-radius: 4px; padding: 6px; margin-bottom: 10px; font-size: 12px; color: #065f46;">
                            ✅ Ready
                        </div>
                        {% endif %}
                        
                        <!-- Tabbed Interface -->
                        <div style="margin-bottom: 15px;">
                            <div style="display: flex; border-bottom: 1px solid #e5e7eb; margin-bottom: 10px;">
                                <button type="button" onclick="switchControlTab('upload')" id="uploadTab" class="control-tab active-tab" style="flex: 1; padding: 8px 12px; border: none; background: #f8fafc; border-bottom: 2px solid #7c3aed; cursor: pointer; font-size: 13px; font-weight: 500;">
                                    📁 Upload Image
                                </button>
                                <button type="button" onclick="switchControlTab('samples')" id="samplesTab" class="control-tab" style="flex: 1; padding: 8px 12px; border: none; background: #f8fafc; border-bottom: 2px solid transparent; cursor: pointer; font-size: 13px; color: #6b7280;">
                                    🎨 Samples ({{ sample_metadata[controlnet_type]|length if sample_metadata and controlnet_type in sample_metadata else 0 }})
                                </button>
                                <button type="button" onclick="switchControlTab('settings')" id="settingsTab" class="control-tab" style="flex: 1; padding: 8px 12px; border: none; background: #f8fafc; border-bottom: 2px solid transparent; cursor: pointer; font-size: 13px; color: #6b7280;">
                                    ⚙️ Settings
                                </button>
                            </div>
                            
                            <!-- Upload Tab -->
                            <div id="uploadTabContent" class="tab-content">
                                <div class="form-group" style="margin-bottom: 10px;">
                                    <input type="file" name="control_image" id="control_image" accept="image/*" class="file-input" style="padding: 8px; font-size: 13px;">
                                    <small class="help-text" style="font-size: 11px;">Upload image for {{ controlnet_type }} control</small>
                                </div>
                            </div>
                            
                            <!-- Samples Tab -->
                            <div id="samplesTabContent" class="tab-content" style="display: none;">
                                {% if sample_metadata and controlnet_type in sample_metadata %}
                                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 8px; max-height: 200px; overflow-y: auto;">
                                    {% for filename, metadata in sample_metadata[controlnet_type].items() %}
                                    <div class="sample-item" onclick="loadSampleImage('{{ controlnet_type }}', '{{ filename }}')" style="padding: 6px;">
                                        <img src="/samples/{{ controlnet_type }}/{{ filename }}" alt="{{ metadata.title }}" style="width: 100%; height: 80px; object-fit: cover; border-radius: 3px; margin-bottom: 4px;">
                                        <div style="text-align: center; font-size: 10px; color: #374151; font-weight: 500;">{{ metadata.title }}</div>
                                    </div>
                                    {% endfor %}
                                </div>
                                {% else %}
                                <p style="color: #6b7280; font-size: 12px; text-align: center; margin: 20px 0;">No samples available</p>
                                {% endif %}
                            </div>
                            
                            <!-- Settings Tab -->
                            <div id="settingsTabContent" class="tab-content" style="display: none;">
                                <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px;">
                                    <div>
                                        <label style="font-size: 11px; color: #374151; display: block; margin-bottom: 3px;">Strength</label>
                                        <input type="number" name="controlnet_conditioning_scale" id="controlnet_conditioning_scale" value="{{ controlnet_conditioning_scale or 1.0 }}" min="0.0" max="2.0" step="0.1" style="width: 100%; padding: 4px 6px; font-size: 12px; border: 1px solid #d1d5db; border-radius: 3px;">
                                    </div>
                                    <div>
                                        <label style="font-size: 11px; color: #374151; display: block; margin-bottom: 3px;">Start</label>
                                        <input type="number" name="control_guidance_start" id="control_guidance_start" value="{{ control_guidance_start or 0.0 }}" min="0.0" max="1.0" step="0.1" style="width: 100%; padding: 4px 6px; font-size: 12px; border: 1px solid #d1d5db; border-radius: 3px;">
                                    </div>
                                    <div>
                                        <label style="font-size: 11px; color: #374151; display: block; margin-bottom: 3px;">End</label>
                                        <input type="number" name="control_guidance_end" id="control_guidance_end" value="{{ control_guidance_end or 1.0 }}" min="0.0" max="1.0" step="0.1" style="width: 100%; padding: 4px 6px; font-size: 12px; border: 1px solid #d1d5db; border-radius: 3px;">
                                    </div>
                                </div>
                                <div style="margin-top: 8px; padding: 6px; background: #f0f9ff; border-radius: 3px; font-size: 10px; color: #0369a1;">
                                    💡 Strength: How much control to apply | Start/End: When to apply control during generation
                                </div>
                            </div>
                        </div>
                    </div>
                    {% endif %}
                    
                    <button type="submit" class="btn" {{ 'disabled' if not model_loaded }}>
                        🎨 Generate Image
                    </button>
                </form>

                <!-- img2img Section -->
                <details style="margin-top: 20px;">
                    <summary style="cursor: pointer; font-weight: 600; color: #374151; padding: 10px 0;">🖼️ Image-to-Image (img2img)</summary>
                    <form method="post" action="/generate/img2img" enctype="multipart/form-data" style="margin-top: 10px;">
                        <div class="form-group">
                            <label for="img2img_prompt">Prompt</label>
                            <textarea name="prompt" id="img2img_prompt" rows="2" placeholder="Describe the desired output..." required></textarea>
                        </div>
                        <div class="form-group">
                            <label for="img2img_image">Input Image</label>
                            <input type="file" name="image" id="img2img_image" accept="image/*" class="file-input" required>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="img2img_strength">Strength</label>
                                <input type="number" name="strength" id="img2img_strength" value="0.75" min="0.0" max="1.0" step="0.05">
                                <small class="help-text">Higher = more change from original</small>
                            </div>
                            <div class="form-group">
                                <label for="img2img_steps">Steps</label>
                                <input type="number" name="num_inference_steps" id="img2img_steps" value="{{ model_parameters.get('num_inference_steps', 28) }}" min="1" max="100">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="img2img_guidance">Guidance Scale</label>
                                <input type="number" name="guidance_scale" id="img2img_guidance" value="{{ model_parameters.get('guidance_scale', 3.5) }}" min="0" max="20" step="0.1">
                            </div>
                            <div class="form-group">
                                <label for="img2img_seed">Seed</label>
                                <input type="number" name="seed" id="img2img_seed" placeholder="Random" min="0" max="4294967295">
                            </div>
                        </div>
                        <input type="hidden" name="negative_prompt" value="low quality, bad anatomy, worst quality, low resolution">
                        <button type="submit" class="btn" {{ 'disabled' if not model_loaded }}>
                            🖼️ Generate img2img
                        </button>
                    </form>
                </details>
            </div>
            
            <div class="result-section">
                <h2>Generation Result</h2>
                
                <div class="loading" id="loading">
                    <div class="spinner"></div>
                    <p>Generating image, please wait...</p>
                </div>
                
                {% if control_image_b64 and image_b64 %}
                <!-- ControlNet Results: Show control image and generated image side by side -->
                <div class="controlnet-results">
                    <div>
                        <h3 style="color: #374151; margin-bottom: 10px; text-align: center;">🎛️ Control Image</h3>
                        <img src="data:image/png;base64,{{ control_image_b64 }}" alt="Control Image" class="result-image">
                        <p style="color: #6b7280; text-align: center; font-size: 14px; margin-top: 10px;">
                            Preprocessed for {{ controlnet_type }} control
                        </p>
                    </div>
                    <div>
                        <h3 style="color: #374151; margin-bottom: 10px; text-align: center;">🎨 Generated Image</h3>
                        <img src="data:image/png;base64,{{ image_b64 }}" alt="Generated Image" class="result-image">
                        <p style="color: #6b7280; text-align: center; font-size: 14px; margin-top: 10px;">
                            Conditioning Scale: {{ controlnet_conditioning_scale }}
                        </p>
                    </div>
                </div>
                <p style="color: #6b7280; margin-top: 15px; text-align: center;">
                    <strong>Prompt:</strong> {{ prompt }}
                </p>
                {% elif input_image_b64 and image_b64 %}
                <!-- img2img Results -->
                <div class="controlnet-results">
                    <div>
                        <h3 style="color: #374151; margin-bottom: 10px; text-align: center;">🖼️ Input Image</h3>
                        <img src="data:image/png;base64,{{ input_image_b64 }}" alt="Input Image" class="result-image">
                    </div>
                    <div>
                        <h3 style="color: #374151; margin-bottom: 10px; text-align: center;">🎨 Generated Image</h3>
                        <img src="data:image/png;base64,{{ image_b64 }}" alt="Generated Image" class="result-image">
                    </div>
                </div>
                <p style="color: #6b7280; margin-top: 15px; text-align: center;">
                    <strong>Prompt:</strong> {{ prompt }}
                </p>
                {% elif image_b64 %}
                <!-- Regular Generation Result -->
                <img src="data:image/png;base64,{{ image_b64 }}" alt="Generated Image" class="result-image">
                <p style="color: #6b7280; margin-top: 15px;">
                    <strong>Prompt:</strong> {{ prompt }}
                </p>
                {% else %}
                <div style="background: #f9fafb; border: 2px dashed #d1d5db; border-radius: 12px; padding: 60px 20px; color: #6b7280;">
                    <div style="font-size: 3em; margin-bottom: 15px;">🖼️</div>
                    <p>Generated image will be displayed here</p>
                    {% if is_controlnet_model %}
                    <p style="margin-top: 10px; font-size: 14px;">
                        💡 Upload a control image to guide the generation process
                    </p>
                    {% endif %}
                </div>
                {% endif %}
            </div>
        </div>
    </div>
    
    <script>
        document.getElementById('generateForm').addEventListener('submit', function() {
            document.getElementById('loading').classList.add('show');
        });
        
        async function initializeControlNet() {
            const button = event.target;
            const originalText = button.textContent;
            
            // Show loading state
            button.textContent = 'Initializing...';
            button.disabled = true;
            
            try {
                // Call the initialization endpoint
                const response = await fetch('/api/controlnet/initialize', {
                    method: 'POST'
                });
                const data = await response.json();
                
                if (data.success && data.initialized) {
                    // Reload page to update UI
                    window.location.reload();
                } else {
                    alert(data.message || 'Failed to initialize ControlNet preprocessors. Please check the console for errors.');
                    button.textContent = originalText;
                    button.disabled = false;
                }
            } catch (error) {
                console.error('Error initializing ControlNet:', error);
                alert('Error initializing ControlNet preprocessors.');
                button.textContent = originalText;
                button.disabled = false;
            }
        }
        
        function switchControlTab(tab) {
            // Remove active class from all tabs
            const tabs = document.querySelectorAll('.control-tab');
            tabs.forEach(t => t.classList.remove('active-tab'));
            
            // Add active class to the clicked tab
            const clickedTab = document.getElementById(tab + 'Tab');
            clickedTab.classList.add('active-tab');
            
            // Hide all tab contents
            const contents = document.querySelectorAll('.tab-content');
            contents.forEach(content => content.style.display = 'none');
            
            // Show the selected tab content
            const selectedContent = document.getElementById(tab + 'TabContent');
            if (selectedContent) {
                selectedContent.style.display = 'block';
            }
        }
        
        // Initialize the first tab as active when page loads
        document.addEventListener('DOMContentLoaded', function() {
            const uploadContent = document.getElementById('uploadTabContent');
            if (uploadContent) {
                uploadContent.style.display = 'block';
            }
        });
        
        async function loadSampleImage(controlnetType, filename) {
            try {
                // Fetch the sample image
                const response = await fetch(`/samples/${controlnetType}/${filename}`);
                if (!response.ok) {
                    throw new Error('Failed to load sample image');
                }
                
                // Convert to blob and create file object
                const blob = await response.blob();
                const file = new File([blob], filename, { type: blob.type });
                
                // Create a DataTransfer object to simulate file selection
                const dataTransfer = new DataTransfer();
                dataTransfer.items.add(file);
                
                // Set the file input
                const fileInput = document.getElementById('control_image');
                fileInput.files = dataTransfer.files;
                
                // Trigger change event to update any listeners
                const changeEvent = new Event('change', { bubbles: true });
                fileInput.dispatchEvent(changeEvent);
                
                // Visual feedback - find the clicked sample item
                const sampleItems = document.querySelectorAll('.sample-item');
                sampleItems.forEach(item => item.style.borderColor = '#e5e7eb');
                
                // Find the clicked sample item by looking for the image with matching src
                const clickedImg = document.querySelector(`img[src="/samples/${controlnetType}/${filename}"]`);
                if (clickedImg) {
                    const sampleItem = clickedImg.closest('.sample-item');
                    if (sampleItem) {
                        sampleItem.style.borderColor = '#7c3aed';
                    }
                }
                
                // Show success message
                const successDiv = document.createElement('div');
                successDiv.style.cssText = 'position: fixed; top: 20px; right: 20px; background: #10b981; color: white; padding: 12px 20px; border-radius: 6px; z-index: 1000; font-size: 14px;';
                successDiv.textContent = `✅ Sample "${filename.replace('.png', '').replace(/_/g, ' ')}" loaded!`;
                document.body.appendChild(successDiv);
                
                setTimeout(() => {
                    successDiv.remove();
                }, 3000);
                
            } catch (error) {
                console.error('Error loading sample image:', error);
                
                // Show detailed error message
                const errorDiv = document.createElement('div');
                errorDiv.style.cssText = 'position: fixed; top: 20px; right: 20px; background: #dc2626; color: white; padding: 12px 20px; border-radius: 6px; z-index: 1000; font-size: 14px;';
                errorDiv.textContent = `❌ Failed to load sample: ${error.message}`;
                document.body.appendChild(errorDiv);
                
                setTimeout(() => {
                    errorDiv.remove();
                }, 5000);
            }
        }
    </script>
</body>
</html> 