'use client';

/**
 * Network status — full-viewport command board (no scroll, built for
 * projection). A dominant world map fills the top-left, the region rail sits
 * top-right, and a down-first monitor strip spans the bottom. Clicking a map
 * signal or a region chip drills the strip + zooms the map; click again or the
 * ✕ clears it.
 */
import { useState } from 'react';
import { useSentinelContext } from '../../_components/SentinelDataContext';
import { WorldMap } from '../../_components/WorldMap';
import { FadeUp, LiveDot, ResponseMeter, StatusDot } from '../../_components/primitives';
import { FLAGS } from '../../_components/regions';
import { uptimeStatus, responseStatus } from '@/lib/executive/status';
import type { MonitorRow, StatusLevel } from '@/lib/executive/types';

const STATUS_COLOR: Record<StatusLevel, string> = { healthy: 'var(--ok-fg)', warning: 'var(--warn-fg)', critical: 'var(--crit-fg)' };

function MonitorStatusPill({ status }: { status: MonitorRow['status'] }) {
    const map = {
        up: { label: 'Operational', level: 'healthy' as StatusLevel },
        down: { label: 'Down', level: 'critical' as StatusLevel },
        unknown: { label: 'Unknown', level: 'warning' as StatusLevel },
    }[status];
    const color = STATUS_COLOR[map.level];
    return (
        <span className="pill" style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 9px', fontFamily: 'var(--font-mono)', fontSize: 11, color, border: `1px solid color-mix(in srgb, ${color} 45%, transparent)` }}>
            <StatusDot status={map.level} size={6} />
            {map.label}
        </span>
    );
}

