/* global React, Sev, Tag, Card, ConfBar, Spark, Pin */
// Widgets - Evening dark theme matching Figma 1:1006
// Uses CSS vars so evening Themed wrapper applies correctly.
// Marcus Chen incident: Senior DBA, MBP-MCHEN-01, March 2026.

const { useState: uSW2 } = React;

// ── Figma circle-plus icon ──
const ICON_CIRCLE_PLUS = 'https://www.figma.com/api/mcp/asset/63e60342-24cb-4f02-a9bb-78fc0d424c13';

// ── Alerts data ──────────────────────────────────────────────────────
const ALERTS = [
  { id: 'A02:47', t: '02:47', sev: 'warn',     src: 'Okta / SIEM',      title: 'Odd-hours login - 10.14.22.88',                         user: 'm.chen', mit: 'T1078',     tone: 'mustard', label: 'Odd-hours login - corp IP 10.14.22.88',                        day: 0.116 },
  { id: 'A03:41', t: '03:41', sev: 'warn',     src: 'Okta MFA',         title: 'MFA fatigue accept - 6 push prompts',                   user: 'm.chen', mit: 'T1078',     tone: 'mustard', label: 'MFA fatigue accept - 6 push prompts',                          day: 0.154 },
  { id: 'A04:08', t: '04:08', sev: 'critical', src: 'prod-db-01',       title: 'DB query spike - customers_pii 412k',                   user: 'm.chen', mit: 'T1213',     tone: 'brick',   label: 'DB query spike - customers_pii - 412k rows',                  day: 0.172 },
  { id: 'A04:23', t: '04:23', sev: 'critical', src: 'DLP / CASB',       title: 'Sensitive-label access - PII data class',               user: 'm.chen', mit: 'T1530',     tone: 'brick',   label: 'Sensitive-label access - PII data class',                     day: 0.183 },
  { id: 'A04:51', t: '04:51', sev: 'critical', src: 'Netskope',         title: 'Personal Dropbox upload - 2.3 GB egress',               user: 'm.chen', mit: 'T1567',     tone: 'brick',   label: 'Personal Dropbox upload - 2.3 GB egress',                     day: 0.202 },
  { id: 'A05:12', t: '05:12', sev: 'warn',     src: 'AWS API Gateway',  title: 'Unauthorized API call - payment service 200 requests',  user: 'm.chen', mit: 'T1071',     tone: 'mustard', label: 'Unauthorized API call - payment service 200 requests',        day: 0.213 },
  { id: 'A05:45', t: '05:45', sev: 'warn',     src: 'Okta',             title: 'Credential stuffing attack - 500 attempts',             user: 'm.chen', mit: 'T1110',     tone: 'mustard', label: 'Credential stuffing attack - 500 attempts',                   day: 0.240 },
  { id: 'A14:23', t: '14:23', sev: 'warn',     src: 'Endpoint EDR',     title: 'New device fingerprint - Win/Chrome',                   user: 'm.chen', mit: 'T1078',     tone: 'mustard', label: 'New device fingerprint - Windows/Chrome vs macOS/Safari',     day: 1.599 },
  { id: 'A16:05', t: '16:05', sev: 'warn',     src: 'GeoIP Auth',       title: 'Geo anomaly - Bucharest RO parallel session',           user: 'm.chen', mit: 'T1078',     tone: 'mustard', label: 'Geo anomaly - Bucharest RO parallel session',                 day: 1.670 },
];

// ── Severity dot - Figma exact: critical=#952711, brick=#c9826f, mustard=#c9a86a ──
function SevDot({ sev, tone }) {
  // Evening vars: --brick = #c9826f, --mustard = #c9a86a. Critical is always hardcoded.
  const color = sev === 'critical' ? '#952711'
              : tone === 'brick' ? 'var(--brick)'
              : 'var(--mustard)';
  return (
    <div style={{
      width: 6, height: 6, borderRadius: 3,
      background: color, flexShrink: 0,
    }} />
  );
}

