/* global React, WatsonRail, WaxSeal, CaseMark, Timeline, AlertsLedger, EntityPanel, RiskScore, MitreGrid, DevicePanel, Card, Tag, Sev, EVIDENCE, EVIDENCE_TWIST, HYPOTHESES, NARRATIVE, recomputeHypotheses */
// Full Incident Investigation screen - Evening dark theme matching Figma 1:1006

const { useState: uS } = React;

// ── Figma logo/icon asset URLs ──
const SHERLOCK_LOGO_URL = 'https://www.figma.com/api/mcp/asset/175bbae4-18a9-4e65-9f5b-e92f7ce878e4';
const CMD_ICON_URL      = 'https://www.figma.com/api/mcp/asset/41004654-7768-4573-8d44-16ee2e1210dd';

// ── Top bar - Figma 1:1668, height 76px ──────────────────────────────
function TopBar({
  caseId = 'Marcus Chen, Mar 5',
  commandValue,
  suggestionsOpen,
  suggestions,
  variant = 'A',
  onCommand,
}) {
  const [localCmd, setLocalCmd] = uS('');

  function handleKey(e) {
    if (e.key === 'Enter' && localCmd.trim()) {
      if (onCommand) onCommand(localCmd.trim());
      setLocalCmd('');
    }
  }

  return (
    <header style={{
      height: 76,
      background: 'var(--parchment)',   /* evening: #22243a */
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between',
      padding: '0 24px',
      flexShrink: 0,
      position: 'relative',
      zIndex: 10,
    }}>
      {/* Left: logo + breadcrumb + CRITICAL badge */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 32, flex: '1 0 0', minWidth: 0 }}>
        {/* Sherlock wordmark */}
        <img src={SHERLOCK_LOGO_URL} alt="Sherlock"
          style={{ height: 24, width: 92, objectFit: 'contain', flexShrink: 0 }}
          onError={(e) => { e.target.style.display = 'none'; if (e.target.nextSibling) e.target.nextSibling.style.display = 'block'; }}
        />
        <span style={{
          display: 'none',
          fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 20,
          color: 'var(--ink)', letterSpacing: -0.5, flexShrink: 0,
        }}>Sherlock</span>

        {/* Breadcrumb */}
        <nav style={{ display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0 }}>
          <span style={{ fontFamily: 'var(--sans)', fontSize: 12.5, color: 'var(--ink-mute)' }}>Investigations</span>
          <span style={{ fontFamily: 'var(--sans)', fontSize: 12.5, color: 'var(--ink-faint)' }}>/</span>
          <span style={{ fontFamily: 'var(--sans)', fontSize: 12.5, fontWeight: 500, color: 'var(--ink)' }}>Marcus Chen, Mar 5</span>
          {/* CRITICAL pill - bg #952711 per Figma (not theme-variable, always red) */}
          <div style={{
            marginLeft: 12,
            background: '#952711', borderRadius: 12,
            padding: '4px 8px',
            fontFamily: 'var(--sans)', fontSize: 10, fontWeight: 500,
            color: '#f2c0b6', letterSpacing: '0.06px', textTransform: 'uppercase',
            flexShrink: 0,
          }}>CRITICAL</div>
        </nav>
      </div>

      {/* Center: command bar */}
      <div style={{ position: 'relative', flexShrink: 0 }}>
        <div style={{
          width: 421, height: 40,
          background: 'var(--parchment-2)',   /* evening: #1b1d31 */
          border: '1px solid rgba(103,112,209,0.40)',
          borderRadius: 8,
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '0 13px',
        }}>
          <img src={CMD_ICON_URL} alt="" style={{ width: 20, height: 18, objectFit: 'contain', flexShrink: 0, opacity: 0.6 }}
            onError={(e) => { e.target.style.display = 'none'; }}
          />
          <input
            value={localCmd}
            onChange={e => setLocalCmd(e.target.value)}
            onKeyDown={handleKey}
            placeholder="Ask Watson, or command the canvas..."
            style={{
              flex: 1, border: 'none', background: 'transparent', outline: 'none',
              fontFamily: 'var(--sans)', fontSize: 12.5,
              color: localCmd ? 'var(--ink)' : 'var(--ink-mute)',
              lineHeight: 'normal',
            }}
          />
          {localCmd && (
            <span style={{ display: 'inline-block', width: 6, height: 13, background: 'var(--ink)', animation: 'cursor-blink 1s steps(2) infinite', verticalAlign: '-2px' }} />
          )}
        </div>
        {suggestionsOpen && (
          <CommandSuggestions items={suggestions} onRun={onCommand} />
        )}
      </div>

      {/* Right: LIVE + buttons + avatar */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, flex: '1 0 0', justifyContent: 'flex-end' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ fontFamily: 'var(--sans)', fontSize: 10, color: 'var(--ink-mute)' }}>4 sources - LIVE</span>
          <span className="live-dot" />
        </div>

        <button style={{
          border: '1px solid rgba(239,231,210,0.16)', background: 'transparent',
          borderRadius: 4, padding: '7px 11px',
          fontFamily: 'var(--sans)', fontSize: 11.5, fontWeight: 500, color: 'var(--ink)',
          cursor: 'pointer',
        }}>Hand off</button>

        <button style={{
          background: 'var(--ink)', border: '1px solid var(--ink)',
          borderRadius: 4, padding: '7px 11px',
          fontFamily: 'var(--sans)', fontSize: 11.5, fontWeight: 500, color: 'var(--parchment)',
          cursor: 'pointer',
        }}>Open case file</button>

        <div style={{
          width: 32, height: 32, borderRadius: '50%',
          background: '#5eb480', border: '1px solid rgba(239,231,210,0.07)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--sans)', fontSize: 10, fontWeight: 500, color: 'var(--ink)',
          flexShrink: 0,
        }}>SH</div>
      </div>
    </header>
  );
}