export default function NetworkPage() {
    const { data, cycle } = useSentinelContext();
    const [selected, setSelected] = useState<string | null>(null);
    if (!data) return null;

    const toggle = (code: string) => setSelected((s) => (s === code ? null : code));
    const filtered = selected ? data.monitors.filter((m) => m.region === selected) : data.monitors;
    // Down-first ordering, capped to what fits the wallboard strip (never scrolls).
    const order: Record<MonitorRow['status'], number> = { down: 0, unknown: 1, up: 2 };
    const sorted = [...filtered].sort((a, b) => order[a.status] - order[b.status]);
    const VISIBLE = 6;
    const rows = sorted.slice(0, VISIBLE);
    const moreCount = sorted.length - rows.length;
    const regionName = (code: string) => data.countryBreakdown.find((c) => c.code === code)?.country ?? code;

    const COLS = '2.2fr 0.7fr 1.1fr 1.3fr 2.4fr';

    return (
        <div
            key={cycle}
            style={{
                display: 'grid',
                gridTemplateColumns: '1fr 320px',
                gridTemplateRows: '1fr 252px',
                gridTemplateAreas: `"map regions" "table table"`,
                gap: 12,
                height: '100%',
                minHeight: 0,
            }}
        >
            {/* MAP */}
            <FadeUp className="glass-card" style={{ gridArea: 'map', padding: 16, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
                <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 8, flex: 'none' }}>
                    <span className="eyebrow">Global network</span>
                    <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--fg-3)' }}>
                        {selected ? `${regionName(selected)} · click ocean to zoom out` : 'click a signal to zoom into a country'}
                    </span>
                </div>
                <div style={{ flex: 1, minHeight: 0 }}>
                    <WorldMap countryBreakdown={data.countryBreakdown} monitors={data.monitors} selected={selected} onSelect={toggle} />
                </div>
                <div style={{ display: 'flex', gap: 18, marginTop: 8, flex: 'none', fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)' }}>
                    <Legend color="var(--ok)" label="Healthy" />
                    <Legend color="var(--warn)" label="Warning" />
                    <Legend color="var(--crit)" label="Critical" />
                </div>
            </FadeUp>

            {/* REGION RAIL */}
            <FadeUp index={1} className="glass-card" style={{ gridArea: 'regions', padding: 14, display: 'flex', flexDirection: 'column', gap: 8, minHeight: 0, overflow: 'hidden' }}>
                <div className="eyebrow" style={{ flex: 'none' }}>Regions</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8, flex: 1, minHeight: 0, overflow: 'hidden' }}>
                    {data.countryBreakdown.map((c) => {
                        const status = uptimeStatus(c.uptime);
                        const downs = data.monitors.filter((m) => m.region === c.code && m.status === 'down').length;
                        const isSel = selected === c.code;
                        return (
                            <button
                                key={c.code}
                                type="button"
                                onClick={() => toggle(c.code)}
                                style={{
                                    display: 'flex', alignItems: 'center', gap: 10, padding: '9px 12px', cursor: 'pointer', textAlign: 'left', width: '100%', flex: 'none',
                                    background: isSel ? 'color-mix(in srgb, var(--accent) 12%, transparent)' : 'var(--card-bg)',
                                    border: `1px solid ${isSel ? 'color-mix(in srgb, var(--accent) 45%, transparent)' : 'var(--hair)'}`,
                                    transition: 'transform 0.15s', transform: isSel ? 'translateX(3px)' : 'none',
                                }}
                            >
                                <span style={{ fontSize: 19, flex: 'none' }}>{FLAGS[c.code] ?? '🌐'}</span>
                                <span style={{ flex: 1, minWidth: 0 }}>
                                    <span style={{ display: 'block', fontSize: 13, fontWeight: 600, color: 'var(--fg)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{c.country}</span>
                                    <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--fg-3)' }}>{c.monitors} monitors{downs > 0 ? ` · ${downs} down` : ''}</span>
                                </span>
                                <span className="tnum" style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 600, color: STATUS_COLOR[status], flex: 'none' }}>{c.uptime.toFixed(1)}%</span>
                            </button>
                        );
                    })}
                </div>
            </FadeUp>

            {/* MONITOR STRIP */}
            <FadeUp index={2} className="glass-card" style={{ gridArea: 'table', padding: 16, display: 'flex', flexDirection: 'column', minHeight: 0, overflow: 'hidden' }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10, flex: 'none' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <h3 style={{ margin: 0, fontFamily: 'var(--font-heading)', fontSize: 16, fontWeight: 700, color: 'var(--fg)' }}>
                            Monitors{selected ? ` · ${regionName(selected)}` : ''}
                        </h3>
                        <span className="tnum" style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-3)' }}>{sorted.length}</span>
                        {selected && (
                            <button type="button" onClick={() => setSelected(null)} className="pill" style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 10px', cursor: 'pointer', background: 'color-mix(in srgb, var(--accent) 14%, transparent)', border: '1px solid color-mix(in srgb, var(--accent) 40%, transparent)', color: 'var(--accent)', fontFamily: 'var(--font-mono)', fontSize: 11 }}>
                                {FLAGS[selected]} Filtered · {regionName(selected)} ✕
                            </button>
                        )}
                    </div>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)' }}><LiveDot color="var(--ok)" size={6} /> live</span>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: COLS, gap: 8, fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.08em', paddingBottom: 7, borderBottom: '1px solid var(--hair)', flex: 'none' }}>
                    <span>Monitor</span><span>Type</span><span>Status</span><span>Response</span><span>Endpoint</span>
                </div>
                <div style={{ flex: 1, minHeight: 0, overflow: 'hidden' }}>
                    {rows.map((m, i) => (
                        <div key={m.id} style={{ display: 'grid', gridTemplateColumns: COLS, gap: 8, alignItems: 'center', padding: '7px 0', borderBottom: '1px solid var(--hair)', animation: `nocFadeUp .45s ease-out ${i * 35}ms both` }}>
                            <span style={{ display: 'flex', alignItems: 'center', gap: 9, minWidth: 0 }}>
                                <StatusDot status={m.status === 'up' ? 'healthy' : m.status === 'down' ? 'critical' : 'warning'} size={7} />
                                <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.name}</span>
                                <span className="tnum" style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)', flex: 'none' }}>{FLAGS[m.region]} {m.region}</span>
                            </span>
                            <span className="tnum" style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-2)' }}>{m.type}</span>
                            <span><MonitorStatusPill status={m.status} /></span>
                            <span><ResponseMeter ms={m.responseTime} status={m.responseTime === 0 ? 'critical' : responseStatus(m.responseTime)} maxMs={600} /></span>
                            <span className="tnum" style={{ fontFamily: 'var(--font-mono)', fontSize: 11.5, color: 'var(--fg-3)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.url}</span>
                        </div>
                    ))}
                </div>
                {moreCount > 0 && (
                    <div style={{ flex: 'none', paddingTop: 8, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)', textAlign: 'center' }}>
                        + {moreCount} more {selected ? `in ${regionName(selected)}` : 'monitors'} — open the dashboard for the full list
                    </div>
                )}
            </FadeUp>
        </div>
    );
}

function Legend({ color, label }: { color: string; label: string }) {
    return (
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: color, boxShadow: `0 0 6px ${color}` }} />
            {label}
        </span>
    );
}