// ── Alerts ledger - matches Figma 4:344 ──────────────────────────────
function AlertsLedger({ pinned = [], onPin, max = 7, density = 'comfy' }) {
  const [hoverIdx, setHoverIdx] = uSW2(null);

  return (
    <div>
      {/* Column headers */}
      <div style={{
        display: 'grid', gridTemplateColumns: '64px 1fr 72px 28px',
        padding: '4px 18px 13px',
        borderBottom: '1px solid var(--rule)',
      }}>
        {['Time', 'Signal', 'MITRE', ''].map((h, i) => (
          <span key={i} style={{
            fontFamily: 'var(--sans)', fontSize: 11, fontWeight: 500,
            letterSpacing: '1.54px', textTransform: 'uppercase', color: 'var(--ink-mute)',
          }}>{h}</span>
        ))}
      </div>

      {/* Rows */}
      {ALERTS.slice(0, max).map((a, i) => {
        const isPinned = pinned.includes(a.t);
        const isHover = hoverIdx === i;
        return (
          <div
            key={a.id}
            onClick={() => {
              if (onPin && !isPinned) {
                onPin({ id: a.id, t: a.t, label: a.label, src: a.src, tone: a.tone, day: a.day });
              }
            }}
            onMouseEnter={() => setHoverIdx(i)}
            onMouseLeave={() => setHoverIdx(null)}
            style={{
              display: 'grid', gridTemplateColumns: '64px 1fr 72px 28px',
              alignItems: 'center',
              height: 46,
              padding: '0 18px',
              borderBottom: '1px solid var(--rule-soft)',
              background: isPinned
                ? 'var(--brick-wash)'
                : isHover
                  ? 'var(--parchment-3)'
                  : 'transparent',
              cursor: isPinned ? 'default' : 'pointer',
              transition: 'background 0.1s',
            }}
          >
            {/* Time */}
            <span style={{ fontFamily: 'var(--sans)', fontSize: 13, color: 'var(--ink-soft)' }}>{a.t}</span>

            {/* Signal: severity dot + title */}
            <span style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0, overflow: 'hidden' }}>
              <SevDot sev={a.sev} tone={a.tone} />
              <span style={{
                fontFamily: 'var(--sans)', fontSize: 14, color: 'var(--ink)',
                overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
              }}>{a.title}</span>
            </span>

            {/* MITRE code */}
            <span style={{ fontFamily: 'var(--sans)', fontSize: 12, color: 'var(--ink-mute)' }}>{a.mit}</span>

            {/* Pin icon */}
            <span style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
              {isPinned ? (
                <span style={{ color: 'var(--brick)', fontSize: 14 }}>+</span>
              ) : isHover && onPin ? (
                <img src={ICON_CIRCLE_PLUS} alt="pin" style={{ width: 16, height: 16, opacity: 0.7 }}
                  onError={(e) => { e.target.outerHTML = '<span style="color:var(--plum);font-size:14px">+</span>'; }}
                />
              ) : (
                <span style={{ color: 'var(--ink-ghost)', fontSize: 14 }}>+</span>
              )}
            </span>
          </div>
        );
      })}
    </div>
  );
}

// ── Inline spark chart for entity panel ──────────────────────────────
function SparkMini({ data = [], w = 319, h = 62, anomalyIndex, onAnomalyClick }) {
  if (!data || data.length < 2) return null;
  const max = Math.max(...data);
  const baseline = Math.min(...data.filter((_, i) => i !== anomalyIndex));
  const range = max - baseline || 1;

  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - ((v - baseline) / range) * (h - 4) - 2;
    return [x, Math.max(2, Math.min(h - 2, y))];
  });

  const pathD = pts.map(([x, y], i) => `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`).join(' ');
  const fillD = pathD + ` L${pts[pts.length - 1][0].toFixed(1)},${h} L0,${h} Z`;

  const [hoverAnomaly, setHoverAnomaly] = uSW2(false);
  const anomalyPt = anomalyIndex != null ? pts[anomalyIndex] : null;

  return (
    <svg width={w} height={h} style={{ overflow: 'visible', display: 'block' }}>
      <path d={fillD} fill="rgba(159,138,166,0.08)" />
      <path d={pathD} fill="none" stroke="var(--plum)" strokeWidth={1.2} />
      {anomalyPt && (
        <circle
          cx={anomalyPt[0]} cy={anomalyPt[1]}
          r={hoverAnomaly ? 5 : 4}
          fill="var(--brick)" stroke="var(--paper)" strokeWidth={2}
          style={{ cursor: onAnomalyClick ? 'pointer' : 'default', transition: 'r 0.1s' }}
          onMouseEnter={() => setHoverAnomaly(true)}
          onMouseLeave={() => setHoverAnomaly(false)}
          onClick={() => onAnomalyClick && onAnomalyClick()}
        />
      )}
    </svg>
  );
}

