{% extends 'layout.twig' %}

{% block title %}{{ detail.ip }} — IRDB{% endblock %}

{% macro flag(country) %}
    {%- set emoji = flag_emoji(country) -%}
    {%- if emoji -%}
        <span class="text-base leading-none">{{- emoji -}}</span>
    {%- else -%}
        <span class="rounded bg-slate-100 px-1.5 py-0.5 font-mono text-[0.65rem] text-slate-500 dark:bg-slate-800 dark:text-slate-400">??</span>
    {%- endif -%}
{% endmacro %}

{% macro status_pill(status) %}
    {%- set classes = {
        'allowlisted':      'bg-emerald-100 text-emerald-900 dark:bg-emerald-900 dark:text-emerald-100',
        'manually_blocked': 'bg-amber-100 text-amber-900 dark:bg-amber-900 dark:text-amber-100',
        'scored':           'bg-red-100 text-red-900 dark:bg-red-900 dark:text-red-100',
        'clean':            'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300',
    } -%}
    <span class="rounded px-2.5 py-1 font-mono text-xs uppercase {{ classes[status]|default('bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300') }}">{{ status }}</span>
{% endmacro %}

{% block content %}
{% import _self as h %}
<div class="mx-auto max-w-5xl">
    <a href="/app/ips" class="text-sm text-slate-500 hover:underline dark:text-slate-400">← Back to IPs</a>

    <div class="mt-3 flex items-center justify-between">
        <h1 class="font-mono text-2xl font-semibold tracking-tight">{{ detail.ip }}</h1>
        {{ h.status_pill(detail.status) }}
    </div>
    <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">{{ detail.isIpv4 ? 'IPv4' : 'IPv6' }}</p>

    {% if can_write|default(false) %}
        <div class="mt-4 flex flex-wrap items-center gap-2 text-sm">
            {% if detail.allowlist %}
                <form method="post" action="/app/allowlist/{{ detail.allowlist.id }}/delete" class="inline">
                    <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
                    <input type="hidden" name="next" value="/app/ips/{{ detail.ip|url_encode }}">
                    <button type="submit" class="rounded-md border border-emerald-300 px-3 py-1 text-xs font-medium text-emerald-700 hover:bg-emerald-50 dark:border-emerald-700 dark:text-emerald-300 dark:hover:bg-slate-800">Remove from allowlist</button>
                </form>
            {% else %}
                <div x-data="toggle" class="inline">
                    <button type="button" x-on:click="show()" class="rounded-md border border-emerald-300 px-3 py-1 text-xs font-medium text-emerald-700 hover:bg-emerald-50 dark:border-emerald-700 dark:text-emerald-300 dark:hover:bg-slate-800">Add to allowlist…</button>
                    <div x-show="open" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 px-4">
                        <form method="post" action="/app/allowlist" x-on:click.outside="hide()" class="w-full max-w-sm rounded-2xl border border-slate-200 bg-white p-6 shadow-lg dark:border-slate-800 dark:bg-slate-900">
                            <h2 class="text-base font-semibold">Add {{ detail.ip }} to allowlist</h2>
                            <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
                            <input type="hidden" name="kind" value="ip">
                            <input type="hidden" name="ip" value="{{ detail.ip }}">
                            <label class="mt-3 block text-xs font-medium text-slate-600 dark:text-slate-400">Reason (optional)</label>
                            <input type="text" name="reason" class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2 py-1.5 text-sm dark:border-slate-700 dark:bg-slate-950">
                            <div class="mt-4 flex justify-end gap-2">
                                <button type="button" x-on:click="hide()" class="rounded-md border border-slate-300 px-3 py-1.5 text-sm hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800">Cancel</button>
                                <button type="submit" class="rounded-md bg-emerald-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-emerald-500">Add</button>
                            </div>
                        </form>
                    </div>
                </div>
            {% endif %}

            {% if detail.manualBlock %}
                <form method="post" action="/app/manual-blocks/{{ detail.manualBlock.id }}/delete" class="inline">
                    <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
                    <input type="hidden" name="next" value="/app/ips/{{ detail.ip|url_encode }}">
                    <button type="submit" class="rounded-md border border-amber-300 px-3 py-1 text-xs font-medium text-amber-700 hover:bg-amber-50 dark:border-amber-700 dark:text-amber-300 dark:hover:bg-slate-800">Remove manual block</button>
                </form>
            {% else %}
                <div x-data="toggle" class="inline">
                    <button type="button" x-on:click="show()" class="rounded-md border border-amber-300 px-3 py-1 text-xs font-medium text-amber-700 hover:bg-amber-50 dark:border-amber-700 dark:text-amber-300 dark:hover:bg-slate-800">Manually block…</button>
                    <div x-show="open" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 px-4">
                        <form method="post" action="/app/manual-blocks" x-on:click.outside="hide()" class="w-full max-w-sm rounded-2xl border border-slate-200 bg-white p-6 shadow-lg dark:border-slate-800 dark:bg-slate-900">
                            <h2 class="text-base font-semibold">Manually block {{ detail.ip }}</h2>
                            <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
                            <input type="hidden" name="kind" value="ip">
                            <input type="hidden" name="ip" value="{{ detail.ip }}">
                            <label class="mt-3 block text-xs font-medium text-slate-600 dark:text-slate-400">Reason (optional)</label>
                            <input type="text" name="reason" class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2 py-1.5 text-sm dark:border-slate-700 dark:bg-slate-950">
                            <label class="mt-3 block text-xs font-medium text-slate-600 dark:text-slate-400">Expires at (optional)</label>
                            <input type="datetime-local" name="expires_at" class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2 py-1.5 text-sm dark:border-slate-700 dark:bg-slate-950">
                            <div class="mt-4 flex justify-end gap-2">
                                <button type="button" x-on:click="hide()" class="rounded-md border border-slate-300 px-3 py-1.5 text-sm hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800">Cancel</button>
                                <button type="submit" class="rounded-md bg-amber-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-amber-500">Block</button>
                            </div>
                        </form>
                    </div>
                </div>
            {% endif %}
        </div>
    {% endif %}

    <section class="mt-6 grid grid-cols-1 gap-4 lg:grid-cols-2">
        <div class="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm dark:border-slate-800 dark:bg-slate-900">
            <h2 class="text-sm font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Enrichment</h2>
            {% if detail.enrichment.country_code or detail.enrichment.asn %}
                <dl class="mt-3 grid grid-cols-3 gap-y-2 text-sm">
                    <dt class="text-slate-500 dark:text-slate-400">Country</dt>
                    <dd class="col-span-2 font-mono">{{ h.flag(detail.enrichment.country_code) }} <span>{{ detail.enrichment.country_code|default('—') }}</span></dd>
                    <dt class="text-slate-500 dark:text-slate-400">ASN</dt>
                    <dd class="col-span-2 font-mono">
                        {% if detail.enrichment.asn %}
                            <a href="https://bgp.he.net/AS{{ detail.enrichment.asn }}" target="_blank" rel="noopener" class="text-indigo-600 hover:underline dark:text-indigo-400">AS{{ detail.enrichment.asn }}</a>
                        {% else %}—{% endif %}
                    </dd>
                    <dt class="text-slate-500 dark:text-slate-400">AS org</dt>
                    <dd class="col-span-2">{{ detail.enrichment.as_org|default('—') }}</dd>
                </dl>
                {% if detail.enrichment.enriched_at %}
                    <p class="mt-3 text-xs text-slate-400">Enriched <time class="irdb-dt" datetime="{{ detail.enrichment.enriched_at }}">{{ detail.enrichment.enriched_at }}</time></p>
                {% endif %}
            {% else %}
                <p class="mt-3 text-sm text-slate-400">
                    <span class="rounded bg-slate-100 px-1.5 py-0.5 text-xs text-slate-500 dark:bg-slate-800">Unknown</span>
                    not yet enriched.
                </p>
            {% endif %}
            {% if geoip_provider == 'dbip' %}
                <p class="mt-4 border-t border-slate-100 pt-3 text-[0.65rem] text-slate-400 dark:border-slate-800">IP Geolocation by <a href="https://db-ip.com" target="_blank" rel="noopener" class="hover:underline">DB-IP</a> (CC BY 4.0)</p>
            {% elseif geoip_provider == 'ipinfo' %}
                <p class="mt-4 border-t border-slate-100 pt-3 text-[0.65rem] text-slate-400 dark:border-slate-800">IP data powered by <a href="https://ipinfo.io" target="_blank" rel="noopener" class="hover:underline">IPinfo</a></p>
            {% endif %}
        </div>

        <div class="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm dark:border-slate-800 dark:bg-slate-900">
            <h2 class="text-sm font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Override status</h2>
            {% if detail.allowlist %}
                <p class="mt-3 text-sm">Allowlisted since
                    <time class="irdb-dt font-mono" datetime="{{ detail.allowlist.created_at }}">{{ detail.allowlist.created_at }}</time>.
                    {% if detail.allowlist.reason %}<br><span class="text-slate-500 dark:text-slate-400">Reason:</span> {{ detail.allowlist.reason }}{% endif %}
                </p>
            {% elseif detail.manualBlock %}
                <p class="mt-3 text-sm">Manually blocked since
                    <time class="irdb-dt font-mono" datetime="{{ detail.manualBlock.created_at }}">{{ detail.manualBlock.created_at }}</time>.
                    {% if detail.manualBlock.reason %}<br><span class="text-slate-500 dark:text-slate-400">Reason:</span> {{ detail.manualBlock.reason }}{% endif %}
                </p>
            {% else %}
                <p class="mt-3 text-sm text-slate-400">No manual override on this IP.</p>
            {% endif %}
        </div>
    </section>

    <section class="mt-6 rounded-2xl border border-slate-200 bg-white p-5 shadow-sm dark:border-slate-800 dark:bg-slate-900">
        <h2 class="text-sm font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Score per category</h2>
        {% if detail.scores|length > 0 %}
            {% set max_score = detail.maxScore() %}
            <ul class="mt-3 space-y-3 text-sm">
                {% for s in detail.scores %}
                    {% set width_pct = max_score > 0 ? (s.score / max_score * 100) : 0 %}
                    {# SEC_REVIEW F62: bucket the dynamic width into 5%
                       steps and render as a `data-score-width` attribute.
                       The bundled stylesheet (`resources/css/app.css`)
                       ships one rule per bucket, so dropping
                       `style-src 'unsafe-inline'` from CSP doesn't break
                       the visual. 5% buckets are visually indistinguishable
                       from per-pixel widths on this 1.5px-tall bar. #}
                    {% set width_bucket = (width_pct / 5)|round * 5 %}
                    <li>
                        <div class="flex items-baseline justify-between">
                            <span class="font-mono">{{ s.category|default('?') }}</span>
                            <span class="font-mono text-slate-600 dark:text-slate-300">{{ s.score|number_format(2) }} <span class="text-xs text-slate-400">({{ s.report_count_30d }} in 30d)</span></span>
                        </div>
                        <div class="mt-1 h-1.5 overflow-hidden rounded bg-slate-100 dark:bg-slate-800">
                            <div class="h-full bg-indigo-500" data-score-width="{{ width_bucket }}"></div>
                        </div>
                    </li>
                {% endfor %}
            </ul>
        {% else %}
            <p class="mt-3 text-sm text-slate-400">No scored categories.</p>
        {% endif %}
    </section>

    <section class="mt-6 rounded-2xl border border-slate-200 bg-white p-5 shadow-sm dark:border-slate-800 dark:bg-slate-900"
             x-data="scoreOverTime"
             data-score-chart="{{ {reports: score_chart.reports, categories: score_chart.categories, now: score_chart.now}|json_encode|e('html_attr') }}">
        <div class="flex flex-wrap items-center justify-between gap-3">
            <h2 class="text-sm font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Score over time</h2>
            <div class="inline-flex overflow-hidden rounded-md border border-slate-300 text-xs dark:border-slate-700">
                <template x-for="opt in ranges" :key="opt.id">
                    <button type="button"
                            x-on:click="setRange(opt.id)"
                            :class="classForRange(opt.id)"
                            x-text="opt.label"></button>
                </template>
            </div>
        </div>

        <template x-if="hasNoReports">
            <p class="mt-3 text-sm text-slate-400">No reports yet — nothing to plot.</p>
        </template>

        <template x-if="hasReports">
            <div>
                <svg viewBox="0 0 660 240" class="mt-3 w-full rounded border border-slate-200 bg-slate-50 dark:border-slate-800 dark:bg-slate-950" preserveAspectRatio="none">
                    <g class="stroke-slate-200 dark:stroke-slate-800" stroke-width="1">
                        <line x1="50" y1="20"  x2="640" y2="20"/>
                        <line x1="50" y1="65"  x2="640" y2="65"/>
                        <line x1="50" y1="110" x2="640" y2="110"/>
                        <line x1="50" y1="155" x2="640" y2="155"/>
                    </g>
                    <line x1="50" y1="200" x2="640" y2="200" class="stroke-slate-300 dark:stroke-slate-700" stroke-width="1"/>
                    <line x1="50" y1="20"  x2="50"  y2="200" class="stroke-slate-300 dark:stroke-slate-700" stroke-width="1"/>

                    <template x-if="isFuture()">
                        <rect x="50" y="20" width="590" height="180" class="fill-amber-50 dark:fill-amber-900/20" />
                    </template>

                    <g font-size="10" text-anchor="end" class="fill-slate-500 dark:fill-slate-400">
                        <text x="46" y="23"  x-text="yLabel(1.0)"></text>
                        <text x="46" y="68"  x-text="yLabel(0.75)"></text>
                        <text x="46" y="113" x-text="yLabel(0.5)"></text>
                        <text x="46" y="158" x-text="yLabel(0.25)"></text>
                        <text x="46" y="203">0</text>
                    </g>

                    <g font-size="10" text-anchor="middle" class="fill-slate-500 dark:fill-slate-400">
                        <text x="50"  y="216" x-text="xLabel(0)"></text>
                        <text x="197" y="216" x-text="xLabel(0.25)"></text>
                        <text x="345" y="216" x-text="xLabel(0.5)"></text>
                        <text x="492" y="216" x-text="xLabel(0.75)"></text>
                        <text x="640" y="216" x-text="xLabel(1)"></text>
                    </g>
                    <text x="345" y="232" font-size="10" text-anchor="middle" class="fill-slate-500 dark:fill-slate-400" x-text="xAxisCaption()"></text>

                    <path :d="path()" stroke="currentColor" class="text-indigo-500" fill="none" stroke-width="2"/>
                </svg>
                <p class="mt-2 text-xs text-slate-400">
                    <span x-text="rangeLabel()"></span> · max: <span x-text="maxScoreLabel"></span>
                    <template x-if="isFuture()">
                        <span class="ml-2 text-amber-600 dark:text-amber-400">forecast assumes no new reports</span>
                    </template>
                </p>
            </div>
        </template>
    </section>

    <section class="mt-6 rounded-2xl border border-slate-200 bg-white p-5 shadow-sm dark:border-slate-800 dark:bg-slate-900">
        <h2 class="text-sm font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">History</h2>
        {% if detail.history|length > 0 %}
            <ol class="mt-3 space-y-3 text-sm">
                {% for ev in detail.history %}
                    <li class="border-l-2 border-slate-200 pl-3 dark:border-slate-800">
                        <div class="flex items-baseline justify-between">
                            <span class="font-mono text-xs uppercase tracking-wider text-slate-500 dark:text-slate-400">
                                {{ ev.type }}
                            </span>
                            <time class="irdb-dt font-mono text-xs text-slate-400" datetime="{{ ev.at }}">{{ ev.at }}</time>
                        </div>
                        {% if ev.type == 'report' %}
                            <p class="mt-1">
                                {% if ev.category %}<span class="font-mono">{{ ev.category }}</span>{% endif %}
                                {% if ev.reporter %}<span class="text-slate-500 dark:text-slate-400"> via {{ ev.reporter }}</span>{% endif %}
                                {% if ev.weight %}<span class="text-slate-400"> · w={{ ev.weight }}</span>{% endif %}
                            </p>
                            {% if ev.metadata %}
                                <pre class="mt-1 overflow-x-auto rounded bg-slate-50 p-2 text-xs dark:bg-slate-950">{{ ev.metadata|json_encode(constant('JSON_PRETTY_PRINT')) }}</pre>
                            {% endif %}
                        {% elseif ev.type == 'manual_block_added' %}
                            <p class="mt-1">Manual block added{% if ev.reason %}: <span class="text-slate-600 dark:text-slate-300">{{ ev.reason }}</span>{% endif %}</p>
                        {% elseif ev.type == 'allowlist_added' %}
                            <p class="mt-1">Allowlist entry added{% if ev.reason %}: <span class="text-slate-600 dark:text-slate-300">{{ ev.reason }}</span>{% endif %}</p>
                        {% endif %}
                    </li>
                {% endfor %}
            </ol>
            {% if detail.hasMore %}
                <p class="mt-3 text-xs text-slate-500 dark:text-slate-400">Showing the most recent 200 events. Older events are available via the API directly until the in-app pagination lands in a future milestone.</p>
            {% endif %}
        {% else %}
            <p class="mt-3 text-sm text-slate-400">No history yet.</p>
        {% endif %}
    </section>
</div>

{% endblock %}
