{% extends "base.html" %}
{% block title %}{{ ind.name }} - Personaut{% endblock %}

{% block content %}
<header class="page-header">
    <div style="display:flex;align-items:center;gap:1.5rem">
        {% if ind.portrait_url %}
        <img src="{{ ind.portrait_url }}" alt="Portrait of {{ ind.name }}" id="header-portrait"
            style="width:80px;height:80px;border-radius:50%;object-fit:cover;border:3px solid var(--accent);box-shadow:0 2px 12px rgba(108,93,211,0.25)">
        {% else %}
        <div id="header-portrait"
            style="width:80px;height:80px;border-radius:50%;background:linear-gradient(135deg,var(--card) 0%,var(--surface) 100%);border:3px dashed var(--border);display:flex;align-items:center;justify-content:center;font-size:2rem;color:var(--txt3)">
            🧑
        </div>
        {% endif %}
        <div>
            <h1>{{ ind.name }}</h1>
            <span class="badge {{ ind.individual_type }}">{{ ind.individual_type }}</span>
        </div>
    </div>
    <div style="display:flex;gap:0.75rem">
        <a href="{{ url_for('individuals.edit_view', id=ind.id) }}" class="btn btn-secondary">✏️ Edit</a>
        <a href="{{ url_for('chat.select_session') }}?individual={{ ind.id }}" class="btn btn-primary">💬 Start Chat</a>
    </div>
</header>

<div class="detail-grid">
    {# Description #}
    <section class="detail-section">
        <h2>Description</h2>
        <p>{{ ind.description or 'No description provided' }}</p>
    </section>

    {# Background / Metadata #}
    {% if ind.metadata %}
    <section class="detail-section">
        <h2>Background</h2>
        <div class="meta-grid">
            {% for key, value in ind.metadata.items() %}
            <div class="meta-item">
                <span class="meta-key">{{ key.replace('_', ' ') }}</span>
                <span class="meta-val">{{ value }}</span>
            </div>
            {% endfor %}
        </div>
    </section>
    {% endif %}

    {# Physical Features #}
    {% if ind.physical_features %}
    <section class="detail-section">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:0.75rem">
            <h2 style="margin:0">🧍 Physical Features</h2>
            <button type="button" class="btn btn-secondary btn-sm" id="btn-gen-portrait"
                onclick="generatePortrait('{{ ind.id }}')" style="font-size:0.8rem;padding:0.35rem 0.75rem">
                🖼️ {{ 'Regenerate' if ind.portrait_url else 'Generate' }} Portrait
            </button>
        </div>
        {% if ind.portrait_url %}
        <div style="text-align:center;margin-bottom:1rem" id="portrait-container">
            <img src="{{ ind.portrait_url }}" alt="Portrait of {{ ind.name }}"
                style="max-width:280px;border-radius:12px;box-shadow:0 4px 20px rgba(0,0,0,0.15);border:2px solid var(--border)">
        </div>
        {% else %}
        <div id="portrait-container"></div>
        {% endif %}
        <div class="meta-grid">
            {% for key, value in ind.physical_features.items() %}
            <div class="meta-item">
                <span class="meta-key">{{ key.replace('_', ' ') }}</span>
                <span class="meta-val">{% if value is iterable and value is not string %}{{ value|join(', ') }}{% else
                    %}{{ value }}{% endif %}</span>
            </div>
            {% endfor %}
        </div>
    </section>
    {% endif %}

    {# Trait Profile #}
    {% if ind.trait_profile %}
    <section class="detail-section">
        <h2>Personality Traits</h2>
        {% for trait, value in ind.trait_profile.items() %}
        <div class="bar-row">
            <span class="bar-label">{{ trait_fmt(trait) }}</span>
            <div class="bar-track">
                <div class="bar-midline"></div>
                <div class="bar-fill {% if value >= 0.7 %}positive{% elif value <= 0.3 %}negative{% else %}accent{% endif %}"
                    style="width: {{ value * 100 }}%"></div>
            </div>
            <span class="bar-percent">{{ (value * 100)|int }}%</span>
        </div>
        {% endfor %}
    </section>
    {% endif %}

    {# Emotional State #}
    {% if ind.emotional_state %}
    <section class="detail-section">
        <h2>Emotional State</h2>
        {% for emotion, value in ind.emotional_state.items()|sort(attribute='1', reverse=true) %}
        {% if value > 0 %}
        <div class="bar-row">
            <span class="bar-label">{{ emotion|capitalize }}</span>
            <div class="bar-track">
                <div class="bar-fill accent" style="width: {{ value * 100 }}%"></div>
            </div>
            <span class="bar-percent">{{ (value * 100)|int }}%</span>
        </div>
        {% endif %}
        {% endfor %}
        {% set has_any = ind.emotional_state.values()|select('gt', 0)|list %}
        {% if not has_any %}
        <p style="color:var(--txt3);font-size:0.85rem">All emotions at baseline (0%)</p>
        {% endif %}
    </section>
    {% endif %}
</div>

<div style="margin-top: 1.5rem">
    <a href="{{ url_for('individuals.list_view') }}" class="btn btn-secondary">← Back to list</a>
</div>
{% endblock %}

{% block scripts %}
<script>
    async function generatePortrait(individualId) {
        const btn = document.getElementById('btn-gen-portrait');
        const container = document.getElementById('portrait-container');
        const origText = btn.textContent;

        btn.disabled = true;
        btn.textContent = '⏳ Generating…';
        btn.style.opacity = '0.6';

        try {
            const resp = await fetch('/individuals/' + individualId + '/generate-portrait', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            });
            if (!resp.ok) {
                const err = await resp.json().catch(() => ({}));
                throw new Error(err.detail || 'Generation failed (' + resp.status + ')');
            }
            const data = await resp.json();
            if (data.portrait_url) {
                // Update portrait container
                container.innerHTML = '<img src="' + data.portrait_url + '?t=' + Date.now() + '" alt="Portrait" '
                    + 'style="max-width:280px;border-radius:12px;box-shadow:0 4px 20px rgba(0,0,0,0.15);border:2px solid var(--border)">';
                container.style.textAlign = 'center';
                container.style.marginBottom = '1rem';

                // Update header portrait
                const header = document.getElementById('header-portrait');
                if (header) {
                    const img = document.createElement('img');
                    img.src = data.portrait_url + '?t=' + Date.now();
                    img.alt = 'Portrait';
                    img.id = 'header-portrait';
                    img.style.cssText = 'width:80px;height:80px;border-radius:50%;object-fit:cover;border:3px solid var(--accent);box-shadow:0 2px 12px rgba(108,93,211,0.25)';
                    header.replaceWith(img);
                }

                btn.textContent = '🖼️ Regenerate Portrait';
            }
        } catch (e) {
            alert('Portrait generation failed: ' + e.message);
        } finally {
            btn.disabled = false;
            btn.style.opacity = '1';
            if (btn.textContent === '⏳ Generating…') btn.textContent = origText;
        }
    }
</script>
{% endblock %}