// ── Command suggestions dropdown ──────────────────────────────────────
function CommandSuggestions({ items, header = 'Try', onRun }) {
  const groups = items || [
    { kind: 'canvas', label: 'show me logins from Bucharest in the last 72h',  hint: 'reshape - timeline' },
    { kind: 'canvas', label: 'switch timeline to two lanes',                    hint: 'reshape - timeline' },
    { kind: 'canvas', label: 'compare to last week',                            hint: 'overlay - timeline' },
    { kind: 'canvas', label: 'stack alerts by MITRE tactic',                    hint: 'reshape - alerts'   },
    { kind: 'ask',    label: 'why is hijack hypothesis rising?',                hint: 'ask Watson'         },
    { kind: 'ask',    label: 'has Marcus Chen been flagged before?',            hint: 'ask Watson'         },
    { kind: 'ask',    label: 'what does the new device fingerprint prove?',     hint: 'ask Watson'         },
  ];
  return (
    <div style={{
      position: 'absolute', top: 44, left: 0, width: 421,
      background: 'var(--parchment)',
      border: '1px solid rgba(103,112,209,0.40)',
      borderRadius: 8,
      padding: '6px 0',
      zIndex: 50,
    }}>
      <div style={{ padding: '8px 14px 6px', fontFamily: 'var(--sans)', fontSize: 10, fontWeight: 600, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--plum)' }}>{header}</div>
      {groups.map((g, i) => (
        <div key={i}
          onClick={() => onRun && onRun(g.label)}
          style={{
            display: 'grid', gridTemplateColumns: '56px 1fr auto',
            alignItems: 'center', gap: 10,
            padding: '7px 14px',
            cursor: 'pointer',
            transition: 'background 0.1s',
          }}
          onMouseEnter={e => e.currentTarget.style.background = 'rgba(239,231,210,0.06)'}
          onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
        >
          <span style={{
            fontSize: 9.5, fontWeight: 500,
            color: g.kind === 'canvas' ? 'var(--brick)' : 'var(--plum)',
            letterSpacing: '0.1em', textTransform: 'uppercase', fontFamily: 'var(--mono)',
          }}>{g.kind === 'canvas' ? 'canvas' : 'ask'}</span>
          <span style={{ fontFamily: 'var(--sans)', fontSize: 13, color: 'var(--ink)', lineHeight: 1.2 }}>{g.label}</span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 9.5, color: 'var(--ink-mute)' }}>{g.hint}</span>
        </div>
      ))}
      <div style={{ borderTop: '1px solid var(--rule)', padding: '8px 14px', display: 'flex', justifyContent: 'space-between' }}>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 9.5, color: 'var(--ink-mute)' }}>Watson commands the canvas; pinned clues stay.</span>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 9.5, color: 'var(--ink-mute)' }}>Enter to run</span>
      </div>
    </div>
  );
}