// ── Entity panel (Marcus Chen subject card) - matches Figma 4:493 ────
function EntityPanel({ compact, onPin }) {
  const series = [12,14,11,13,15,12,11,14,13,12,11,13,14,12,11,13,14,12,11,13,14,12,11,13,14,15,122,9,11,13];
  const spikeIdx = 26;
  const spikeVal = series[spikeIdx];
  const baseline = Math.round(series.filter((_, i) => i !== spikeIdx).reduce((a, b) => a + b, 0) / (series.length - 1));

  // Figma chart image asset from node 4:506
  const chartImgUrl = 'https://www.figma.com/api/mcp/asset/5997ceda-2ecb-41d0-9e1a-545ac2a86ed3';

  return (
    <div>
      {/* "QUERIES PER DAY" - muted label */}
      <div style={{
        fontFamily: 'var(--sans)', fontSize: 12, fontWeight: 600,
        letterSpacing: '1px', textTransform: 'uppercase', color: 'var(--ink-mute)',
        marginBottom: 16,
      }}>Queries per day</div>

      {/* MC avatar + name/role row */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 18 }}>
        {/* MC monogram - bg var(--parchment-2) evening = #1b1d31 */}
        <div style={{
          width: 52, height: 52, flexShrink: 0,
          background: 'var(--parchment-2)',
          border: '1px solid var(--rule)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--serif)', fontStyle: 'italic', fontWeight: 500,
          fontSize: 20, color: 'var(--ink)',
        }}>MC</div>

        <div>
          {/* Marcus Chen - Spectral Regular 22px */}
          <div style={{
            fontFamily: 'var(--serif)', fontSize: 22, lineHeight: 1.1,
            color: 'var(--ink)', marginBottom: 2,
          }}>Marcus Chen</div>
          {/* "Senior DBA, prod-db root" - plum + brick */}
          <div style={{ fontFamily: 'var(--sans)', fontSize: 13 }}>
            <span style={{ color: 'var(--plum)' }}>Senior DBA, </span>
            <span style={{ color: 'var(--brick)' }}>prod-db root</span>
          </div>
        </div>
      </div>

      {/* Chart section */}
      {!compact && (
        <div style={{
          background: 'var(--plum-wash)',   /* evening: #251d34 */
          border: '1px solid var(--plum-soft)', /* evening: #463854 */
          borderRadius: 8,
          padding: '15px 15px 13px',
        }}>
          {/* Chart - Figma asset with SVG fallback */}
          <div style={{ marginBottom: 14 }}>
            <img
              src={chartImgUrl}
              alt="Queries per day chart"
              style={{ width: '100%', height: 62, objectFit: 'fill', display: 'block', borderRadius: 4 }}
              onError={(e) => {
                e.target.style.display = 'none';
                const next = e.target.nextSibling;
                if (next) next.style.display = 'block';
              }}
            />
            <div style={{ display: 'none' }}>
              <SparkMini
                data={series}
                w={319} h={62}
                anomalyIndex={spikeIdx}
                onAnomalyClick={() => onPin && onPin({
                  id: 'A04:08', t: '04:08',
                  label: 'DB query spike, customers_pii, 412k rows',
                  src: 'prod-db-01', tone: 'brick', day: 0.172,
                })}
              />
            </div>
          </div>

          {/* "+840% spike at 04:08 UTC" */}
          <div style={{ fontFamily: 'var(--sans)', fontSize: 13, fontWeight: 500, color: 'var(--brick)', lineHeight: 1.3 }}>
            +840% spike at 04:08 UTC
          </div>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 12, color: 'var(--ink-mute)', lineHeight: 1.3, marginTop: 2 }}>
            against a 30-day baseline of {baseline} queries
          </div>
        </div>
      )}
    </div>
  );
}

