// FFmpeg Profiles screen — a compact profile list (icon + name + resolution/codec badges +
// copy/delete) that drills into a General/Video/Audio settings-row editor, mirroring the
// ChannelEditScreen form language. Static mockup toggles list ⇄ editor for both states.
(function () {
  const NS = window.ChicoryTVDesignSystem_eb3b61;
  const { Button, IconButton, Badge, Card, Input, Select, Checkbox, Tooltip } = NS;
  const Ico = window.Ico;
  const mono = { fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" };

  const PROFILES = [
    { id: 1, name: "1080p30 — NVENC", resolution: "1920x1080", video: "hevc", audio: "aac" },
    { id: 2, name: "1080p30 — Software", resolution: "1920x1080", video: "h264", audio: "aac" },
    { id: 3, name: "720p30 — VAAPI", resolution: "1280x720", video: "h264", audio: "aac" },
    { id: 4, name: "4K HDR — NVENC AV1", resolution: "3840x2160", video: "av1", audio: "ac3" },
    { id: 5, name: "Retro 480i — Copy", resolution: "720x480", video: "mpeg-2 video", audio: "aac" },
    { id: 6, name: "Music Channel — Audio only", resolution: "1280x720", video: "h264", audio: "aac (latm)" },
    { id: 7, name: "QSV Balanced", resolution: "1920x1080", video: "hevc", audio: "aac" },
    { id: 8, name: "Low-bitrate Mobile", resolution: "854x480", video: "h264", audio: "aac" },
  ];

  const SCALING_OPTIONS = [
    { label: "Scale and Pad", value: "ScaleAndPad" },
    { label: "Stretch", value: "Stretch" },
    { label: "Crop", value: "Crop" },
  ];
  const PAD_MODE_OPTIONS = [
    { label: "Hardware If Possible", value: "HardwareIfPossible" },
    { label: "Software", value: "Software" },
  ];
  const RESOLUTION_OPTIONS = ["1920x1080", "1280x720", "3840x2160", "854x480", "720x480"];
  const VIDEO_FORMAT_OPTIONS = [
    { label: "h264", value: "H264" },
    { label: "hevc", value: "Hevc" },
    { label: "mpeg-2", value: "Mpeg2Video" },
    { label: "av1", value: "Av1" },
  ];
  const VIDEO_PROFILE_OPTIONS = [
    { label: "main", value: "main" },
    { label: "high", value: "high" },
    { label: "high444p", value: "high444p" },
  ];
  const PRESET_OPTIONS = [{ label: "(none)", value: "" }, { label: "llhp", value: "llhp" }, { label: "llhq", value: "llhq" }];
  const BIT_DEPTH_OPTIONS = [
    { label: "8-bit", value: "EightBit" },
    { label: "10-bit", value: "TenBit" },
  ];
  const HWACCEL_OPTIONS = ["None", "Nvenc", "Qsv", "Vaapi", "Amf", "VideoToolbox"];
  const TONEMAP_OPTIONS = ["Linear", "Clip", "Gamma", "Reinhard", "Mobius", "Hable"];
  const AUDIO_FORMAT_OPTIONS = [
    { label: "aac", value: "Aac" },
    { label: "ac3", value: "Ac3" },
    { label: "aac (latm)", value: "AacLatm" },
  ];
  const LOUDNESS_OPTIONS = [
    { label: "Off", value: "Off" },
    { label: "loudnorm", value: "LoudNorm" },
  ];

  function Row({ label, help, control = 320, first = false, children }) {
    return (
      <div
        style={{
          display: "flex",
          alignItems: "flex-start",
          gap: 24,
          padding: "13px 20px",
          borderTop: first ? "none" : "1px solid var(--border-hairline)",
        }}
      >
        <div style={{ flex: "1 1 auto", minWidth: 0, paddingTop: 5 }}>
          <div style={{ font: "var(--weight-medium) var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-primary)" }}>{label}</div>
          {help && <div style={{ marginTop: 3, font: "var(--text-xs)/1.4 var(--font-sans)", color: "var(--text-secondary)", maxWidth: 460 }}>{help}</div>}
        </div>
        <div style={{ flex: `0 0 ${control}px` }}>{children}</div>
      </div>
    );
  }

  function ActionBar({ children }) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 20px", borderBottom: "1px solid var(--border-hairline)", flex: "0 0 auto", minHeight: 58 }}>
        {children}
      </div>
    );
  }

  function ProfileList({ onOpen, onAdd }) {
    return (
      <React.Fragment>
        <ActionBar>
          <Badge tone="neutral">{PROFILES.length} profiles</Badge>
          <span style={{ flex: 1 }} />
          <Button size="sm" startIcon={<Ico n="Plus" s={14} />} onClick={onAdd}>
            New profile
          </Button>
        </ActionBar>

        <div style={{ flex: 1, overflow: "auto", padding: "16px 20px" }}>
          <Card padded={false}>
            {PROFILES.map((p, i) => (
              <div
                key={p.id}
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 12,
                  padding: "0 16px",
                  height: "var(--row-h, 52px)",
                  minHeight: 52,
                  borderTop: i === 0 ? "none" : "1px solid var(--border-hairline)",
                }}
              >
                <Ico n="SlidersHorizontal" s={15} color="var(--ctv-accent)" />
                <button
                  type="button"
                  onClick={() => onOpen(p)}
                  style={{
                    flex: "1 1 auto",
                    minWidth: 0,
                    textAlign: "left",
                    background: "none",
                    border: "none",
                    padding: 0,
                    cursor: "pointer",
                    font: "var(--weight-medium) var(--text-sm)/1.3 var(--font-sans)",
                    color: "var(--ctv-accent)",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                  }}
                >
                  {p.name}
                </button>
                <Badge tone="neutral">{p.resolution}</Badge>
                <Badge tone="neutral">{`${p.video} / ${p.audio}`}</Badge>
                <Tooltip label={`Copy ${p.name}`}>
                  <IconButton size="sm" variant="ghost" title={`Copy ${p.name}`} onClick={() => onAdd()}>
                    <Ico n="Copy" s={14} />
                  </IconButton>
                </Tooltip>
                <Tooltip label="Delete">
                  <IconButton size="sm" variant="ghost" title="Delete">
                    <Ico n="Trash2" s={14} />
                  </IconButton>
                </Tooltip>
              </div>
            ))}
          </Card>
        </div>
      </React.Fragment>
    );
  }

  function ProfileEditor({ profile, isAdd, onBack }) {
    const [normalizeVideo, setNormalizeVideo] = React.useState(true);
    const [normalizeAudio, setNormalizeAudio] = React.useState(true);
    const [hwaccel, setHwaccel] = React.useState(profile ? (profile.video === "hevc" ? "Nvenc" : "None") : "None");
    const [loudness, setLoudness] = React.useState("Off");

    return (
      <React.Fragment>
        <ActionBar>
          <Button size="sm" variant="ghost" startIcon={<Ico n="ArrowLeft" s={14} />} onClick={onBack}>
            All profiles
          </Button>
          <span style={{ font: "var(--weight-medium) var(--text-sm)/1 var(--font-sans)", color: "var(--text-primary)" }}>
            {isAdd ? "New FFmpeg profile" : "Edit FFmpeg profile"}
          </span>
          <span style={{ flex: 1 }} />
          <Button size="sm" startIcon={<Ico n="Check" s={14} />}>
            {isAdd ? "Add profile" : "Save profile"}
          </Button>
        </ActionBar>

        <div style={{ flex: 1, overflow: "auto", padding: "16px 20px", display: "flex", flexDirection: "column", gap: 16 }}>
          <Card padded={false} title="General">
            <Row first label="Name" control={360}>
              <Input size="sm" value={isAdd ? "" : profile.name} placeholder="e.g. 1080p30 Software" />
            </Row>
            <Row label="Thread count" control={200}>
              <Input size="sm" type="number" trailing="threads" value="0" />
            </Row>
            <Row label="Normalize audio" control={200}>
              <Checkbox checked={normalizeAudio} onChange={setNormalizeAudio} />
            </Row>
            <Row label="Normalize video" control={200}>
              <Checkbox checked={normalizeVideo} onChange={setNormalizeVideo} />
            </Row>
            <Row label="Preferred resolution" control={360}>
              <Select value={isAdd ? RESOLUTION_OPTIONS[0] : profile.resolution} options={RESOLUTION_OPTIONS} />
            </Row>
            {normalizeVideo && (
              <React.Fragment>
                <Row label="Scaling behavior" control={360}>
                  <Select value="ScaleAndPad" options={SCALING_OPTIONS} />
                </Row>
                <Row control={360} label="Pad mode" help="Hardware padding only applies with VAAPI; otherwise software padding is used.">
                  <Select disabled={hwaccel !== "Vaapi"} value="Software" options={PAD_MODE_OPTIONS} />
                </Row>
              </React.Fragment>
            )}
          </Card>

          <Card padded={false} title="Video">
            {normalizeVideo ? (
              <React.Fragment>
                <Row first label="Format" control={360}>
                  <Select value={isAdd ? "H264" : "Hevc"} options={VIDEO_FORMAT_OPTIONS} />
                </Row>
                <Row label="Profile" control={360}>
                  <Select value="high" options={VIDEO_PROFILE_OPTIONS} />
                </Row>
                <Row label="Preset" control={360}>
                  <Select disabled={hwaccel === "None"} value={hwaccel === "None" ? "" : "llhq"} options={PRESET_OPTIONS} />
                </Row>
                <Row label="Allow B-frames" control={200}>
                  <Checkbox checked={false} />
                </Row>
                <Row label="Bit depth" control={360}>
                  <Select value="EightBit" options={BIT_DEPTH_OPTIONS} />
                </Row>
                <Row label="Bitrate" control={220}>
                  <Input size="sm" type="number" trailing="kBit/s" value="2000" />
                </Row>
                <Row label="Buffer size" control={220}>
                  <Input size="sm" type="number" trailing="kBit" value="4000" />
                </Row>
                <Row label="Hardware acceleration" control={360}>
                  <Select value={hwaccel} options={HWACCEL_OPTIONS} onChange={(e) => setHwaccel(e.target.value)} />
                </Row>
                {hwaccel === "Vaapi" && (
                  <React.Fragment>
                    <Row label="VAAPI driver" control={360}>
                      <Select value="Default" options={["Default", "iHD", "i965", "RadeonSI", "Nouveau"]} />
                    </Row>
                    <Row label="VAAPI display" control={360} help="Rendering display, e.g. drm.">
                      <Input size="sm" value="drm" />
                    </Row>
                  </React.Fragment>
                )}
                {(hwaccel === "Vaapi" || hwaccel === "Qsv") && (
                  <Row label={hwaccel === "Vaapi" ? "VAAPI device" : "QSV device"} control={360} help="Render device, e.g. /dev/dri/renderD128.">
                    <Input size="sm" value="/dev/dri/renderD128" />
                  </Row>
                )}
                {hwaccel === "Qsv" ? (
                  <Row label="QSV extra hardware frames" control={200}>
                    <Input size="sm" type="number" value="64" />
                  </Row>
                ) : (
                  <Row label="Tonemap algorithm" control={360}>
                    <Select value="Linear" options={TONEMAP_OPTIONS} />
                  </Row>
                )}
                <Row label="Normalize frame rate" control={200}>
                  <Checkbox checked={false} />
                </Row>
                <Row label="Normalize colors" control={200}>
                  <Checkbox checked={true} />
                </Row>
                <Row label="Auto deinterlace video" control={200}>
                  <Checkbox checked={true} />
                </Row>
              </React.Fragment>
            ) : (
              <div style={{ display: "flex", alignItems: "center", gap: 10, margin: 16, padding: "10px 12px", borderRadius: "var(--radius-sm)", background: "var(--ctv-warn-soft)", border: "1px solid var(--border-hairline)" }}>
                <Ico n="TriangleAlert" s={14} color="var(--status-warn)" />
                <span style={{ font: "var(--text-xs)/1.4 var(--font-sans)", color: "var(--text-secondary)" }}>
                  Video will be copied as-is, including timestamps, which will cause issues with most clients.
                </span>
              </div>
            )}
          </Card>

          <Card padded={false} title="Audio">
            {normalizeAudio ? (
              <React.Fragment>
                <Row first label="Format" control={360}>
                  <Select value="Aac" options={AUDIO_FORMAT_OPTIONS} />
                </Row>
                <Row label="Bitrate" control={220}>
                  <Input size="sm" type="number" trailing="kBit/s" value="192" />
                </Row>
                <Row label="Buffer size" control={220}>
                  <Input size="sm" type="number" trailing="kBit" value="384" />
                </Row>
                <Row label="Channels" control={200}>
                  <Input size="sm" type="number" value="2" />
                </Row>
                <Row label="Sample rate" control={220}>
                  <Input size="sm" type="number" trailing="kHz" value="48" />
                </Row>
                <Row label="Normalize loudness" control={360}>
                  <Select value={loudness} options={LOUDNESS_OPTIONS} onChange={(e) => setLoudness(e.target.value)} />
                </Row>
                {loudness === "LoudNorm" && (
                  <Row label="Target loudness" control={220}>
                    <Input size="sm" type="number" trailing="LUFS" value="-23" />
                  </Row>
                )}
              </React.Fragment>
            ) : (
              <div style={{ display: "flex", alignItems: "center", gap: 10, margin: 16, padding: "10px 12px", borderRadius: "var(--radius-sm)", background: "var(--ctv-warn-soft)", border: "1px solid var(--border-hairline)" }}>
                <Ico n="TriangleAlert" s={14} color="var(--status-warn)" />
                <span style={{ font: "var(--text-xs)/1.4 var(--font-sans)", color: "var(--text-secondary)" }}>
                  Audio will be copied as-is, including timestamps, which will cause issues with most clients.
                </span>
              </div>
            )}
          </Card>
        </div>
      </React.Fragment>
    );
  }

  function FFmpegProfiles() {
    const [screen, setScreen] = React.useState({ kind: "list" });

    return (
      <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
        {screen.kind === "list" ? (
          <ProfileList onOpen={(p) => setScreen({ kind: "edit", profile: p })} onAdd={() => setScreen({ kind: "add" })} />
        ) : (
          <ProfileEditor
            profile={screen.profile}
            isAdd={screen.kind === "add"}
            onBack={() => setScreen({ kind: "list" })}
          />
        )}
      </div>
    );
  }

  window.CTVFFmpegProfiles = FFmpegProfiles;
})();