// ── Case header row - title + meta right ─────────────────────────────
function CaseHeader({ topConf, hijackConf, clueCount = 0, topName }) {
  const hasTheory = clueCount > 0;
  const titleText = hasTheory && topName ? topName : 'Open case, no theory yet';
  return (
    <div style={{
      display: 'flex', alignItems: 'baseline',
      justifyContent: 'space-between', gap: 20,
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 16, flexWrap: 'wrap', minWidth: 0 }}>
        <h1 style={{
          fontFamily: 'var(--serif)', fontStyle: 'italic', fontWeight: 400,
          fontSize: 36, lineHeight: 1.1,
          color: 'var(--ink)', margin: 0, letterSpacing: -0.3, flexShrink: 0,
        }}>
          {titleText}
        </h1>
        <span style={{
          fontFamily: 'var(--sans)', fontSize: 14, fontWeight: 400,
          color: 'var(--ink)', flexShrink: 0,
        }}>
          Marcus Chen, 5 Mar 2026
        </span>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 2, flexShrink: 0 }}>
        {hasTheory ? (
          <>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 14, color: 'var(--ink-mute)' }}>
              Watson{' '}
              <span style={{ color: 'var(--plum)', fontWeight: 600 }}>{topConf}%</span>
            </div>
            {hijackConf != null && (
              <div style={{ fontFamily: 'var(--sans)', fontSize: 14, color: 'var(--mustard)', fontStyle: 'italic' }}>
                session-hijack possibility {hijackConf}%
              </div>
            )}
          </>
        ) : (
          <div style={{ fontFamily: 'var(--sans)', fontSize: 14, color: 'var(--ink-mute)', fontStyle: 'italic' }}>
            {clueCount === 0 ? 'Watson is reading the ledger.' : `${clueCount} clue collected`}
          </div>
        )}
      </div>
    </div>
  );
}

// ── Timeline mode toggle ──────────────────────────────────────────────
function TimelineActions({ timelineMode, showCompare, onModeChange }) {
  const modes = [
    { id: 'area',  label: 'AREA' },
    { id: 'bars',  label: 'BARS' },
    { id: 'lanes', label: 'LANES' },
  ];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <div style={{ display: 'inline-flex', borderRadius: 4, overflow: 'hidden', border: '1px solid rgba(239,231,210,0.15)' }}>
        {modes.map(m => {
          const active = timelineMode === m.id;
          return (
            <span key={m.id}
              onClick={() => onModeChange && onModeChange(m.id)}
              style={{
                padding: '4px 10px',
                fontFamily: 'var(--sans)', fontSize: 10.5, fontWeight: 500,
                letterSpacing: '0.06em',
                /* Active mode: inverted - cream bg, dark text. Figma: bg #efe7d2 text #272a42 */
                background: active ? 'var(--ink)' : 'transparent',
                color: active ? 'var(--parchment)' : 'var(--ink-mute)',
                cursor: 'pointer',
                transition: 'background 0.12s, color 0.12s',
                userSelect: 'none',
              }}>{m.label}</span>
          );
        })}
      </div>
      {showCompare && (
        <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--plum)' }}>
          compare: last week ON
        </span>
      )}
    </div>
  );
}

// ── Panel card wrapper (dark themed) ─────────────────────────────────
function DarkPanel({ children, style }) {
  return (
    <div style={{
      background: 'var(--paper)',        /* evening: #272a42 */
      border: '1px solid var(--rule)',   /* evening: rgba(239,231,210,0.07) */
      borderRadius: 16,
      overflow: 'hidden',
      ...style,
    }}>
      {children}
    </div>
  );
}

// ── Section heading inside a panel ───────────────────────────────────
function PanelHeading({ children, muted }) {
  return (
    <div style={{
      fontFamily: 'var(--sans)', fontSize: 12, fontWeight: 600,
      letterSpacing: '1px', textTransform: 'uppercase',
      color: muted ? 'var(--ink-mute)' : 'var(--plum)',
    }}>{children}</div>
  );
}

