{% extends "indy_hub/base.html" %}
{% load i18n %}
{% load static %}
{% load humanize %}

{% block page_title %}{{ bp_name }} - {% trans "Crafting Requirements" %}{% endblock page_title %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'indy_hub/css/page_headers.css' %}">
<link rel="stylesheet" href="{% static 'indy_hub/css/blueprints.css' %}">
<link rel="stylesheet" href="{% static 'indy_hub/css/craft_bp.css' %}">
{% endblock extra_css %}

{% block content %}
<main class="craft-bp-surface bg-body p-4">
    <div class="container-fluid my-0 bg-body">
        <div class="dev-alert alert alert-warning d-flex align-items-center gap-3 mb-4" role="alert">
            <i class="fas fa-exclamation-triangle fa-lg"></i>
            <div>
                <h2 class="h6 fw-semibold mb-1 text-uppercase">{% trans "Active development" %}</h2>
                <p class="mb-0 small">{% trans "This crafting workspace is under active development. Please don't rely on the displayed data for production decisions yet." %}</p>
            </div>
        </div>
        <div class="page-header craft-hero mb-4 position-relative overflow-hidden">
            <i class="fas fa-tools header-bg"></i>
            <div class="craft-hero__content position-relative">
                <div class="row g-4 align-items-center">
                    <div class="col-lg-7">
                        <div class="hero-headline d-flex align-items-start gap-3">
                            {% if product_type_id %}
                            <span class="blueprint-icon flex-shrink-0">
                                <img src="https://images.evetech.net/types/{{ product_type_id }}/icon?size=64" alt="{{ bp_name }}" onerror="this.style.display='none';this.nextElementSibling.style.display='flex';">
                                <span class="fallback"><i class="fas fa-industry"></i></span>
                            </span>
                            {% else %}
                            <span class="blueprint-icon flex-shrink-0">
                                <span class="fallback" style="display:flex;"><i class="fas fa-industry"></i></span>
                            </span>
                            {% endif %}
                            <div>
                                <span class="hero-eyebrow text-white-50 text-uppercase fw-semibold">{% trans "Production workspace" %}</span>
                                <h1 class="hero-title display-6 fw-bold text-white mb-2">
                                    <i class="fas fa-tools me-2"></i>{{ bp_name }}
                                </h1>
                                <p class="hero-subtitle text-white-50 mb-0">{% trans "Material requirements, production planning and profitability at a glance." %}</p>
                            </div>
                        </div>
                        <div class="hero-chip-row d-flex flex-wrap gap-2 mt-4">
                            <span class="hero-chip">
                                <i class="fas fa-cube"></i>
                                <span class="hero-chip-label">{% trans "Runs" %}</span>
                                <span class="hero-chip-value">{{ num_runs|default:1|intcomma }}</span>
                            </span>
                            <span class="hero-chip">
                                <i class="fas fa-industry"></i>
                                <span class="hero-chip-label">{% trans "Output" %}</span>
                                <span class="hero-chip-value">{{ final_product_qty|default:num_runs|intcomma }}</span>
                            </span>
                            <span class="hero-chip">
                                <i class="fas fa-layer-group"></i>
                                <span class="hero-chip-label">ME</span>
                                <span class="hero-chip-value">{{ me|default:0 }}</span>
                            </span>
                            <span class="hero-chip">
                                <i class="fas fa-stopwatch"></i>
                                <span class="hero-chip-label">TE</span>
                                <span class="hero-chip-value">{{ te|default:0 }}</span>
                            </span>
                        </div>
                        <div class="hero-kpi-row d-flex flex-wrap gap-3 mt-4">
                            <div class="hero-kpi">
                                <span class="hero-kpi-label">{% trans "Estimated profit" %}</span>
                                <span id="heroProfit" class="hero-kpi-value">0 ISK</span>
                            </div>
                            <div class="hero-kpi">
                                <span class="hero-kpi-label">{% trans "Estimated margin" %}</span>
                                <span id="heroMargin" class="hero-kpi-value">0%</span>
                            </div>
                            <div class="hero-kpi">
                                <span class="hero-kpi-label">{% trans "Last recalculated" %}</span>
                                <span id="heroUpdated" class="hero-kpi-value text-white-50">—</span>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-5">
                        <div class="craft-hero__panel glass-panel p-3 p-lg-4 h-100">
                            <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
                                <h2 class="hero-panel-title h6 text-uppercase text-white-50 mb-0">{% trans "Simulation controls" %}</h2>
                                <span id="simulationStatus" class="badge bg-secondary d-none"></span>
                            </div>
                            <div class="hero-action-buttons d-flex flex-wrap gap-2 mb-3">
                                <button id="saveSimulationBtn" class="btn btn-outline-light btn-sm px-3" type="button" data-bs-toggle="modal" data-bs-target="#saveSimulationModal">
                                    <i class="fas fa-save me-1"></i>{% trans "Save" %}
                                </button>
                                <button id="loadSimulationBtn" class="btn btn-light text-primary btn-sm px-3" type="button" data-bs-toggle="modal" data-bs-target="#loadSimulationModal">
                                    <i class="fas fa-folder-open me-1"></i>{% trans "Load" %}
                                </button>
                                <button id="recalcNowBtn" class="btn btn-primary btn-sm px-3" type="button">
                                    <i class="fas fa-sync-alt me-1"></i>{% trans "Recalculate" %}
                                </button>
                            </div>
                            <form id="blueprint-control-form" class="hero-form d-flex flex-column gap-3" method="get" action="">
                                <div class="input-group input-group-sm">
                                    <span class="input-group-text fw-semibold"><i class="fas fa-sync-alt me-1"></i>{% trans "Runs" %}</span>
                                    <input type="number" min="1" name="runs" id="runsInput" value="{{ num_runs|default:1 }}" class="form-control">
                                    <button class="btn btn-primary" type="submit">{% trans "Update" %}</button>
                                </div>
                                <div class="form-text text-muted small">
                                    {% trans "Runs will refresh material counts and financials when applied." %}
                                </div>
                                <input type="hidden" name="me" value="{{ me|default:0 }}">
                                <input type="hidden" name="te" value="{{ te|default:0 }}">
                                <input type="hidden" name="buy" value="{{ request.GET.buy|default:'' }}">
                                {% if request.GET.next %}
                                <input type="hidden" name="next" value="{{ request.GET.next|escape }}">
                                {% endif %}
                                <input type="hidden" name="active_tab" id="activeTabInput" value="{{ active_tab|default:'materials' }}">
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    <div id="bpTabs-loading" class="border border-warning-subtle bg-warning-subtle rounded-3 p-4 mb-4">
        <div class="d-flex align-items-center gap-3">
            <div class="spinner-border text-warning" role="status" style="width:2.5rem;height:2.5rem;">
                <span class="visually-hidden">{% trans "Loading..." %}</span>
            </div>
            <div>
                <h5 class="mb-1 text-warning fw-semibold">{% trans "Preparing simulation workspace" %}</h5>
                <p class="mb-0 text-muted small">{% trans "We are synchronising materials, production tree and financial data." %}</p>
            </div>
        </div>
    </div>

    {% with current_tab=active_tab|default:'materials' %}
    <div class="main-content blueprint-main">
        <div id="bpTabs" class="nav nav-pills flex-row flex-nowrap overflow-auto gap-3 mb-4 blueprint-tabs" role="tablist">
            <button class="nav-link blueprint-tab {% if current_tab == 'materials' %}active{% endif %}" id="materials-tab" data-bs-toggle="tab" data-bs-target="#tab-materials" type="button" role="tab" aria-controls="tab-materials" aria-selected="{% if current_tab == 'materials' %}true{% else %}false{% endif %}">
                <span class="tab-icon"><i class="fas fa-cubes"></i></span>
                <span class="tab-text">
                    <span class="tab-title">{% trans "Materials" %}</span>
                    <span class="tab-subtitle">{% trans "Stock & inputs" %}</span>
                </span>
            </button>
            <button class="nav-link blueprint-tab {% if current_tab == 'tree' %}active{% endif %}" id="tree-tab" data-bs-toggle="tab" data-bs-target="#tab-tree" type="button" role="tab" aria-controls="tab-tree" aria-selected="{% if current_tab == 'tree' %}true{% else %}false{% endif %}">
                <span class="tab-icon"><i class="fas fa-sitemap"></i></span>
                <span class="tab-text">
                    <span class="tab-title">{% trans "Production tree" %}</span>
                    <span class="tab-subtitle">{% trans "Toggle make or buy" %}</span>
                </span>
            </button>
            <button class="nav-link blueprint-tab {% if current_tab == 'cycles' %}active{% endif %}" id="cycles-tab" data-bs-toggle="tab" data-bs-target="#tab-cycles" type="button" role="tab" aria-controls="tab-cycles" aria-selected="{% if current_tab == 'cycles' %}true{% else %}false{% endif %}">
                <span class="tab-icon"><i class="fas fa-sync"></i></span>
                <span class="tab-text">
                    <span class="tab-title">{% trans "Cycles" %}</span>
                    <span class="tab-subtitle">{% trans "Plan throughput" %}</span>
                </span>
            </button>
            <button class="nav-link blueprint-tab {% if current_tab == 'financial' %}active{% endif %}" id="financial-tab" data-bs-toggle="tab" data-bs-target="#tab-financial" type="button" role="tab" aria-controls="tab-financial" aria-selected="{% if current_tab == 'financial' %}true{% else %}false{% endif %}">
                <span class="tab-icon"><i class="fas fa-file-invoice-dollar"></i></span>
                <span class="tab-text">
                    <span class="tab-title">{% trans "Financial" %}</span>
                    <span class="tab-subtitle">{% trans "Profit & pricing" %}</span>
                </span>
            </button>
            <button class="nav-link blueprint-tab {% if current_tab == 'needed' %}active{% endif %}" id="needed-tab" data-bs-toggle="tab" data-bs-target="#tab-needed" type="button" role="tab" aria-controls="tab-needed" aria-selected="{% if current_tab == 'needed' %}true{% else %}false{% endif %}">
                <span class="tab-icon"><i class="fas fa-cart-arrow-down"></i></span>
                <span class="tab-text">
                    <span class="tab-title">{% trans "Purchase list" %}</span>
                    <span class="tab-subtitle">{% trans "Shopping helper" %}</span>
                </span>
            </button>
            <button class="nav-link blueprint-tab {% if current_tab == 'config' %}active{% endif %}" id="config-tab" data-bs-toggle="tab" data-bs-target="#tab-config" type="button" role="tab" aria-controls="tab-config" aria-selected="{% if current_tab == 'config' %}true{% else %}false{% endif %}">
                <span class="tab-icon"><i class="fas fa-sliders-h"></i></span>
                <span class="tab-text">
                    <span class="tab-title">{% trans "Blueprint config" %}</span>
                    <span class="tab-subtitle">{% trans "Efficiencies" %}</span>
                </span>
            </button>
        </div>

        <div class="tab-content" id="bpTabsContent">
            <div class="tab-pane fade {% if current_tab == 'materials' %}show active{% endif %}" id="tab-materials" role="tabpanel" aria-labelledby="materials-tab">
                <div class="tab-intro card card-intro shadow-sm border-0 mb-4">
                    <div class="card-body d-flex align-items-center gap-3">
                        <span class="tab-intro-icon text-primary-emphasis bg-primary-subtle"><i class="fas fa-cubes"></i></span>
                        <div>
                            <h3 class="h6 text-uppercase text-muted mb-1">{% trans "Materials overview" %}</h3>
                            <p class="mb-0 text-muted small">{% trans "Review grouped inputs to understand volumes per run and spot potential bottlenecks." %}</p>
                        </div>
                    </div>
                </div>
                <div class="row row-cols-1 row-cols-sm-2 row-cols-lg-4 g-3 mb-4">
                    <div class="col">
                        <div class="card shadow-sm border-0 h-100">
                            <div class="card-body">
                                <div class="text-muted text-uppercase small fw-semibold">{% trans "Runs" %}</div>
                                <div class="fs-4 fw-bold text-primary">{{ num_runs|default:1|intcomma }}</div>
                            </div>
                        </div>
                    </div>
                    <div class="col">
                        <div class="card shadow-sm border-0 h-100">
                            <div class="card-body">
                                <div class="text-muted text-uppercase small fw-semibold">{% trans "Output quantity" %}</div>
                                <div class="fs-4 fw-bold text-success">{{ final_product_qty|default:num_runs|intcomma }}</div>
                            </div>
                        </div>
                    </div>
                    <div class="col">
                        <div class="card shadow-sm border-0 h-100">
                            <div class="card-body">
                                <div class="text-muted text-uppercase small fw-semibold">{% trans "Material efficiency" %}</div>
                                <div class="fs-4 fw-bold">{{ me|default:0 }}</div>
                            </div>
                        </div>
                    </div>
                    <div class="col">
                        <div class="card shadow-sm border-0 h-100">
                            <div class="card-body">
                                <div class="text-muted text-uppercase small fw-semibold">{% trans "Time efficiency" %}</div>
                                <div class="fs-4 fw-bold">{{ te|default:0 }}</div>
                            </div>
                        </div>
                    </div>
                </div>

                <div id="materialsGroupsContainer">
                    {% if materials_by_group %}
                        {% for group_id, group in materials_by_group.items %}
                        <div class="card shadow-sm mb-4">
                            <div class="card-header d-flex align-items-center justify-content-between bg-body-secondary">
                                <span class="fw-semibold">
                                    <i class="fas fa-layer-group text-primary me-2"></i>{{ group.group_name|default:_("Other") }}
                                </span>
                                <span class="badge bg-primary-subtle text-primary fw-semibold">{{ group.items|length }}</span>
                            </div>
                            <div class="card-body p-0">
                                <div class="table-responsive">
                                    <table class="table table-hover table-sm align-middle mb-0">
                                        <thead class="table-light">
                                            <tr>
                                                <th>{% trans "Material" %}</th>
                                                <th class="text-end">{% trans "Quantity" %}</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {% for item in group.items %}
                                            <tr data-type-id="{{ item.type_id }}">
                                                <td class="fw-semibold">
                                                    <div class="d-flex align-items-center gap-3">
                                                        <img src="https://images.evetech.net/types/{{ item.type_id }}/icon?size=32" alt="{{ item.type_name }}" class="rounded" style="width:30px;height:30px;background:#f3f4f6;" onerror="this.style.display='none';">
                                                        <span class="badge bg-info-subtle text-info-emphasis px-2 py-1">{{ item.type_name }}</span>
                                                    </div>
                                                </td>
                                                <td class="text-end">
                                                    <span class="badge bg-primary text-white" data-qty="{{ item.quantity }}">{{ item.quantity|intcomma }}</span>
                                                </td>
                                            </tr>
                                            {% endfor %}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    {% endif %}
                </div>
                <div id="materialsEmptyState" class="alert alert-info"{% if materials_by_group %} style="display:none;"{% endif %}>
                    <i class="fas fa-info-circle me-2"></i>{% trans "No material requirements have been detected for this blueprint." %}
                </div>
            </div>

            <div class="tab-pane fade {% if current_tab == 'tree' %}show active{% endif %}" id="tab-tree" role="tabpanel" aria-labelledby="tree-tab">
                <div class="tab-intro card card-intro shadow-sm border-0 mb-4">
                    <div class="card-body d-flex align-items-center gap-3">
                        <span class="tab-intro-icon text-success-emphasis bg-success-subtle"><i class="fas fa-sitemap"></i></span>
                        <div>
                            <h3 class="h6 text-uppercase text-muted mb-1">{% trans "Production tree controls" %}</h3>
                            <p class="mb-0 text-muted small">{% trans "Drill into the hierarchy, switch intermediate products between Buy and Prod, and let dependencies collapse automatically." %}</p>
                        </div>
                    </div>
                </div>
                <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
                    <div class="btn-group btn-group-sm" role="group" aria-label="{% trans 'Tree controls' %}">
                        <button class="btn btn-outline-secondary" type="button" id="expand-tree"><i class="fas fa-plus-square me-1"></i>{% trans "Expand all" %}</button>
                        <button class="btn btn-outline-secondary" type="button" id="collapse-tree"><i class="fas fa-minus-square me-1"></i>{% trans "Collapse all" %}</button>
                    </div>
                    <div class="btn-group btn-group-sm" role="group" aria-label="{% trans 'Mode shortcuts' %}">
                        <button class="btn btn-outline-success" type="button" id="set-tree-prod"><i class="fas fa-industry me-1"></i>{% trans "All prod" %}</button>
                        <button class="btn btn-outline-danger" type="button" id="set-tree-buy"><i class="fas fa-shopping-cart me-1"></i>{% trans "All buy" %}</button>
                    </div>
                </div>
                <div class="card shadow-sm">
                    <div class="card-header bg-info text-white fw-semibold">
                        <i class="fas fa-sitemap me-2"></i>{% trans "Production tree" %}
                    </div>
                    <div class="card-body">
                        {% if materials_tree %}
                            {% include "indy_hub/material_tree.html" with materials=materials_tree level=0 %}
                        {% else %}
                            <div class="alert alert-info mb-0">{% trans "No sub-productions detected for this blueprint." %}</div>
                        {% endif %}
                    </div>
                </div>
            </div>

            <div class="tab-pane fade {% if current_tab == 'cycles' %}show active{% endif %}" id="tab-cycles" role="tabpanel" aria-labelledby="cycles-tab">
                <div class="tab-intro card card-intro shadow-sm border-0 mb-4">
                    <div class="card-body d-flex align-items-center gap-3">
                        <span class="tab-intro-icon text-info-emphasis bg-info-subtle"><i class="fas fa-sync"></i></span>
                        <div>
                            <h3 class="h6 text-uppercase text-muted mb-1">{% trans "Cycle forecasting" %}</h3>
                            <p class="mb-0 text-muted small">{% trans "Compare what each production run yields versus what the project consumes to avoid shortages." %}</p>
                        </div>
                    </div>
                </div>
                {% if craft_cycles_summary %}
                <div class="card shadow-sm">
                    <div class="card-header bg-body-secondary fw-semibold d-flex align-items-center justify-content-between">
                        <span><i class="fas fa-sync me-2 text-primary"></i>{% trans "Production cycles overview" %}</span>
                        <span class="badge bg-primary-subtle text-primary fw-semibold">{{ craft_cycles_summary|length }}</span>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover align-middle mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th>{% trans "Item" %}</th>
                                        <th class="text-end">{% trans "Needed" %}</th>
                                        <th class="text-end">{% trans "Per cycle" %}</th>
                                        <th class="text-end">{% trans "Cycles" %}</th>
                                        <th class="text-end">{% trans "Produced" %}</th>
                                        <th class="text-end">{% trans "Surplus" %}</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for type_id, data in craft_cycles_summary.items %}
                                    <tr data-type-id="{{ type_id }}">
                                        <td>
                                            <div class="d-flex align-items-center gap-3">
                                                <img src="https://images.evetech.net/types/{{ type_id }}/icon?size=32" alt="{{ data.type_name }}" class="rounded" style="width:30px;height:30px;background:#f3f4f6;" onerror="this.style.display='none';">
                                                <div>
                                                    <div class="fw-semibold">{{ data.type_name }}</div>
                                                </div>
                                            </div>
                                        </td>
                                        <td class="text-end"><span class="badge bg-primary-subtle text-primary fw-semibold">{{ data.total_needed|intcomma }}</span></td>
                                        <td class="text-end">{{ data.produced_per_cycle|intcomma }}</td>
                                        <td class="text-end">{{ data.cycles|intcomma }}</td>
                                        <td class="text-end text-success fw-semibold">{{ data.total_produced|intcomma }}</td>
                                        <td class="text-end">
                                            {% if data.surplus > 0 %}
                                                <span class="badge bg-success-subtle text-success fw-semibold">+{{ data.surplus|intcomma }}</span>
                                            {% elif data.surplus < 0 %}
                                                <span class="badge bg-danger-subtle text-danger fw-semibold">{{ data.surplus|intcomma }}</span>
                                            {% else %}
                                                <span class="badge bg-secondary-subtle text-secondary">{{ data.surplus|intcomma }}</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                {% else %}
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i>{% trans "This blueprint does not have any intermediate craftable items requiring cycle calculations." %}
                </div>
                {% endif %}
            </div>

            <div class="tab-pane fade {% if current_tab == 'financial' %}show active{% endif %}" id="tab-financial" role="tabpanel" aria-labelledby="financial-tab">
                <div class="tab-intro card card-intro shadow-sm border-0 mb-4">
                    <div class="card-body d-flex align-items-center gap-3">
                        <span class="tab-intro-icon text-warning-emphasis bg-warning-subtle"><i class="fas fa-file-invoice-dollar"></i></span>
                        <div>
                            <h3 class="h6 text-uppercase text-muted mb-1">{% trans "Financial cockpit" %}</h3>
                            <p class="mb-0 text-muted small">{% trans "Fetch market references, override prices manually and track profitability in real time." %}</p>
                        </div>
                    </div>
                </div>
                <div class="row row-cols-1 row-cols-sm-2 row-cols-xl-5 g-3 mb-4">
                    <div class="col">
                        <div class="card shadow-sm border-0 h-100">
                            <div class="card-body">
                                <div class="text-muted text-uppercase small fw-semibold">{% trans "Total cost" %}</div>
                                <div class="fs-5 fw-bold text-danger" id="financialSummaryCost">0 ISK</div>
                            </div>
                        </div>
                    </div>
                    <div class="col">
                        <div class="card shadow-sm border-0 h-100">
                            <div class="card-body">
                                <div class="text-muted text-uppercase small fw-semibold">{% trans "Total revenue" %}</div>
                                <div class="fs-5 fw-bold text-success" id="financialSummaryRevenue">0 ISK</div>
                            </div>
                        </div>
                    </div>
                    <div class="col">
                        <div class="card shadow-sm border-0 h-100">
                            <div class="card-body">
                                <div class="text-muted text-uppercase small fw-semibold">{% trans "Profit" %}</div>
                                <div class="fs-5 fw-bold" id="financialSummaryProfit">0 ISK</div>
                            </div>
                        </div>
                    </div>
                    <div class="col">
                        <div class="card shadow-sm border-0 h-100">
                            <div class="card-body">
                                <div class="text-muted text-uppercase small fw-semibold">{% trans "Margin" %}</div>
                                <div class="fs-5 fw-bold" id="financialSummaryMargin">0%</div>
                            </div>
                        </div>
                    </div>
                    <div class="col">
                        <div class="card shadow-sm border-0 h-100">
                            <div class="card-body">
                                <div class="text-muted text-uppercase small fw-semibold">{% trans "Last updated" %}</div>
                                <div class="fs-6 fw-semibold" id="financialSummaryUpdated">—</div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card shadow-sm">
                    <div class="card-header bg-body-secondary fw-semibold d-flex align-items-center justify-content-between gap-2 flex-wrap">
                        <span class="d-flex align-items-center gap-2"><i class="fas fa-file-invoice-dollar text-success"></i>{% trans "Purchase planner" %}</span>
                        <div class="d-flex gap-2 flex-wrap">
                            <button id="resetManualPricesBtn" type="button" class="btn btn-outline-secondary btn-sm">
                                <i class="fas fa-undo-alt me-1"></i>{% trans "Reset overrides" %}
                            </button>
                            <button id="loadFuzzworkBtn" type="button" class="btn btn-outline-info btn-sm">
                                <i class="fas fa-cloud-download-alt me-1"></i>{% trans "Load Fuzzwork prices" %}
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <p class="text-muted small mb-4">
                            <i class="fas fa-lightbulb me-2 text-warning"></i>
                            {% trans "Switch items to Buy in the tree tab to include them here. Adjust the real price column with your market assumptions." %}
                        </p>
                        <div class="invoice-box border rounded-3 overflow-hidden">
                            <div class="table-responsive">
                                <table class="table table-hover align-middle mb-0">
                                    <thead class="table-light">
                                        <tr>
                                            <th>{% trans "Item" %}</th>
                                            <th class="text-end">{% trans "Qty" %}</th>
                                            <th class="text-end">{% trans "Fuzzwork price" %}</th>
                                            <th class="text-end">{% trans "Real price" %}</th>
                                            <th class="text-end">{% trans "Line total" %}</th>
                                        </tr>
                                    </thead>
                                    <tbody id="financialItemsBody">
                                        {% for mat in materials %}
                                        <tr data-type-id="{{ mat.type_id }}">
                                            <td class="fw-semibold">
                                                <div class="d-flex align-items-center gap-3">
                                                    <img src="https://images.evetech.net/types/{{ mat.type_id }}/icon?size=32" alt="{{ mat.type_name }}" class="rounded" style="width:28px;height:28px;background:#f3f4f6;" onerror="this.style.display='none';">
                                                    <span class="badge bg-info-subtle text-info-emphasis px-2 py-1">{{ mat.type_name }}</span>
                                                </div>
                                            </td>
                                            <td class="text-end" data-qty="{{ mat.quantity }}">
                                                <span class="badge bg-primary text-white">{{ mat.quantity|intcomma }}</span>
                                            </td>
                                            <td class="text-end">
                                                <input type="number" min="0" step="0.01" class="form-control form-control-sm fuzzwork-price text-end bg-light" data-type-id="{{ mat.type_id }}" value="0" readonly>
                                            </td>
                                            <td class="text-end">
                                                <input type="number" min="0" step="0.01" class="form-control form-control-sm real-price text-end" data-type-id="{{ mat.type_id }}" value="0">
                                            </td>
                                            <td class="text-end total-cost">0</td>
                                        </tr>
                                        {% endfor %}
                                        <tr id="finalProductRow" class="table-success fw-semibold" data-type-id="{{ product_type_id|default:0 }}">
                                            <td>
                                                <div class="d-flex align-items-center gap-3">
                                                    <img src="https://images.evetech.net/types/{{ product_type_id }}/icon?size=32" alt="{% trans 'Final product' %}" class="rounded" style="width:28px;height:28px;background:#f3f4f6;" onerror="this.style.display='none';">
                                                    <span>{% trans "Final product" %}</span>
                                                </div>
                                            </td>
                                            <td class="text-end" data-qty="{{ final_product_qty|default:num_runs }}">
                                                <span class="badge bg-success text-white">{{ final_product_qty|default:num_runs|intcomma }}</span>
                                            </td>
                                            <td class="text-end">
                                                <input type="number" min="0" step="0.01" class="form-control form-control-sm fuzzwork-price text-end bg-light" data-type-id="{{ product_type_id|default:0 }}" value="0" readonly>
                                            </td>
                                            <td class="text-end">
                                                <input type="number" min="0" step="0.01" class="form-control form-control-sm sale-price-unit text-end" data-type-id="{{ product_type_id|default:0 }}" value="0">
                                            </td>
                                            <td class="text-end total-revenue">0</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            <table class="table table-borderless mb-0">
                                <tfoot>
                                    <tr>
                                        <th colspan="4" class="text-end text-muted">{% trans "Total cost" %}</th>
                                        <th class="text-end grand-total-cost fw-semibold text-danger">0</th>
                                    </tr>
                                    <tr>
                                        <th colspan="4" class="text-end text-muted">{% trans "Total revenue" %}</th>
                                        <th class="text-end grand-total-rev fw-semibold text-success">0</th>
                                    </tr>
                                    <tr>
                                        <th colspan="4" class="text-end text-muted">{% trans "Profit" %}</th>
                                        <th class="text-end profit fw-bold">0 <span class="profit-pct text-muted">(0%)</span></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade {% if current_tab == 'needed' %}show active{% endif %}" id="tab-needed" role="tabpanel" aria-labelledby="needed-tab">
                <div class="tab-intro card card-intro shadow-sm border-0 mb-4">
                    <div class="card-body d-flex align-items-center gap-3">
                        <span class="tab-intro-icon text-warning-emphasis bg-warning-subtle"><i class="fas fa-cart-arrow-down"></i></span>
                        <div>
                            <h3 class="h6 text-uppercase text-muted mb-1">{% trans "Shopping assistant" %}</h3>
                            <p class="mb-0 text-muted small">{% trans "Rebuild the list after toggling Buy modes to export accurate purchase quantities." %}</p>
                        </div>
                    </div>
                </div>
                <div class="card shadow-sm">
                    <div class="card-header bg-warning-subtle text-warning-emphasis fw-semibold d-flex align-items-center justify-content-between">
                        <span><i class="fas fa-shopping-cart me-2"></i>{% trans "Items to purchase" %}</span>
                        <button id="compute-needed" class="btn btn-outline-warning btn-sm">
                            <i class="fas fa-calculator me-1"></i>{% trans "Compute list" %}
                        </button>
                    </div>
                    <div class="card-body">
                        <p class="text-muted small mb-3">
                            {% trans "Use the production tree to decide which components you will manufacture versus buy. This table recomputes the shopping list." %}
                        </p>
                        <div class="table-responsive">
                            <table class="table table-striped align-middle" id="needed-table">
                                <thead class="table-light">
                                    <tr>
                                        <th>{% trans "Item" %}</th>
                                        <th class="text-end">{% trans "Qty" %}</th>
                                        <th class="text-end">{% trans "Unit price" %}</th>
                                        <th class="text-end">{% trans "Line total" %}</th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                                <tfoot>
                                    <tr>
                                        <th colspan="3" class="text-end">{% trans "Total cost" %}</th>
                                        <th class="text-end purchase-total">0</th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade {% if current_tab == 'config' %}show active{% endif %}" id="tab-config" role="tabpanel" aria-labelledby="config-tab">
                <div class="tab-intro card card-intro shadow-sm border-0 mb-4">
                    <div class="card-body d-flex align-items-center gap-3">
                        <span class="tab-intro-icon text-danger-emphasis bg-danger-subtle"><i class="fas fa-sliders-h"></i></span>
                        <div>
                            <h3 class="h6 text-uppercase text-muted mb-1">{% trans "Blueprint fine-tuning" %}</h3>
                            <p class="mb-0 text-muted small">{% trans "Adjust ME/TE on child blueprints; changes apply when switching tabs or saving simulations." %}</p>
                        </div>
                    </div>
                </div>
                {% if blueprint_configs_grouped %}
                <div class="accordion" id="blueprintConfigAccordion">
                    {% for group in blueprint_configs_grouped %}
                    <div class="accordion-item">
                        <h2 class="accordion-header" id="heading-group-{{ forloop.counter }}">
                            <button class="accordion-button {% if not forloop.first %}collapsed{% endif %}" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-group-{{ forloop.counter }}" aria-expanded="{% if forloop.first %}true{% else %}false{% endif %}" aria-controls="collapse-group-{{ forloop.counter }}">
                                <i class="fas fa-scroll me-2 text-primary"></i>{{ group.group_name }}
                            </button>
                        </h2>
                        <div id="collapse-group-{{ forloop.counter }}" class="accordion-collapse collapse {% if forloop.first %}show{% endif %}" aria-labelledby="heading-group-{{ forloop.counter }}" data-bs-parent="#blueprintConfigAccordion">
                            <div class="accordion-body">
                                {% for level in group.levels %}
                                <div class="mb-4">
                                    <h6 class="fw-semibold text-muted mb-2">
                                        <i class="fas fa-layer-group me-2 text-secondary"></i>{% trans "Blueprint level" %} {{ level.level }}
                                    </h6>
                                    <div class="table-responsive">
                                        <table class="table table-sm align-middle">
                                            <thead class="table-light">
                                                <tr>
                                                    <th style="width:35%">{% trans "Blueprint" %}</th>
                                                    <th style="width:15%" class="text-center">{% trans "ME" %}</th>
                                                    <th style="width:15%" class="text-center">{% trans "TE" %}</th>
                                                    <th>{% trans "Product" %}</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {% for bc in level.blueprints %}
                                                <tr data-blueprint-type-id="{{ bc.type_id }}">
                                                    <td class="fw-semibold">
                                                        <div class="d-flex align-items-center gap-3">
                                                            <img src="https://images.evetech.net/types/{{ bc.type_id }}/bp?size=32" alt="{{ bc.type_name }}" class="rounded" style="width:30px;height:30px;background:#f3f4f6;" onerror="this.style.display='none';">
                                                            <span>{{ bc.type_name }}</span>
                                                        </div>
                                                    </td>
                                                    <td class="text-center">
                                                        <input type="number" name="me_{{ bc.type_id }}" value="{{ bc.material_efficiency }}" min="0" max="10" class="form-control form-control-sm text-center">
                                                    </td>
                                                    <td class="text-center">
                                                        <input type="number" name="te_{{ bc.type_id }}" value="{{ bc.time_efficiency }}" min="0" max="20" class="form-control form-control-sm text-center">
                                                    </td>
                                                    <td>
                                                        {% if bc.product_type_id %}
                                                        <div class="d-flex align-items-center gap-3">
                                                            <img src="https://images.evetech.net/types/{{ bc.product_type_id }}/icon?size=32" alt="{{ bc.product_type_name }}" class="rounded" style="width:30px;height:30px;background:#f3f4f6;" onerror="this.style.display='none';">
                                                            <span class="badge bg-info-subtle text-info-emphasis px-2 py-1">{{ bc.product_type_name }}</span>
                                                        </div>
                                                        {% else %}
                                                        <span class="text-muted">{% trans "No product detected" %}</span>
                                                        {% endif %}
                                                    </td>
                                                </tr>
                                                {% endfor %}
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                                {% endfor %}
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
                {% else %}
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i>{% trans "No child blueprints require configuration tweaks for this item." %}
                </div>
                {% endif %}
            </div>
        </div>
    </div>
    {% endwith %}

    <!-- Save simulation modal -->
    <div class="modal fade" id="saveSimulationModal" tabindex="-1" aria-labelledby="saveSimulationModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="saveSimulationModalLabel"><i class="fas fa-save me-2"></i>{% trans "Save production simulation" %}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{% trans 'Close' %}"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>{% trans "Saved simulations keep your production, price and configuration choices so you can resume later." %}
                    </div>
                    <div class="mb-3">
                        <label for="simulationName" class="form-label fw-semibold">{% trans "Simulation name" %}</label>
                        <input type="text" class="form-control" id="simulationName" placeholder="{% trans 'Example: Doctrine fit batch' %}">
                    </div>
                    <div class="border rounded-3 p-3 bg-body-tertiary">
                        <h6 class="fw-semibold mb-3">{% trans "Summary" %}</h6>
                        <dl class="row mb-0">
                            <dt class="col-sm-6">{% trans "Runs" %}</dt>
                            <dd class="col-sm-6" id="summaryRuns">{{ num_runs|default:1|intcomma }}</dd>
                            <dt class="col-sm-6">{% trans "Production items" %}</dt>
                            <dd class="col-sm-6" id="summaryProdItems">0</dd>
                            <dt class="col-sm-6">{% trans "Buy items" %}</dt>
                            <dd class="col-sm-6" id="summaryBuyItems">0</dd>
                            <dt class="col-sm-6">{% trans "Estimated profit" %}</dt>
                            <dd class="col-sm-6" id="summaryProfit">0</dd>
                        </dl>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">{% trans "Cancel" %}</button>
                    <button type="button" class="btn btn-primary" id="confirmSaveSimulation">
                        <i class="fas fa-save me-1"></i>{% trans "Save simulation" %}
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Load simulation modal -->
    <div class="modal fade" id="loadSimulationModal" tabindex="-1" aria-labelledby="loadSimulationModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="loadSimulationModalLabel"><i class="fas fa-folder-open me-2"></i>{% trans "Load saved simulation" %}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{% trans 'Close' %}"></button>
                </div>
                <div class="modal-body">
                    <div id="simulationsList">
                        <div class="text-center py-4 text-muted">
                            <i class="fas fa-spinner fa-spin fa-2x mb-3"></i>
                            <p class="mb-0">{% trans "Loading saved simulations…" %}</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">{% trans "Close" %}</button>
                </div>
            </div>
        </div>
    </div>
