// Troubleshooting screen — tabbed view of system info and FFmpeg hardware acceleration capabilities.
(function () {
  const NS = window.ChicoryTVDesignSystem_eb3b61;
  const { Button, Card, Tabs } = NS;
  const Ico = window.Ico;
  const mono = { fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" };

  const generalJson = `{
  "appVersion": "26.4.0-fork",
  "osVersion": "Linux 6.8.0-1009-aws",
  "dotnetVersion": ".NET 10.0.0",
  "ffmpegVersion": "7.1.1",
  "ffmpegPath": "/usr/bin/ffmpeg",
  "processorCount": 8,
  "totalMemoryMb": 16384,
  "availableMemoryMb": 8642,
  "systemUptime": 847634,
  "ffmpegCapabilities": {
    "encoders": [
      "libx264",
      "libx265",
      "libvpx",
      "libvpx-vp9",
      "libopus",
      "aac"
    ],
    "decoders": [
      "h264",
      "hevc",
      "vp9",
      "av1",
      "opus"
    ],
    "hardwareAccel": [
      "vaapi",
      "qsv",
      "cuvid"
    ]
  },
  "database": "SQLite",
  "configPath": "/config",
  "dataPath": "/data"
}`;

  const nvidiaCapabilities = `ffmpeg version 7.1.1 Copyright (c) 2000-2025 the FFmpeg developers

NVIDIA GPU acceleration detected:
  Device 0: NVIDIA GeForce RTX 4090
    Memory: 24576 MB
    CUDA Compute Capability: 8.9
    Encoding Support:
      H.264 (NVENC): ✓
      H.265 (NVENC): ✓
      AV1 (NVENC): ✓
    Decoding Support:
      H.264 (CUVID): ✓
      H.265 (CUVID): ✓
      VP9 (CUVID): ✓
      AV1 (CUVID): ✓

Detailed NVENC Capabilities (H.265):
  Supported Frame Rates: 24, 25, 30, 48, 50, 60 fps
  Max Resolution: 7680x4320
  Presets: default, slow, medium, fast
  B-Frames: Yes
  Reference Frames: Configurable`;

  const qsvCapabilities = `Intel Quick Sync Video (QSV) Probe:

Device: Intel(R) Arc(TM) A770 Graphics
Driver Version: 27.1.14
Media SDK Version: 2024.1

Encoding Capabilities:
  H.264 (AVC):
    Profile: Baseline, Main, High
    Level: 4.2
    Rate Control: VBR, CBR, CQP
    Supported Resolutions: 176x144 to 4096x2304

  HEVC (H.265):
    Profile: Main, Main10
    Level: 5.1
    Rate Control: VBR, CBR, CQP
    Supported Resolutions: 176x144 to 8192x4320

Decoding Capabilities:
  H.264: Yes
  HEVC: Yes
  VP9: Yes
  AV1: Partial (decode only, limited profiles)

Performance:
  Throughput: 8K@30fps simultaneous encode/decode
  Latency: <50ms`;

  const vaapiCapabilities = `VAAPI Device Probe Results:

Device: /dev/dri/renderD128 (Intel)
Driver: Intel iHD
API Version: 1.15

Encoding Support:
  H.264: Yes (Main, High profile)
  HEVC: Yes (Main, Main10 profile)
  VP8: Yes
  VP9: Yes
  AV1: No

Decoding Support:
  H.264: Yes
  HEVC: Yes
  VP8: Yes
  VP9: Yes
  AV1: Yes (partial)
  MPEG2: Yes

Configuration:
  Max Resolution: 7680x4320
  Concurrent Sessions: Unlimited
  Performance Mode: Enabled`;

  const tabs = [
    { label: 'General', value: 'general' },
    { label: 'NVIDIA', value: 'nvidia' },
    { label: 'QSV', value: 'qsv' },
    { label: 'VAAPI', value: 'vaapi' }
  ];

  const tabContents = {
    general: {
      title: 'General',
      subtitle: 'Version, environment, hardware and FFmpeg settings',
      content: generalJson
    },
    nvidia: {
      title: 'NVIDIA',
      subtitle: 'Raw capability probe output',
      content: nvidiaCapabilities
    },
    qsv: {
      title: 'QSV',
      subtitle: 'Raw capability probe output',
      content: qsvCapabilities
    },
    vaapi: {
      title: 'VAAPI',
      subtitle: 'Raw capability probe output',
      content: vaapiCapabilities
    }
  };

  function CopyButton({ text }) {
    const [copied, setCopied] = React.useState(false);
    const copy = () => {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(() => {
          setCopied(true);
          setTimeout(() => setCopied(false), 1500);
        });
      }
    };
    return (
      <Button
        onClick={copy}
        size="sm"
        startIcon={copied ? <Ico n="Check" s={14} /> : <Ico n="Copy" s={14} />}
        variant="secondary"
      >
        {copied ? 'Copied' : 'Copy'}
      </Button>
    );
  }

  function Troubleshooting() {
    const [activeTab, setActiveTab] = React.useState('general');

    const activeContent = tabContents[activeTab];

    return (
      <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
        {/* action bar */}
        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 20px", borderBottom: "1px solid var(--border-hairline)", flex: "0 0 auto", minHeight: 58 }}>
          <Tabs tabs={tabs} value={activeTab} onChange={setActiveTab} />
          <span style={{ flex: 1 }} />
          <Button size="sm" startIcon={<Ico n="RefreshCw" s={14} />} variant="secondary">
            Refresh
          </Button>
        </div>

        {/* content area */}
        <div style={{ flex: 1, overflow: "auto", padding: "20px" }}>
          <Card
            title={activeContent.title}
            subtitle={activeContent.subtitle}
            actions={<CopyButton text={activeContent.content} />}
          >
            <pre style={{
              font: `var(--weight-normal) var(--text-xs)/1.4 var(--font-mono)`,
              color: "var(--text-primary)",
              background: "var(--ctv-bg-sunken)",
              padding: "16px",
              borderRadius: "var(--radius-sm)",
              overflow: "auto",
              margin: 0,
              maxHeight: "calc(100vh - 280px)",
              whiteSpace: "pre-wrap",
              wordWrap: "break-word"
            }}>
              <code>{activeContent.content}</code>
            </pre>
          </Card>
        </div>
      </div>
    );
  }

  window.CTVTroubleshooting = Troubleshooting;
})();