// ── Main investigation screen ─────────────────────────────────────────
function InvestigationScreen({
  variant = 'A',
  pins = [],
  ranked,
  brush = null,
  pinned = [],
  timelineMode = 'bars',
  showCompare = false,
  commandValue,
  suggestionsOpen = false,
  onCommand,
  onBrushChange,
  onPinRegion,
  onUnpinRegion,
  onResizeRegion,
  onPinAlert,
  onUnpin,
  onFocus,
  onTimelineModeChange,
}) {
  const computedRanked = ranked || (typeof recomputeHypotheses !== 'undefined' ? recomputeHypotheses(pins, HYPOTHESES) : HYPOTHESES);
  const topConf = computedRanked.length > 0
    ? (computedRanked[0].conf <= 1 ? Math.round(computedRanked[0].conf * 100) : Math.round(computedRanked[0].conf))
    : 72;
  const hijackEntry = computedRanked.find(h => h.id === 'hijack');
  const hijackConf = hijackEntry
    ? (hijackEntry.conf <= 1 ? Math.round(hijackEntry.conf * 100) : Math.round(hijackEntry.conf))
    : 38;

  return (
    <div style={{
      width: '100%', height: '100%',
      display: 'flex', flexDirection: 'column',
      background: 'var(--parchment)',   /* evening: #22243a */
      overflow: 'hidden',
    }}>
      <TopBar
        variant={variant}
        commandValue={commandValue}
        suggestionsOpen={suggestionsOpen}
        onCommand={onCommand}
      />

      {/* Body: watson rail (left 337px) + main canvas (right) */}
      <div style={{ display: 'flex', flex: 1, minHeight: 0, overflow: 'hidden' }}>

        {/* Watson rail - 289px panel + 24px gutters each side = 337px total */}
        <div style={{
          width: 337, flexShrink: 0,
          padding: '0 24px 24px 24px',
          overflowY: 'auto',
          height: '100%',
        }}>
          <DarkPanel style={{ height: '100%', display: 'flex', flexDirection: 'column', borderRadius: 16 }}>
            <WatsonRail
              pins={pins}
              ranked={computedRanked}
              narrativeHeight={220}
              onUnpin={onUnpin}
              onFocus={onFocus}
            />
          </DarkPanel>
        </div>

        {/* Main canvas - scrollable */}
        <main style={{
          flex: 1, minWidth: 0,
          overflowY: 'auto',
          padding: '0 24px 48px 0',
          display: 'flex', flexDirection: 'column',
        }}>
          {/* Case title row */}
          <div style={{ padding: '16px 0 16px 0', flexShrink: 0 }}>
            <CaseHeader
              topConf={topConf}
              hijackConf={hijackConf}
              clueCount={pins.length}
              topName={computedRanked[0]?.name}
            />
          </div>

          {/* Hero timeline */}
          <DarkPanel style={{ marginBottom: 16, flexShrink: 0 }}>
            <div style={{ padding: '20px 25px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <PanelHeading>Signal Volume</PanelHeading>
              <TimelineActions timelineMode={timelineMode} showCompare={showCompare} onModeChange={onTimelineModeChange} />
            </div>
            <div style={{ padding: '0 25px 20px' }}>
              <Timeline
                mode={timelineMode}
                brush={brush}
                pinned={pinned}
                showCompare={showCompare}
                height={240}
                onBrushChange={onBrushChange}
                onPinRegion={onPinRegion}
                onUnpinRegion={onUnpinRegion}
                onResizeRegion={onResizeRegion}
              />
            </div>
          </DarkPanel>

          {/* Middle row: alerts (left) + risk + subject (right) */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 399px', gap: 16, marginBottom: 16, alignItems: 'start', flexShrink: 0 }}>

            {/* Alerts ledger */}
            <DarkPanel>
              <div style={{ padding: '25px 25px 0' }}>
                <PanelHeading>Alerts</PanelHeading>
              </div>
              <div style={{ padding: '20px 0 25px' }}>
                <AlertsLedger pinned={pins.map(p => p.t)} onPin={onPinAlert} max={7} />
              </div>
            </DarkPanel>

            {/* Right column stack */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              {/* Risk gauge - 399x126 (compact) */}
              <DarkPanel style={{ padding: 25 }}>
                <RiskScore score={87} delta={24} />
              </DarkPanel>

              {/* Subject card - 399x291 */}
              <DarkPanel style={{ padding: 25 }}>
                <EntityPanel onPin={onPinAlert} />
              </DarkPanel>
            </div>
          </div>

          {/* Bottom row: devices + mapped techniques */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, flexShrink: 0 }}>
            {/* Devices section */}
            <DarkPanel style={{ padding: 25 }}>
              <PanelHeading muted>Devices</PanelHeading>
              <div style={{ marginTop: 24 }}>
                <DevicePanel onPin={onPinAlert} pinned={pins.map(p => p.t)} />
              </div>
            </DarkPanel>

            {/* Mapped techniques */}
            <DarkPanel style={{ padding: '25px 0' }}>
              <div style={{ padding: '0 25px' }}>
                <PanelHeading muted>Mapped techniques</PanelHeading>
              </div>
              <div style={{ marginTop: 20 }}>
                <MitreGrid />
              </div>
            </DarkPanel>
          </div>
        </main>
      </div>
    </div>
  );
}

Object.assign(window, { TopBar, CommandSuggestions, InvestigationScreen, CaseHeader, TimelineActions });