</div>
</main>
{% endblock content %}

{% block extra_javascript %}
{{ blueprint_payload|json_script:"blueprint-payload" }}

<script>
(function() {
    const payloadEl = document.getElementById('blueprint-payload');
    if (payloadEl) {
        try {
            const data = JSON.parse(payloadEl.textContent);
            window.BLUEPRINT_DATA = Object.assign({}, data, {
                save_url: data.urls ? data.urls.save : undefined,
                load_url: data.urls ? data.urls.load_list : undefined,
                load_config_url: data.urls ? data.urls.load_config : undefined,
                fuzzwork_price_url: data.urls ? data.urls.fuzzwork_price : undefined
            });
        } catch (error) {
            console.error('Failed to parse blueprint payload:', error);
            window.BLUEPRINT_DATA = window.BLUEPRINT_DATA || {};
        }
    } else {
        window.BLUEPRINT_DATA = window.BLUEPRINT_DATA || {};
    }
})();
</script>
<script src="{% static 'indy_hub/js/craft_bp_simulation_api.js' %}"></script>
<script src="{% static 'indy_hub/js/craft_bp_active_tab.js' %}"></script>
<script src="{% static 'indy_hub/js/craft_bp.js' %}"></script>
<script src="{% static 'indy_hub/js/craft_bp_inline.js' %}"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const controlForm = document.getElementById('blueprint-control-form');
    const activeTabInput = document.getElementById('activeTabInput');
    if (controlForm && activeTabInput) {
        controlForm.addEventListener('submit', function() {
            const activeTab = document.querySelector('#bpTabs .nav-link.active');
            if (activeTab) {
                const target = activeTab.getAttribute('data-bs-target');
                if (target) {
                    activeTabInput.value = target.replace('#tab-', '');
                }
            }
        });
    }

    if (window.CraftBP && typeof window.CraftBP.init === 'function') {
        window.CraftBP.init({
            productTypeId: '{{ product_type_id|default:0 }}',
            fuzzworkPriceUrl: '{% url "indy_hub:fuzzwork_price" %}'
        });
    }
});
</script>
{% endblock extra_javascript %}