// ── Risk score gauge - matches Figma 4:464 ───────────────────────────
function RiskScore({ score = 87, delta = 24, big }) {
  const r = big ? 72 : 56;
  const cx = r + 8;
  const cy = r + 8;

  // Semicircle arc: score% filled
  const toRad = (pct) => Math.PI - (pct / 100) * Math.PI;
  const arcPt = (pct) => {
    const a = toRad(pct);
    return [cx + r * Math.cos(a), cy - r * Math.sin(a)];
  };
  const [ex, ey] = arcPt(score);

  const scoreColor = score > 75 ? 'var(--brick)' : score > 50 ? 'var(--mustard)' : 'var(--teal)';

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 24 }}>
      {/* SVG arc gauge */}
      <div style={{ flexShrink: 0 }}>
        <svg width={(r + 8) * 2} height={r + 16} style={{ overflow: 'visible' }}>
          {/* Track */}
          <path
            d={`M${cx - r} ${cy} A${r} ${r} 0 0 1 ${cx + r} ${cy}`}
            fill="none" stroke="var(--parchment-2)" strokeWidth={6}
          />
          {/* Score arc */}
          {score > 0 && (
            <path
              d={`M${cx - r} ${cy} A${r} ${r} 0 ${score > 50 ? 0 : 0} 1 ${ex} ${ey}`}
              fill="none" stroke={scoreColor} strokeWidth={6} strokeLinecap="butt"
            />
          )}
          {/* Tick marks */}
          {[0, 25, 50, 75, 100].map(p => {
            const a = toRad(p);
            const x1 = cx + (r - 5) * Math.cos(a), y1 = cy - (r - 5) * Math.sin(a);
            const x2 = cx + (r + 5) * Math.cos(a), y2 = cy - (r + 5) * Math.sin(a);
            return <line key={p} x1={x1} y1={y1} x2={x2} y2={y2} stroke="var(--ink-ghost)" strokeWidth={0.8} />;
          })}
          {/* "87" - Spectral 26px */}
          <text x={cx} y={cy + 2} textAnchor="middle"
            fontFamily="Spectral, Georgia, serif" fontSize={big ? 32 : 26}
            fill="var(--ink)">{score}</text>
          {/* "/ 100" - Geist 9px */}
          <text x={cx} y={cy + (big ? 20 : 16)} textAnchor="middle"
            fontFamily="Geist, sans-serif" fontSize={9} fill="var(--ink-mute)">/ 100</text>
        </svg>
      </div>

      {/* Right labels */}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: 'var(--sans)', fontSize: 12, fontWeight: 600,
          letterSpacing: '1px', textTransform: 'uppercase', color: 'var(--ink-mute)',
          marginBottom: 2,
        }}>Case risk</div>
        <div style={{ fontFamily: 'var(--sans)', fontSize: 13, fontWeight: 500, color: 'var(--brick)', marginBottom: 4 }}>
          +{delta} pts - 1h
        </div>
        <div style={{ fontFamily: 'var(--sans)', fontSize: 10, color: 'var(--ink-mute)' }}>
          Severity ceiling reached at 04:08
        </div>
      </div>
    </div>
  );
}

// ── MITRE techniques - matches Figma 4:976 ───────────────────────────
const MITRE = [
  { id: 'T1078',  name: 'Valid Accounts',         score: 87 },
  { id: 'T1621',  name: 'MFA Request Generation', score: 92 },
  { id: 'T1213',  name: 'Data from Repositories', score: 23 },
  { id: 'T1530',  name: 'Cloud Storage Object',   score: 83 },
  { id: 'T1567',  name: 'Exfil to Cloud Storage', score: 94 },
  { id: 'T1098',  name: 'Add Cloud Credentials',  score: 79 },
  { id: 'T1078.004', name: 'Cloud Accounts',      score: 67 },
  { id: 'T1110',  name: 'Credential Stuffing',    score: 67 },
];

