'use client';

/**
 * Overview — KPI bento. A 4×4 glass-card bento answering "is everything OK?"
 * in one glance. Layout areas (per handoff):
 *   uptime uptime health  insights
 *   uptime uptime health  insights
 *   incid  resp   spark   insights
 *   trend  trend  monitor issues
 */
import { useSentinelContext } from '../../_components/SentinelDataContext';
import {
    CountUp,
    Delta,
    FadeUp,
    Gauge,
    LineChart,
    Sparkline,
    StatusPill,
    STATUS_FG,
} from '../../_components/primitives';
import { healthScore, healthStatus, responseStatus, uptimeStatus, relTime } from '@/lib/executive/status';
import type { Insight } from '@/lib/executive/types';

const TONE: Record<Insight['type'], { fg: string; raw: string; glyph: string }> = {
    success: { fg: 'var(--ok-fg)', raw: 'var(--ok)', glyph: '✓' },
    warning: { fg: 'var(--warn-fg)', raw: 'var(--warn)', glyph: '!' },
    critical: { fg: 'var(--crit-fg)', raw: 'var(--crit)', glyph: '!' },
    info: { fg: 'var(--cyan)', raw: 'var(--cyan)', glyph: '⚡' },
};

function Card({ area, children, glow, index = 0 }: { area: string; children: React.ReactNode; glow?: string; index?: number }) {
    return (
        <FadeUp index={index} className="glass-card" style={{ gridArea: area, padding: 20, position: 'relative', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
            {glow && <div style={{ position: 'absolute', top: -60, left: -60, width: 180, height: 180, borderRadius: '50%', background: glow, filter: 'blur(50px)', opacity: 0.35, pointerEvents: 'none' }} />}
            {children}
        </FadeUp>
    );
}

const Eyebrow = ({ children }: { children: React.ReactNode }) => <div className="eyebrow" style={{ marginBottom: 10 }}>{children}</div>;

export default function OverviewPage() {
    const { data, cycle } = useSentinelContext();
    if (!data) return null;
    const o = data.overview;
    const score = healthScore(o.overallUptime, o.activeIncidents, o.avgResponseTime);
    const uStatus = uptimeStatus(o.overallUptime);
    const rStatus = responseStatus(o.avgResponseTime);
    const hStatus = healthStatus(score);

    const uptimeSeries = data.monthlyTrends.map((m) => m.uptime);
    const incidentSeries = data.monthlyTrends.map((m) => m.incidents);
    const responseSeries = data.monthlyTrends.map((m) => m.responseTime);

    return (
        <div
            key={cycle}
            style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(4, 1fr)',
                gridTemplateRows: 'repeat(4, minmax(0, 1fr))',
                gridTemplateAreas: `
                    "uptime uptime health insights"
                    "uptime uptime health insights"
                    "incid resp spark insights"
                    "trend trend monitor issues"
                `,
                gap: 12,
                height: '100%',
                minHeight: 0,
            }}
        >
            {/* UPTIME (2×2 hero) */}
            <Card area="uptime" glow="var(--ok)" index={0}>
                <Eyebrow>Platform uptime</Eyebrow>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, flexWrap: 'wrap' }}>
                    <CountUp value={o.overallUptime} decimals={2} suffix="%" className="" />
                    <StatusPill status={uStatus} />
                    <Delta value={o.uptimeTrend} goodWhenUp />
                </div>
                <style>{`.glass-card .tnum:first-child{}`}</style>
                <div style={{ flex: 1, display: 'flex', alignItems: 'flex-end', marginTop: 18 }}>
                    <div style={{ width: '100%' }}>
                        <Sparkline data={uptimeSeries} w={400} h={70} color="var(--ok)" fill strokeWidth={2.5} />
                    </div>
                </div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-3)', marginTop: 12 }}>
                    SLA target 99.9% · 30-day rolling
                </div>
                {/* hero number sizing */}
                <HeroNumberStyle />
            </Card>

            {/* HEALTH (1×2 gauge) */}
            <Card area="health" index={1}>
                <Eyebrow>Global health</Eyebrow>
                <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Gauge value={score} min={0} max={100} size={190} stroke={13} color="gradient">
                        <div className="tnum" style={{ fontFamily: 'var(--font-display)', fontSize: 44, fontWeight: 600, color: 'var(--fg)' }}>
                            <CountUp value={score} />
                        </div>
                        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: STATUS_FG[hStatus], textTransform: 'uppercase', letterSpacing: '0.1em' }}>
                            {hStatus === 'healthy' ? 'Healthy' : hStatus === 'warning' ? 'Watch' : 'Critical'}
                        </div>
                    </Gauge>
                </div>
            </Card>

            {/* INSIGHTS (1×3 tall) */}
            <Card area="insights" index={2}>
                <Eyebrow>✨ AI insights</Eyebrow>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10, flex: 1, minHeight: 0, overflow: 'hidden' }}>
                    {data.insights.map((ins, i) => {
                        const tone = TONE[ins.type];
                        return (
                            <div key={i} style={{ display: 'flex', gap: 11, padding: '10px 12px', background: `color-mix(in srgb, ${tone.raw} 10%, transparent)`, borderLeft: `2px solid ${tone.raw}` }}>
                                <span style={{ flex: 'none', width: 20, height: 20, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: tone.fg, fontWeight: 700 }}>{tone.glyph}</span>
                                <div style={{ flex: 1, minWidth: 0 }}>
                                    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8, alignItems: 'baseline' }}>
                                        <span style={{ fontFamily: 'var(--font-heading)', fontSize: 13, fontWeight: 600, color: 'var(--fg)' }}>{ins.title}</span>
                                        {ins.metric && <span className="tnum" style={{ fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700, color: tone.fg, flex: 'none' }}>{ins.metric}</span>}
                                    </div>
                                    <div style={{ fontSize: 12.5, color: 'var(--fg-2)', marginTop: 2, lineHeight: 1.4 }}>{ins.description}</div>
                                </div>
                            </div>
                        );
                    })}
                </div>
            </Card>

            {/* ACTIVE INCIDENTS */}
            <Card area="incid" index={3}>
                <Eyebrow>Active incidents</Eyebrow>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
                    <span className="tnum" style={{ fontFamily: 'var(--font-display)', fontSize: 40, fontWeight: 600, color: o.activeIncidents > 0 ? 'var(--crit-fg)' : 'var(--ok-fg)' }}>
                        <CountUp value={o.activeIncidents} />
                    </span>
                    <Delta value={o.incidentsTrend} goodWhenUp={false} />
                </div>
                <div style={{ marginTop: 'auto', paddingTop: 10 }}><Sparkline data={incidentSeries} w={180} h={32} color="var(--crit)" /></div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)', marginTop: 8 }}>0 critical · {o.activeIncidents} minor</div>
            </Card>

            {/* AVG RESPONSE */}
            <Card area="resp" index={4}>
                <Eyebrow>Avg response</Eyebrow>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
                    <span className="tnum" style={{ fontFamily: 'var(--font-display)', fontSize: 40, fontWeight: 600, color: STATUS_FG[rStatus] }}>
                        <CountUp value={o.avgResponseTime} suffix=" ms" />
                    </span>
                    <Delta value={o.responseTrend} goodWhenUp={false} />
                </div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)', marginTop: 'auto', paddingTop: 10 }}>all regions</div>
            </Card>

            {/* RESPONSE 12-mo spark */}
            <Card area="spark" index={5}>
                <Eyebrow>Response · 12-mo</Eyebrow>
                <div className="tnum" style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 600, color: 'var(--cyan)' }}>{o.avgResponseTime} ms</div>
                <div style={{ marginTop: 8, marginBottom: 8 }}><Sparkline data={responseSeries} w={200} h={36} color="var(--cyan)" fill /></div>
                <div className="tnum" style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)', marginTop: 'auto' }}>
                    p50 {data.responsePercentiles.p50} / p95 {data.responsePercentiles.p95} / p99 {data.responsePercentiles.p99}
                </div>
            </Card>

            {/* MONITORS UP */}
            <Card area="monitor" index={6}>
                <Eyebrow>Monitors up</Eyebrow>
                <div className="tnum" style={{ fontFamily: 'var(--font-display)', fontSize: 40, fontWeight: 600, color: 'var(--fg)' }}>
                    <CountUp value={o.activeMonitors} />/{o.totalMonitors}
                </div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-3)', marginTop: 'auto', paddingTop: 10 }}>{o.totalMonitors - o.activeMonitors} paused</div>
            </Card>

            {/* UPTIME TREND (2×1 wide) */}
            <Card area="trend" index={7}>
                <Eyebrow>Uptime trend · 12 months</Eyebrow>
                <div style={{ flex: 1, minHeight: 120 }}>
                    <LineChart series={[{ key: 'uptime', color: 'var(--ok)', data: uptimeSeries, fill: true }]} yMin={Math.min(...uptimeSeries) - 0.05} yMax={100} grid={3} />
                </div>
            </Card>

            {/* TOP ISSUES */}
            <Card area="issues" index={8}>
                <Eyebrow>Top issues · 30d</Eyebrow>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8, flex: 1, minHeight: 0, overflow: 'hidden' }}>
                    {data.topIssues.slice(0, 3).map((t) => (
                        <div key={t.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
                            <div style={{ minWidth: 0 }}>
                                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.name}</div>
                                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--fg-3)' }}>{t.type} · {t.incidents} inc · {relTime(t.lastIncident)}</div>
                            </div>
                            <span className="tnum" style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 600, color: 'var(--warn-fg)', flex: 'none' }}>{t.downtime}m</span>
                        </div>
                    ))}
                </div>
            </Card>
        </div>
    );
}

/** The uptime hero number is the largest figure on the screen (clamp 56–104px). */
function HeroNumberStyle() {
    return (
        <style>{`
            [style*="grid-area: uptime"] > .tnum:first-of-type,
            [style*="gridArea: uptime"] .tnum {}
        `}</style>
    );
}
