{% extends "base.html" %}
{% block title %}Create Individual - Personaut{% endblock %}

{% block head %}
<style>
    .memory-item {
        background: var(--bg2, #1e1e2e);
        border: 1px solid var(--bg3, #313244);
        border-radius: 10px;
        padding: 1.25rem;
        margin-bottom: 1rem;
        position: relative;
        transition: border-color 0.2s ease;
    }

    .memory-item:hover {
        border-color: var(--accent, #89b4fa);
    }

    .memory-item .memory-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 0.75rem;
    }

    .memory-item .memory-number {
        font-size: 0.8rem;
        color: var(--txt3, #6c7086);
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }

    .memory-item .memory-description {
        width: 100%;
        padding: 0.75rem;
        border: 1px solid var(--bg3, #313244);
        border-radius: 8px;
        background: var(--bg, #11111b);
        color: var(--txt, #cdd6f4);
        font-family: inherit;
        font-size: 0.9rem;
        resize: vertical;
        min-height: 60px;
        box-sizing: border-box;
    }

    .memory-item .memory-description:focus {
        outline: none;
        border-color: var(--accent, #89b4fa);
        box-shadow: 0 0 0 2px rgba(137, 180, 250, 0.15);
    }

    .memory-salience-row {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        margin: 0.75rem 0;
    }

    .memory-salience-row label {
        font-size: 0.85rem;
        color: var(--txt2, #a6adc8);
        min-width: 80px;
    }

    .memory-salience-row input[type="range"] {
        flex: 1;
    }

    .memory-salience-row .salience-value {
        font-size: 0.85rem;
        color: var(--txt2, #a6adc8);
        min-width: 35px;
        text-align: right;
    }

    .memory-emotions-area {
        margin-top: 0.75rem;
    }

    .generate-emotions-btn {
        background: linear-gradient(135deg, var(--accent, #89b4fa), #b4befe);
        color: var(--bg, #11111b);
        border: none;
        padding: 0.5rem 1rem;
        border-radius: 8px;
        cursor: pointer;
        font-weight: 600;
        font-size: 0.85rem;
        transition: all 0.2s ease;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
    }

    .generate-emotions-btn:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(137, 180, 250, 0.3);
    }

    .generate-emotions-btn:disabled {
        opacity: 0.5;
        cursor: not-allowed;
        transform: none;
        box-shadow: none;
    }

    .generate-emotions-btn .spinner {
        display: none;
        width: 14px;
        height: 14px;
        border: 2px solid transparent;
        border-top-color: var(--bg, #11111b);
        border-radius: 50%;
        animation: spin 0.6s linear infinite;
    }

    .generate-emotions-btn.loading .spinner {
        display: inline-block;
    }

    .generate-emotions-btn.loading .btn-label {
        display: none;
    }

    @keyframes spin {
        to {
            transform: rotate(360deg);
        }
    }

    .memory-emotions-display {
        margin-top: 0.75rem;
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
    }

    .emotion-tag {
        background: var(--bg, #11111b);
        border: 1px solid var(--bg3, #313244);
        color: var(--txt2, #a6adc8);
        padding: 0.35rem 0.75rem;
        border-radius: 20px;
        font-size: 0.8rem;
        display: inline-flex;
        align-items: center;
        gap: 0.4rem;
        transition: all 0.2s ease;
    }

    .emotion-tag .emotion-bar {
        width: 32px;
        height: 4px;
        background: var(--bg3, #313244);
        border-radius: 2px;
        overflow: hidden;
    }

    .emotion-tag .emotion-bar-fill {
        height: 100%;
        border-radius: 2px;
        transition: width 0.6s ease;
    }

    .emotion-tag.positive {
        border-color: rgba(166, 227, 161, 0.3);
    }

    .emotion-tag.positive .emotion-bar-fill {
        background: #a6e3a1;
    }

    .emotion-tag.negative {
        border-color: rgba(243, 139, 168, 0.3);
    }

    .emotion-tag.negative .emotion-bar-fill {
        background: #f38ba8;
    }

    .emotion-tag.neutral {
        border-color: rgba(137, 180, 250, 0.3);
    }

    .emotion-tag.neutral .emotion-bar-fill {
        background: #89b4fa;
    }

    .memory-status {
        font-size: 0.8rem;
        margin-top: 0.5rem;
        padding: 0.5rem 0.75rem;
        border-radius: 6px;
    }

    .memory-status.success {
        background: rgba(166, 227, 161, 0.1);
        color: #a6e3a1;
    }

    .memory-status.error {
        background: rgba(243, 139, 168, 0.1);
        color: #f38ba8;
    }

    .memory-remove-btn {
        background: none;
        border: 1px solid var(--bg3, #313244);
        color: var(--txt3, #6c7086);
        width: 28px;
        height: 28px;
        border-radius: 6px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 0.85rem;
        transition: all 0.15s ease;
    }

    .memory-remove-btn:hover {
        background: rgba(243, 139, 168, 0.15);
        border-color: #f38ba8;
        color: #f38ba8;
    }

    /* ── Masks ── */
    .mask-item,
    .trigger-item {
        background: var(--bg2, #1e1e2e);
        border: 1px solid var(--bg3, #313244);
        border-radius: 10px;
        padding: 1.25rem;
        margin-bottom: 1rem;
        position: relative;
        transition: border-color 0.2s ease;
    }

    .mask-item:hover {
        border-color: #cba6f7;
    }

    .trigger-item:hover {
        border-color: #f9e2af;
    }

    .mask-item .item-header,
    .trigger-item .item-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 0.75rem;
    }

    .mask-item .item-number,
    .trigger-item .item-number {
        font-size: 0.8rem;
        color: var(--txt3, #6c7086);
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }

    .mask-item input[type="text"],
    .mask-item textarea,
    .trigger-item input[type="text"],
    .trigger-item textarea {
        width: 100%;
        padding: 0.6rem 0.75rem;
        border: 1px solid var(--bg3, #313244);
        border-radius: 8px;
        background: var(--bg, #11111b);
        color: var(--txt, #cdd6f4);
        font-family: inherit;
        font-size: 0.9rem;
        box-sizing: border-box;
    }

    .mask-item input[type="text"]:focus,
    .mask-item textarea:focus,
    .trigger-item input[type="text"]:focus,
    .trigger-item textarea:focus {
        outline: none;
        border-color: var(--accent, #89b4fa);
        box-shadow: 0 0 0 2px rgba(137, 180, 250, 0.15);
    }

    .item-form-row {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        margin-bottom: 0.75rem;
    }

    .item-form-row label {
        font-size: 0.85rem;
        color: var(--txt2, #a6adc8);
        min-width: 110px;
        flex-shrink: 0;
    }

    .item-form-row input[type="text"],
    .item-form-row select {
        flex: 1;
    }

    .item-form-row select {
        padding: 0.5rem 0.75rem;
        border: 1px solid var(--bg3, #313244);
        border-radius: 8px;
        background: var(--bg, #11111b);
        color: var(--txt, #cdd6f4);
        font-family: inherit;
        font-size: 0.85rem;
    }

    .item-remove-btn {
        background: none;
        border: 1px solid var(--bg3, #313244);
        color: var(--txt3, #6c7086);
        width: 28px;
        height: 28px;
        border-radius: 6px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 0.85rem;
        transition: all 0.15s ease;
        flex-shrink: 0;
    }

    .item-remove-btn:hover {
        background: rgba(243, 139, 168, 0.15);
        border-color: #f38ba8;
        color: #f38ba8;
    }

    /* ── Modification tags (inside masks) ── */
    .mod-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 0.4rem;
        margin-top: 0.5rem;
    }

    .mod-tag {
        background: var(--bg, #11111b);
        border: 1px solid var(--bg3, #313244);
        color: var(--txt2, #a6adc8);
        padding: 0.25rem 0.6rem;
        border-radius: 16px;
        font-size: 0.78rem;
        display: inline-flex;
        align-items: center;
        gap: 0.35rem;
        cursor: default;
    }

    .mod-tag.boost {
        border-color: rgba(166, 227, 161, 0.3);
        color: #a6e3a1;
    }

    .mod-tag.suppress {
        border-color: rgba(243, 139, 168, 0.3);
        color: #f38ba8;
    }

    .mod-tag .mod-remove {
        cursor: pointer;
        opacity: 0.6;
        font-size: 0.75rem;
    }

    .mod-tag .mod-remove:hover {
        opacity: 1;
    }

    /* ── Trigger rules ── */
    .trigger-rules {
        margin: 0.75rem 0;
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
    }

    .trigger-rule-row {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        flex-wrap: wrap;
    }

    .trigger-rule-row select,
    .trigger-rule-row input[type="number"] {
        padding: 0.4rem 0.6rem;
        border: 1px solid var(--bg3, #313244);
        border-radius: 6px;
        background: var(--bg, #11111b);
        color: var(--txt, #cdd6f4);
        font-family: inherit;
        font-size: 0.85rem;
    }

    .trigger-rule-row input[type="number"] {
        width: 80px;
    }

    .trigger-rule-row .rule-remove-btn {
        background: none;
        border: none;
        color: var(--txt3);
        cursor: pointer;
        font-size: 0.8rem;
        padding: 0.25rem;
    }

    .trigger-rule-row .rule-remove-btn:hover {
        color: #f38ba8;
    }

    .toggle-row {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        margin: 0.5rem 0;
    }

    .toggle-row label {
        font-size: 0.85rem;
        color: var(--txt2, #a6adc8);
    }

    .toggle-switch {
        position: relative;
        width: 40px;
        height: 22px;
        background: var(--bg3, #313244);
        border-radius: 11px;
        cursor: pointer;
        transition: background 0.2s;
    }

    .toggle-switch.active {
        background: var(--accent, #89b4fa);
    }

    .toggle-switch::after {
        content: '';
        position: absolute;
        top: 3px;
        left: 3px;
        width: 16px;
        height: 16px;
        border-radius: 50%;
        background: var(--txt, #cdd6f4);
        transition: transform 0.2s;
    }

    .toggle-switch.active::after {
        transform: translateX(18px);
    }

    .small-btn {
        background: none;
        border: 1px solid var(--bg3, #313244);
        color: var(--txt2, #a6adc8);
        padding: 0.3rem 0.65rem;
        border-radius: 6px;
        cursor: pointer;
        font-size: 0.8rem;
        transition: all 0.15s ease;
    }

    .small-btn:hover {
        border-color: var(--accent, #89b4fa);
        color: var(--accent, #89b4fa);
    }
</style>
{% endblock %}

{% block content %}
<header class="page-header">
    <h1>Create Individual</h1>
    <p class="subtitle">Define a new AI persona with personality, emotions &amp; background</p>
</header>
<form method="POST" class="form-container" id="create-form">

    {# ── Basic Info ── #}
    <div class="form-section">
        <div class="section-header" onclick="toggleSection('sec-basic')">
            <h3>👤 Basic Information</h3>
            <span class="toggle">▲</span>
        </div>
        <div class="section-body open" id="sec-basic">
            <div class="form-group">
                <label for="name">Name *</label>
                <input type="text" id="name" name="name" required placeholder="e.g. Sarah Chen">
            </div>
            <div class="form-group">
                <label for="description">Description</label>
                <textarea id="description" name="description" rows="3"
                    placeholder="Brief description — who is this person?"></textarea>
            </div>
            <div class="form-group">
                <label for="individual_type">Type</label>
                <select id="individual_type" name="individual_type">
                    <option value="simulated">Simulated (AI-generated responses)</option>
                    <option value="human">Human (Manual responses)</option>
                </select>
            </div>
        </div>
    </div>

    {# ── Background / Metadata ── #}
    <div class="form-section">
        <div class="section-header" onclick="toggleSection('sec-meta')">
            <h3>📋 Background &amp; Context</h3>
            <span class="toggle">▲</span>
        </div>
        <div class="section-body open" id="sec-meta">
            {% for key, label, placeholder, input_type in metadata_fields %}
            <div class="form-group">
                <label for="meta_{{ key }}">{{ label }}</label>
                <input type="{{ input_type }}" id="meta_{{ key }}" name="meta_{{ key }}"
                    placeholder="{{ placeholder }}">
                {% if key == 'occupation' %}
                <p class="form-help">Shapes their worldview and knowledge — never explicitly stated in chat, only
                    implied through behavior.</p>
                {% elif key == 'interests' %}
                <p class="form-help">Comma-separated. These come up naturally in conversation.</p>
                {% elif key == 'speaking_style' %}
                <p class="form-help">How they talk — slang, formality, sentence length, quirks.</p>
                {% endif %}
            </div>
            {% endfor %}
        </div>
    </div>

    {# ── Physical Features ── #}
    <div class="form-section">
        <div class="section-header" onclick="toggleSection('sec-physical')">
            <h3>🧍 Physical Features <span
                    style="font-weight:normal;color:var(--txt3);font-size:0.8rem">(appearance)</span></h3>
            <span class="toggle">▼</span>
        </div>
        <div class="section-body" id="sec-physical">
            <p class="form-help" style="margin-bottom:1rem">
                Describe how this individual looks. These details appear in stage directions during in-person chats
                (e.g., "[pushes dark hair back]", "[adjusts glasses]"). All fields are optional.
            </p>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem">
                <div class="form-group">
                    <label for="phys_age_appearance">Age Appearance</label>
                    <input type="text" id="phys_age_appearance" name="phys_age_appearance"
                        placeholder="e.g. mid-30s, young adult, elderly">
                </div>
                <div class="form-group">
                    <label for="phys_height">Height</label>
                    <input type="text" id="phys_height" name="phys_height" placeholder="e.g. 5'10&quot;, tall, 175cm">
                </div>
                <div class="form-group">
                    <label for="phys_build">Build</label>
                    <input type="text" id="phys_build" name="phys_build"
                        placeholder="e.g. athletic, slim, stocky, curvy">
                </div>
                <div class="form-group">
                    <label for="phys_hair">Hair</label>
                    <input type="text" id="phys_hair" name="phys_hair"
                        placeholder="e.g. short dark curly hair, long red ponytail">
                </div>
                <div class="form-group">
                    <label for="phys_eyes">Eyes</label>
                    <input type="text" id="phys_eyes" name="phys_eyes"
                        placeholder="e.g. brown, bright green, dark blue">
                </div>
                <div class="form-group">
                    <label for="phys_skin_tone">Skin Tone</label>
                    <input type="text" id="phys_skin_tone" name="phys_skin_tone"
                        placeholder="e.g. fair, olive, warm brown, ebony">
                </div>
            </div>

            <div class="form-group">
                <label for="phys_facial_features">Facial Features</label>
                <input type="text" id="phys_facial_features" name="phys_facial_features"
                    placeholder="e.g. sharp jawline, dimples, freckles, round face">
            </div>
            <div class="form-group">
                <label for="phys_distinguishing_features">Distinguishing Features</label>
                <input type="text" id="phys_distinguishing_features" name="phys_distinguishing_features"
                    placeholder="Comma-separated: scar above left eyebrow, sleeve tattoo on right arm">
                <p class="form-help">Scars, tattoos, birthmarks, piercings — anything that makes them visually
                    distinctive.</p>
            </div>
            <div class="form-group">
                <label for="phys_clothing_style">Clothing Style</label>
                <input type="text" id="phys_clothing_style" name="phys_clothing_style"
                    placeholder="e.g. business casual, streetwear, vintage dresses">
            </div>
            <div class="form-group">
                <label for="phys_accessories">Accessories</label>
                <input type="text" id="phys_accessories" name="phys_accessories"
                    placeholder="Comma-separated: thick-rimmed glasses, silver watch, leather bracelet">
            </div>
            <div class="form-group">
                <label for="phys_other">Other Appearance Notes</label>
                <input type="text" id="phys_other" name="phys_other" placeholder="Anything else about their appearance">
            </div>
            <div class="form-group" style="margin-top:0.75rem;padding-top:0.75rem;border-top:1px solid var(--border)">
                <label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer;font-weight:500">
                    <input type="checkbox" name="generate_portrait" id="generate_portrait"
                        style="width:1.1rem;height:1.1rem;accent-color:var(--accent)">
                    🖼️ Generate AI Self-Portrait
                </label>
                <p class="form-help" style="margin-top:0.25rem;font-size:0.78rem;color:var(--txt3)">
                    Uses Gemini to create a portrait from these physical features. Requires a Google API key.
                </p>
            </div>
        </div>
    </div>

    {# ── Trait Profile (17 factors) ── #}
    <div class="form-section">
        <div class="section-header" onclick="toggleSection('sec-traits')">
            <h3>🧠 Personality Traits <span style="font-weight:normal;color:var(--txt3);font-size:0.8rem">(17-factor
                    model)</span></h3>
            <span class="toggle">▼</span>
        </div>
        <div class="section-body" id="sec-traits">
            <p class="form-help" style="margin-bottom:1rem">
                Each trait is a spectrum from 0% (left extreme) to 100% (right extreme). Default is 50% (average).
            </p>
            <div class="slider-grid">
                {% for trait in traits %}
                <div class="slider-item">
                    <div class="slider-label">
                        <span class="trait-name">{{ trait_labels[trait][0] }}</span>
                        <span class="trait-hint">{{ trait_labels[trait][1] }}</span>
                    </div>
                    <input type="range" name="trait_{{ trait }}" min="0" max="100" value="50">
                    <span class="slider-value">50%</span>
                </div>
                {% endfor %}
            </div>
        </div>
    </div>

    {# ── Emotional State ── #}
    <div class="form-section">
        <div class="section-header" onclick="toggleSection('sec-emotions')">
            <h3>💛 Initial Emotional State <span style="font-weight:normal;color:var(--txt3);font-size:0.8rem">({{
                    primary_emotions|length }} common + {{ all_emotions|length - primary_emotions|length }}
                    advanced)</span></h3>
            <span class="toggle">▼</span>
        </div>
        <div class="section-body" id="sec-emotions">
            <p class="form-help" style="margin-bottom:1rem">
                Set the starting emotional state. 0% = absent, 100% = intense. Most should start at 0%.
            </p>

            <h4 style="color:var(--txt2);margin-bottom:0.75rem;font-size:0.85rem">Common Emotions</h4>
            <div class="slider-grid">
                {% for emotion in primary_emotions %}
                <div class="slider-item">
                    <div class="slider-label">
                        <span class="trait-name">{{ emotion|capitalize }}</span>
                    </div>
                    <input type="range" name="emotion_{{ emotion }}" min="0" max="100" value="0">
                    <span class="slider-value">0%</span>
                </div>
                {% endfor %}
            </div>

            <div style="margin-top:1.25rem">
                <div class="section-header" onclick="toggleSection('sec-emotions-adv')"
                    style="background:var(--bg);border-color:var(--bg3)">
                    <h3 style="font-size:0.85rem;color:var(--txt2)">All 36 Emotions (advanced)</h3>
                    <span class="toggle">▼</span>
                </div>
                <div class="section-body" id="sec-emotions-adv">
                    <div class="slider-grid">
                        {% for emotion in all_emotions %}
                        {% if emotion not in primary_emotions %}
                        <div class="slider-item">
                            <div class="slider-label">
                                <span class="trait-name">{{ emotion|capitalize }}</span>
                            </div>
                            <input type="range" name="emotion_{{ emotion }}" min="0" max="100" value="0">
                            <span class="slider-value">0%</span>
                        </div>
                        {% endif %}
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
    </div>

    {# ── Memories ── #}
    <div class="form-section">
        <div class="section-header" onclick="toggleSection('sec-memories')">
            <h3>🧠 Memories <span style="font-weight:normal;color:var(--txt3);font-size:0.8rem">(trait-modulated
                    emotional states)</span></h3>
            <span class="toggle">▼</span>
        </div>
        <div class="section-body" id="sec-memories">
            <p class="form-help" style="margin-bottom:1rem">
                Add formative memories for this individual. Enter a description and click
                <strong>Generate Emotions</strong> — the system will produce an emotional state
                modulated by the personality traits configured above.
            </p>
            <div id="memories-container"></div>
            <button type="button" class="btn btn-secondary" id="add-memory-btn" onclick="addMemory()"
                style="margin-top:0.75rem">
                ➕ Add Memory
            </button>
        </div>
    </div>

    {# ── Masks ── #}
    <div class="form-section">
        <div class="section-header" onclick="toggleSection('sec-masks')">
            <h3>🎭 Masks <span style="font-weight:normal;color:var(--txt3);font-size:0.8rem">(contextual
                    personas)</span></h3>
            <span class="toggle">▼</span>
        </div>
        <div class="section-body" id="sec-masks">
            <p class="form-help" style="margin-bottom:1rem">
                Masks are contextual personas the individual adopts in specific situations.
                They modify emotional expression — e.g. a <strong>professional</strong> mask
                suppresses anger in workplace settings.
            </p>

            <div style="margin-bottom:1rem">
                <label style="font-size:0.85rem;color:var(--txt2)">Quick-add preset:</label>
                <div style="display:flex;flex-wrap:wrap;gap:0.5rem;margin-top:0.5rem">
                    {% for pm in preset_masks %}
                    <button type="button" class="btn btn-secondary" style="font-size:0.8rem;padding:0.35rem 0.75rem"
                        onclick="addPresetMask('{{ pm.name }}')">
                        {{ pm.name|capitalize }}
                    </button>
                    {% endfor %}
                </div>
            </div>

            <div id="masks-container"></div>
            <button type="button" class="btn btn-secondary" id="add-mask-btn" onclick="addMask()"
                style="margin-top:0.75rem">
                ➕ Add Custom Mask
            </button>
        </div>
    </div>

    {# ── Triggers ── #}
    <div class="form-section">
        <div class="section-header" onclick="toggleSection('sec-triggers')">
            <h3>⚡ Triggers <span style="font-weight:normal;color:var(--txt3);font-size:0.8rem">(conditional
                    activators)</span></h3>
            <span class="toggle">▼</span>
        </div>
        <div class="section-body" id="sec-triggers">
            <p class="form-help" style="margin-bottom:1rem">
                Triggers fire when an emotional threshold is crossed, activating a mask
                or applying emotion modifications. For example, an <em>anxiety crisis</em>
                trigger might activate the <strong>Stoic</strong> mask when anxiety &gt; 0.8.
            </p>
            <div id="triggers-container"></div>
            <button type="button" class="btn btn-secondary" id="add-trigger-btn" onclick="addTrigger()"
                style="margin-top:0.75rem">
                ⚡ Add Trigger
            </button>
        </div>
    </div>

    <div class="form-actions">
        <a href="{{ url_for('individuals.list_view') }}" class="btn btn-secondary">Cancel</a>
        <button type="submit" class="btn btn-primary">✨ Create Individual</button>
    </div>

</form>
{% endblock %}

{% block scripts %}
<script>
    // Live slider value updates
    document.querySelectorAll('input[type="range"]').forEach(slider => {
        const display = slider.parentElement.querySelector('.slider-value');
        if (display) {
            slider.addEventListener('input', () => { display.textContent = slider.value + '%'; });
        }
    });

    // Section toggle
    function toggleSection(id) {
        const body = document.getElementById(id);
        const toggle = body.previousElementSibling.querySelector('.toggle');
        body.classList.toggle('open');
        toggle.textContent = body.classList.contains('open') ? '▲' : '▼';
    }

    const NEGATIVE_EMOTIONS = new Set([
        'hostile', 'hurt', 'angry', 'selfish', 'hateful', 'critical', 'guilty',
        'ashamed', 'depressed', 'lonely', 'bored', 'apathetic', 'sad',
        'rejected', 'submissive', 'insecure', 'anxious', 'helpless', 'confused'
    ]);
    const POSITIVE_EMOTIONS = new Set([
        'cheerful', 'excited', 'hopeful', 'content', 'creative', 'proud',
        'appreciated', 'important', 'faithful', 'respected', 'satisfied',
        'intimate', 'loving', 'nurturing', 'trusting', 'sensual', 'energetic'
    ]);

    let memoryCounter = 0;

    function addMemory() {
        memoryCounter++;
        const container = document.getElementById('memories-container');
        const item = document.createElement('div');
        item.className = 'memory-item';
        item.dataset.index = memoryCounter;
        item.innerHTML = `
        <div class="memory-header">
            <span class="memory-number">Memory #${memoryCounter}</span>
            <button type="button" class="memory-remove-btn" onclick="removeMemory(this)" title="Remove">✕</button>
        </div>
        <textarea class="memory-description" name="memory_description[]"
                  placeholder="Describe a formative memory, e.g. 'Got promoted to team lead after 2 years of hard work'"
                  rows="2"></textarea>
        <div class="memory-salience-row">
            <label>Salience</label>
            <input type="range" name="memory_salience[]" min="0" max="1" step="0.05" value="0.5"
                   oninput="this.nextElementSibling.textContent = parseFloat(this.value).toFixed(2)">
            <span class="salience-value">0.50</span>
        </div>
        <div class="memory-emotions-area">
            <button type="button" class="generate-emotions-btn" onclick="generateEmotions(this)">
                <span class="btn-label">🔮 Generate Emotions</span>
                <span class="spinner"></span>
            </button>
            <div class="memory-emotions-display"></div>
            <input type="hidden" name="memory_emotions[]" value="{}">
        </div>
    `;
        container.appendChild(item);

        // Animate in
        item.style.opacity = '0';
        item.style.transform = 'translateY(10px)';
        requestAnimationFrame(() => {
            item.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
            item.style.opacity = '1';
            item.style.transform = 'translateY(0)';
        });
    }

    function removeMemory(btn) {
        const item = btn.closest('.memory-item');
        item.style.transition = 'opacity 0.2s ease, transform 0.2s ease';
        item.style.opacity = '0';
        item.style.transform = 'translateY(-10px)';
        setTimeout(() => item.remove(), 200);
    }

    function _collectTraits() {
        const traits = {};
        document.querySelectorAll('input[name^="trait_"]').forEach(input => {
            const name = input.name.replace('trait_', '');
            traits[name] = parseInt(input.value) / 100.0;
        });
        return traits;
    }

    function _emotionValence(name) {
        if (POSITIVE_EMOTIONS.has(name)) return 'positive';
        if (NEGATIVE_EMOTIONS.has(name)) return 'negative';
        return 'neutral';
    }

    function _renderEmotionTags(emotions, displayEl) {
        displayEl.innerHTML = '';
        const sorted = Object.entries(emotions).sort((a, b) => b[1] - a[1]);
        for (const [name, value] of sorted) {
            const valence = _emotionValence(name);
            const pct = Math.round(value * 100);
            const tag = document.createElement('span');
            tag.className = `emotion-tag ${valence}`;
            tag.innerHTML = `
            ${name}
            <span class="emotion-bar">
                <span class="emotion-bar-fill" style="width:${pct}%"></span>
            </span>
            <small>${pct}%</small>
        `;
            displayEl.appendChild(tag);
        }
    }

    async function generateEmotions(btn) {
        const item = btn.closest('.memory-item');
        const textarea = item.querySelector('.memory-description');
        const description = textarea.value.trim();
        if (!description) {
            textarea.focus();
            textarea.style.borderColor = '#f38ba8';
            setTimeout(() => { textarea.style.borderColor = ''; }, 2000);
            return;
        }

        btn.classList.add('loading');
        btn.disabled = true;

        // Clear previous status
        const existing = item.querySelector('.memory-status');
        if (existing) existing.remove();

        const traits = _collectTraits();
        const nameInput = document.getElementById('name');
        const name = nameInput ? nameInput.value.trim() : '';

        try {
            const resp = await fetch('/individuals/generate-memory-emotions', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ description, traits, name })
            });
            const data = await resp.json();

            if (data.error) {
                const status = document.createElement('div');
                status.className = 'memory-status error';
                status.textContent = '⚠ ' + data.error;
                item.querySelector('.memory-emotions-area').appendChild(status);
            } else {
                const emotions = data.emotions;
                // Store in hidden input
                item.querySelector('input[name="memory_emotions[]"]').value = JSON.stringify(emotions);
                // Render tags
                const displayEl = item.querySelector('.memory-emotions-display');
                _renderEmotionTags(emotions, displayEl);
                // Success flash
                const status = document.createElement('div');
                status.className = 'memory-status success';
                status.textContent = `✓ Generated ${Object.keys(emotions).length} emotions based on personality traits`;
                item.querySelector('.memory-emotions-area').appendChild(status);
                setTimeout(() => status.remove(), 4000);
            }
        } catch (err) {
            const status = document.createElement('div');
            status.className = 'memory-status error';
            status.textContent = '⚠ Network error: ' + err.message;
            item.querySelector('.memory-emotions-area').appendChild(status);
        } finally {
            btn.classList.remove('loading');
            btn.disabled = false;
        }
    }

    // ── Preset mask data (injected from Python) ──
    const PRESET_MASKS = {{ preset_masks_json| safe }};
    const ALL_EMOTION_LIST = {{ all_emotions_json| safe }};

    // ==========================================================================
    // Masks
    // ==========================================================================
    let maskCounter = 0;

    function _maskCardHTML(idx, name, desc, situations, mods, activeByDefault) {
        const modTags = Object.entries(mods).map(([em, val]) => {
            const cls = val >= 0 ? 'boost' : 'suppress';
            const sign = val >= 0 ? '+' : '';
            return `<span class="mod-tag ${cls}" data-emotion="${em}" data-value="${val}">
            ${em} ${sign}${val}
            <span class="mod-remove" onclick="removeModTag(this)">✕</span>
        </span>`;
        }).join('');

        return `
        <div class="item-header">
            <span class="item-number">Mask #${idx}</span>
            <button type="button" class="item-remove-btn" onclick="removeItem(this)" title="Remove">✕</button>
        </div>
        <div class="item-form-row">
            <label>Name</label>
            <input type="text" class="mask-name" placeholder="e.g. professional" value="${_esc(name)}">
        </div>
        <div class="item-form-row">
            <label>Description</label>
            <input type="text" class="mask-desc" placeholder="Brief description of when this persona activates" value="${_esc(desc)}">
        </div>
        <div class="item-form-row">
            <label>Trigger situations</label>
            <input type="text" class="mask-situations" placeholder="office, meeting, interview (comma-separated)" value="${_esc(situations)}">
        </div>
        <div class="toggle-row">
            <label>Active by default</label>
            <div class="toggle-switch ${activeByDefault ? 'active' : ''}" onclick="toggleSwitch(this)"
                 data-field="mask-active-default"></div>
        </div>
        <div style="margin-top:0.75rem">
            <label style="font-size:0.85rem;color:var(--txt2)">Emotional modifications:</label>
            <div class="mod-tags">${modTags}</div>
            <div style="display:flex;gap:0.5rem;margin-top:0.5rem;align-items:center;flex-wrap:wrap">
                <select class="mod-emotion-select" style="padding:0.4rem 0.6rem;border:1px solid var(--bg3);border-radius:6px;background:var(--bg);color:var(--txt);font-size:0.85rem">
                    <option value="">Select emotion…</option>
                    ${ALL_EMOTION_LIST.map(e => `<option value="${e}">${e}</option>`).join('')}
                </select>
                <input type="number" class="mod-value-input" step="0.1" min="-1" max="1" value="0.2"
                       style="width:70px;padding:0.4rem;border:1px solid var(--bg3);border-radius:6px;background:var(--bg);color:var(--txt);font-size:0.85rem">
                <button type="button" class="small-btn" onclick="addModification(this)">+ Add</button>
            </div>
        </div>
        <input type="hidden" name="mask_data[]" value="">
    `;
    }

    function _esc(s) { return (s || '').replace(/"/g, '&quot;').replace(/</g, '&lt;'); }

    function _collectMaskData(item) {
        const name = item.querySelector('.mask-name').value.trim();
        const desc = item.querySelector('.mask-desc').value.trim();
        const sits = item.querySelector('.mask-situations').value.trim();
        const activeToggle = item.querySelector('[data-field="mask-active-default"]');
        const activeByDefault = activeToggle ? activeToggle.classList.contains('active') : false;
        const mods = {};
        item.querySelectorAll('.mod-tag').forEach(tag => {
            mods[tag.dataset.emotion] = parseFloat(tag.dataset.value);
        });
        return {
            name: name,
            description: desc,
            trigger_situations: sits ? sits.split(',').map(s => s.trim()).filter(Boolean) : [],
            emotional_modifications: mods,
            active_by_default: activeByDefault,
        };
    }

    function _syncMaskHidden(item) {
        const data = _collectMaskData(item);
        item.querySelector('input[name="mask_data[]"]').value = JSON.stringify(data);
    }

    function addMask(name, desc, situations, mods, activeByDefault) {
        maskCounter++;
        const container = document.getElementById('masks-container');
        const item = document.createElement('div');
        item.className = 'mask-item';
        item.innerHTML = _maskCardHTML(
            maskCounter,
            name || '',
            desc || '',
            situations || '',
            mods || {},
            activeByDefault || false,
        );
        container.appendChild(item);
        _animateIn(item);
        // Sync on input changes
        item.querySelectorAll('input[type="text"]').forEach(inp => {
            inp.addEventListener('input', () => _syncMaskHidden(item));
        });
        _syncMaskHidden(item);
    }

    function addPresetMask(presetName) {
        const pm = PRESET_MASKS.find(m => m.name === presetName);
        if (!pm) return;
        addMask(
            pm.name,
            pm.description,
            (pm.trigger_situations || []).join(', '),
            pm.emotional_modifications || {},
            pm.active_by_default || false,
        );
    }

    function addModification(btn) {
        const item = btn.closest('.mask-item');
        const select = item.querySelector('.mod-emotion-select');
        const valInput = item.querySelector('.mod-value-input');
        const emotion = select.value;
        const value = parseFloat(valInput.value);
        if (!emotion || isNaN(value)) return;
        // Don't add duplicate
        if (item.querySelector(`.mod-tag[data-emotion="${emotion}"]`)) return;

        const cls = value >= 0 ? 'boost' : 'suppress';
        const sign = value >= 0 ? '+' : '';
        const tagEl = document.createElement('span');
        tagEl.className = `mod-tag ${cls}`;
        tagEl.dataset.emotion = emotion;
        tagEl.dataset.value = value;
        tagEl.innerHTML = `${emotion} ${sign}${value} <span class="mod-remove" onclick="removeModTag(this)">✕</span>`;
        item.querySelector('.mod-tags').appendChild(tagEl);

        select.value = '';
        _syncMaskHidden(item);
    }

    function removeModTag(removeBtn) {
        const tag = removeBtn.closest('.mod-tag');
        const item = tag.closest('.mask-item');
        tag.remove();
        _syncMaskHidden(item);
    }

    // ==========================================================================
    // Triggers
    // ==========================================================================
    let triggerCounter = 0;

    function addTrigger() {
        triggerCounter++;
        const container = document.getElementById('triggers-container');
        const item = document.createElement('div');
        item.className = 'trigger-item';

        // Build mask options for the response dropdown
        const maskOptions = Array.from(document.querySelectorAll('.mask-item .mask-name'))
            .map(inp => inp.value.trim()).filter(Boolean)
            .map(name => `<option value="${name}">${name}</option>`).join('');

        item.innerHTML = `
        <div class="item-header">
            <span class="item-number">Trigger #${triggerCounter}</span>
            <button type="button" class="item-remove-btn" onclick="removeItem(this)" title="Remove">✕</button>
        </div>
        <div class="item-form-row">
            <label>Description</label>
            <input type="text" class="trigger-desc" placeholder="e.g. High anxiety crisis response">
        </div>
        <div style="margin:0.75rem 0">
            <label style="font-size:0.85rem;color:var(--txt2)">Rules <small style="color:var(--txt3)">(when should this fire?)</small></label>
            <div class="trigger-rules"></div>
            <button type="button" class="small-btn" onclick="addTriggerRule(this)" style="margin-top:0.35rem">+ Add Rule</button>
        </div>
        <div class="toggle-row">
            <label>Match all rules (AND)</label>
            <div class="toggle-switch active" onclick="toggleSwitch(this)"
                 data-field="trigger-match-all"></div>
        </div>
        <div class="item-form-row">
            <label>Response</label>
            <select class="trigger-response-type" onchange="onTriggerResponseChange(this)">
                <option value="none">None</option>
                <option value="mask">Activate mask…</option>
            </select>
        </div>
        <div class="trigger-mask-select-row item-form-row" style="display:none">
            <label>Mask</label>
            <select class="trigger-response-mask">
                <option value="">Select a mask…</option>
                ${maskOptions}
            </select>
        </div>
        <input type="hidden" name="trigger_data[]" value="">
    `;

        container.appendChild(item);
        _animateIn(item);

        // Add a default rule
        addTriggerRule(item.querySelector('.small-btn'));

        // Sync on changes
        item.querySelectorAll('input,select').forEach(el => {
            el.addEventListener('input', () => _syncTriggerHidden(item));
            el.addEventListener('change', () => _syncTriggerHidden(item));
        });
        _syncTriggerHidden(item);
    }

    function addTriggerRule(btn) {
        const item = btn.closest('.trigger-item');
        const rulesEl = item.querySelector('.trigger-rules');
        const row = document.createElement('div');
        row.className = 'trigger-rule-row';
        row.innerHTML = `
        <select class="rule-emotion">
            ${ALL_EMOTION_LIST.map(e => `<option value="${e}">${e}</option>`).join('')}
        </select>
        <select class="rule-operator">
            <option value=">">&gt;</option>
            <option value=">=">&ge;</option>
            <option value="<">&lt;</option>
            <option value="<=">&le;</option>
            <option value="==">==</option>
        </select>
        <input type="number" class="rule-threshold" step="0.05" min="0" max="1" value="0.7">
        <button type="button" class="rule-remove-btn" onclick="removeTriggerRule(this)">✕</button>
    `;
        rulesEl.appendChild(row);
        // Sync
        row.querySelectorAll('input,select').forEach(el => {
            el.addEventListener('input', () => _syncTriggerHidden(item));
            el.addEventListener('change', () => _syncTriggerHidden(item));
        });
        _syncTriggerHidden(item);
    }

    function removeTriggerRule(btn) {
        const item = btn.closest('.trigger-item');
        btn.closest('.trigger-rule-row').remove();
        _syncTriggerHidden(item);
    }

    function onTriggerResponseChange(select) {
        const item = select.closest('.trigger-item');
        const maskRow = item.querySelector('.trigger-mask-select-row');
        maskRow.style.display = select.value === 'mask' ? 'flex' : 'none';

        // Refresh available masks
        if (select.value === 'mask') {
            const maskSelect = item.querySelector('.trigger-response-mask');
            const names = Array.from(document.querySelectorAll('.mask-item .mask-name'))
                .map(inp => inp.value.trim()).filter(Boolean);
            const current = maskSelect.value;
            maskSelect.innerHTML = '<option value="">Select a mask…</option>' +
                names.map(n => `<option value="${n}" ${n === current ? 'selected' : ''}>${n}</option>`).join('');
        }
        _syncTriggerHidden(item);
    }

    function _syncTriggerHidden(item) {
        const desc = item.querySelector('.trigger-desc').value.trim();
        const matchAllToggle = item.querySelector('[data-field="trigger-match-all"]');
        const matchAll = matchAllToggle ? matchAllToggle.classList.contains('active') : true;

        const rules = [];
        item.querySelectorAll('.trigger-rule-row').forEach(row => {
            rules.push({
                emotion: row.querySelector('.rule-emotion').value,
                threshold: parseFloat(row.querySelector('.rule-threshold').value) || 0,
                operator: row.querySelector('.rule-operator').value,
            });
        });

        const respType = item.querySelector('.trigger-response-type').value;
        let response = null;
        if (respType === 'mask') {
            const maskName = item.querySelector('.trigger-response-mask').value;
            if (maskName) response = { type: 'mask', name: maskName };
        }

        const data = {
            description: desc,
            rules: rules,
            match_all: matchAll,
            response: response,
        };
        item.querySelector('input[name="trigger_data[]"]').value = JSON.stringify(data);
    }

    // ==========================================================================
    // Shared helpers
    // ==========================================================================
    function toggleSwitch(el) {
        el.classList.toggle('active');
        // Sync nearest hidden
        const maskItem = el.closest('.mask-item');
        if (maskItem) _syncMaskHidden(maskItem);
        const trigItem = el.closest('.trigger-item');
        if (trigItem) _syncTriggerHidden(trigItem);
    }

    function removeItem(btn) {
        const item = btn.closest('.mask-item, .trigger-item');
        item.style.transition = 'opacity 0.2s ease, transform 0.2s ease';
        item.style.opacity = '0';
        item.style.transform = 'translateY(-10px)';
        setTimeout(() => item.remove(), 200);
    }

    function _animateIn(item) {
        item.style.opacity = '0';
        item.style.transform = 'translateY(10px)';
        requestAnimationFrame(() => {
            item.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
            item.style.opacity = '1';
            item.style.transform = 'translateY(0)';
        });
    }
</script>
{% endblock %}