function MitreGrid({ compact }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      {MITRE.map((m, i) => (
        <div key={m.id} style={{
          display: 'grid', gridTemplateColumns: '1fr auto auto',
          alignItems: 'center', gap: 32,
          height: 40,
          padding: '0 18px',
          borderBottom: '1px solid var(--rule-soft)',
        }}>
          <span style={{
            fontFamily: 'var(--sans)', fontSize: 14, color: 'var(--ink)',
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>{m.name}</span>
          <span style={{ fontFamily: 'var(--sans)', fontSize: 12, color: 'var(--ink-mute)', whiteSpace: 'nowrap' }}>
            {m.id}
          </span>
          <span style={{ fontFamily: 'var(--sans)', fontSize: 12, color: 'var(--ink-mute)', textAlign: 'right', minWidth: 24 }}>
            {m.score}
          </span>
        </div>
      ))}
    </div>
  );
}

// ── Device panel - matches Figma 4:915 ───────────────────────────────
// "KNOWN" card (plum-wash bg, plum-soft border) + "NEW" alert card (brick-wash bg)
function DevicePanel({ onPin, pinned = [] }) {
  const [hov, setHov] = uSW2(null);
  const alertRow = (key, time, dot, text, code, isLast, clue) => {
    const isPinned = clue && pinned.includes(clue.id);
    const isHover = hov === key;
    return (
      <div
        key={key}
        onClick={() => { if (onPin && clue && !isPinned) onPin(clue); }}
        onMouseEnter={() => setHov(key)}
        onMouseLeave={() => setHov(null)}
        style={{
          display: 'grid', gridTemplateColumns: '64px 1fr auto 28px',
          alignItems: 'center', gap: 32,
          height: 46,
          padding: '0 18px',
          borderBottom: isLast ? 'none' : '1px solid var(--rule-soft)',
          background: isPinned ? 'var(--wax-wash)' : isHover && clue ? 'var(--parchment)' : 'transparent',
          cursor: clue && !isPinned ? 'pointer' : 'default',
          transition: 'background 0.1s',
        }}
      >
        <span style={{ fontFamily: 'var(--sans)', fontSize: 13, color: 'var(--ink-soft)' }}>{time}</span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0, overflow: 'hidden' }}>
          <div style={{ width: 6, height: 6, borderRadius: 3, background: dot, flexShrink: 0 }} />
          <span style={{ fontFamily: 'var(--sans)', fontSize: 14, color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{text}</span>
        </span>
        <span style={{ fontFamily: 'var(--sans)', fontSize: 12, color: 'var(--ink-mute)', whiteSpace: 'nowrap' }}>{code}</span>
        <span style={{ display: 'flex', justifyContent: 'flex-end' }}>
          {isPinned
            ? <Pin size={14} />
            : isHover && clue
              ? <span style={{ color: 'var(--plum)', fontSize: 16, lineHeight: 1 }}>+</span>
              : <span style={{ color: 'var(--ink-faint)', fontSize: 14 }}>+</span>
          }
        </span>
      </div>
    );
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
      {/* Known device */}
      <div style={{
        background: 'var(--plum-wash)',      /* evening: #251d34 */
        border: '1px solid var(--plum-soft)', /* evening: #463854 */
        borderRadius: 8,
        padding: '15px 15px 13px',
        display: 'flex', flexDirection: 'column', gap: 8,
      }}>
        <div style={{
          fontFamily: 'var(--sans)', fontSize: 11, fontWeight: 600,
          letterSpacing: '1.54px', textTransform: 'uppercase', color: 'var(--ink-mute)',
        }}>Known</div>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8 }}>
          <span style={{ fontFamily: 'var(--sans)', fontSize: 14, fontWeight: 500, color: 'var(--ink)' }}>
            MacBook Pro
          </span>
          <span style={{ fontFamily: 'var(--sans)', fontSize: 12, color: 'var(--ink-mute)' }}>
            His usual machine. Safari, TLS 1.3.
          </span>
        </div>
      </div>

      {/* New device - brick-wash bg = #2e1a16 evening */}
      <div style={{
        background: 'var(--brick-wash)',
        border: '1px solid var(--rule)',
        borderRadius: 8,
        overflow: 'hidden',
      }}>
        <div style={{ padding: '15px 15px 0' }}>
          {/* "NEW, 14:23 UTC" - softer brick/wax color */}
          <div style={{
            fontFamily: 'var(--sans)', fontSize: 11, fontWeight: 600,
            letterSpacing: '1.54px', textTransform: 'uppercase', color: 'var(--wax)',
            marginBottom: 8,
          }}>New, 14:23 UTC</div>

          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, marginBottom: 16 }}>
            <span style={{ fontFamily: 'var(--sans)', fontSize: 14, fontWeight: 500, color: 'var(--ink)' }}>
              Windows 11, Chrome
            </span>
            <span style={{ fontFamily: 'var(--sans)', fontSize: 12, color: 'var(--wax)' }}>
              Never seen before on this account.
            </span>
          </div>
        </div>

        {alertRow('tls', '14:23', 'var(--brick)', 'TLS fingerprint does not match. Likely session theft.', 'T1078.004', false, {
          id: 'PT14:23', t: '14:23',
          label: 'New device fingerprint - Windows/Chrome vs macOS/Safari',
          src: 'Endpoint Telemetry', tone: 'mustard', day: 1.599,
        })}
        {alertRow('travel', '16:05', 'var(--mustard)', 'Impossible travel: corp HQ to Bucharest in under 2h.', 'T1078', true, {
          id: 'PT16:05', t: '16:05',
          label: 'Geo anomaly - Bucharest RO parallel session',
          src: 'GeoIP / Auth logs', tone: 'mustard', day: 1.670,
        })}
      </div>
    </div>
  );
}

Object.assign(window, { AlertsLedger, EntityPanel, RiskScore, MitreGrid, DevicePanel, ALERTS, MITRE });
