// Media Detail screen — a fanart-backed hero (poster + title/plot/actions), a chip-stack of
// metadata rows, and a paged child grid (seasons/episodes/music videos) for hierarchical kinds.
// One shell serves Movie / Show / Season / Artist detail; a segmented switcher previews all four.
(function () {
  const NS = window.ChicoryTVDesignSystem_eb3b61;
  const { Button, IconButton, Badge, Tag, Card, Spinner, Tooltip } = NS;
  const Ico = window.Ico;
  const mono = { fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" };

  const KINDS = {
    movie: {
      label: "Movie",
      back: "Back",
      title: "The Cat Concerto",
      subtitle: "1947",
      plot:
        "Tom the cat, playing a piano concerto on stage, is disturbed by Jerry the mouse, who lives inside the piano. The two engage in a slapstick battle that becomes part of the performance itself.",
      poster: true,
      fanart: true,
      state: null,
      path: "/media/movies/tom-and-jerry/the-cat-concerto (1947)/The Cat Concerto.mkv",
      chips: [
        { label: "Genres", values: ["Animation", "Short", "Comedy"] },
        { label: "Tags", values: ["Theatrical Short", "Best Original Score"] },
        { label: "Studios", values: ["MGM"] },
        { label: "Content Ratings", values: ["G"] },
        { label: "Languages", values: ["English"] },
        { label: "Directors", values: ["William Hanna", "Joseph Barbera"] },
        { label: "Writers", values: ["William Hanna", "Joseph Barbera"] },
      ],
      actors: [
        { id: 1, name: "Tom (voice)", role: "Cat", thumb: null },
        { id: 2, name: "Jerry (voice)", role: "Mouse", thumb: null },
      ],
      actions: ["info", "troubleshoot", "addto"],
      grid: null,
    },
    show: {
      label: "Show",
      back: "Back",
      title: "Sesame Street",
      subtitle: "1969",
      plot:
        "A pioneering educational program combining puppetry, animation, and live-action sketches to teach preschool-aged children letters, numbers, and social skills, set on a fictional New York City street.",
      poster: true,
      fanart: true,
      state: null,
      chips: [
        { label: "Genres", values: ["Children", "Educational"] },
        { label: "Tags", values: ["Muppets", "PBS"] },
        { label: "Studios", values: ["Sesame Workshop"] },
        { label: "Networks", values: ["PBS", "HBO Max"] },
        { label: "Content Ratings", values: ["TV-Y"] },
        { label: "Languages", values: ["English"] },
      ],
      actors: [
        { id: 1, name: "Bob McGrath", role: "Bob", thumb: null },
        { id: 2, name: "Loretta Long", role: "Susan", thumb: null },
        { id: 3, name: "Will Lee", role: "Mr. Hooper", thumb: null },
      ],
      actions: ["addto", "scan"],
      grid: { heading: "Seasons", kind: "season", count: 54, page: 1, pages: 1 },
    },
    season: {
      label: "Season",
      back: "Back to show",
      title: "Sesame Street — Season 42",
      subtitle: "2011",
      plot: null,
      poster: true,
      fanart: false,
      state: null,
      chips: [],
      actors: [],
      actions: ["addto"],
      grid: { heading: "Episodes", kind: "episode", count: 26, page: 1, pages: 1 },
    },
    artist: {
      label: "Artist",
      back: "Back",
      title: "Talking Heads",
      subtitle: "New York, NY",
      plot:
        "An American rock band formed in 1975, known for their nervy, angular art-rock sound and David Byrne's distinctive vocal style. Inducted into the Rock and Roll Hall of Fame in 2002.",
      poster: true,
      fanart: true,
      state: null,
      chips: [
        { label: "Genres", values: ["New Wave", "Art Rock", "Post-Punk"] },
        { label: "Styles", values: ["Energetic", "Quirky"] },
        { label: "Moods", values: ["Manic", "Paranoid"] },
        { label: "Languages", values: ["English"] },
      ],
      actors: [],
      actions: ["addto"],
      grid: { heading: "Music Videos", kind: "video", count: 8, page: 1, pages: 1 },
    },
  };

  const CHILD_ITEMS = {
    season: Array.from({ length: 12 }, (_, i) => ({ id: i + 1, title: `Season ${i + 1}`, sub: `${22 + (i % 4)} episodes` })),
    episode: Array.from({ length: 12 }, (_, i) => ({ id: i + 1, title: `Episode ${4090 + i}`, sub: `${20 + (i % 3)}:15` })),
    video: [
      { id: 1, title: "Once in a Lifetime", sub: "4:19" },
      { id: 2, title: "Burning Down the House", sub: "3:59" },
      { id: 3, title: "This Must Be the Place", sub: "4:57" },
      { id: 4, title: "Road to Nowhere", sub: "4:19" },
      { id: 5, title: "Psycho Killer", sub: "4:47" },
      { id: 6, title: "And She Was", sub: "4:03" },
      { id: 7, title: "Wild Wild Life", sub: "4:19" },
      { id: 8, title: "Life During Wartime", sub: "3:41" },
    ],
  };

  const STREAMS = [
    { i: 0, kind: "Video", codec: "h264", lang: "—", title: "—" },
    { i: 1, kind: "Audio", codec: "aac", lang: "eng", title: "Stereo" },
    { i: 2, kind: "Subtitle", codec: "subrip", lang: "eng", title: "English SDH" },
  ];

  function ChipRow({ label, values }) {
    if (!values || values.length === 0) return null;
    return (
      <div style={{ display: "flex", gap: 10, alignItems: "baseline", flexWrap: "wrap" }}>
        <span style={{ minWidth: 130, font: "var(--text-2xs)/1 var(--font-sans)", letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--text-disabled)" }}>{label}</span>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap", flex: 1 }}>
          {values.map((v) => <Tag key={v}>{v}</Tag>)}
        </div>
      </div>
    );
  }

  function PosterThumb({ size, radius, hue }) {
    return (
      <div style={{ width: size, height: size, borderRadius: radius, flexShrink: 0, position: "relative", overflow: "hidden", border: "1px solid var(--border-hairline)", background: `linear-gradient(160deg, hsl(${hue} 24% 22%), hsl(${hue} 26% 14%))` }}>
        <div style={{ position: "absolute", inset: 0, backgroundImage: `repeating-linear-gradient(135deg, hsl(${hue} 22% 10% / .5) 0 1px, transparent 1px 9px)` }} />
      </div>
    );
  }

  function ActorsRow({ actors }) {
    if (!actors || actors.length === 0) return null;
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        <h3 style={{ margin: 0, font: "var(--weight-semibold) var(--text-md)/1.2 var(--font-sans)", color: "var(--text-primary)" }}>Cast</h3>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(110px, 1fr))", gap: 12 }}>
          {actors.map((a) => (
            <div key={a.id} style={{ display: "flex", flexDirection: "column", gap: 4, textAlign: "center" }}>
              <div style={{ width: "100%", aspectRatio: "1 / 1", borderRadius: "50%", background: "var(--ctv-surface-3)", border: "1px solid var(--border-hairline)" }} />
              <div style={{ font: "var(--text-xs)/1.2 var(--font-sans)", color: "var(--text-primary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{a.name}</div>
              {a.role ? <div style={{ font: "var(--text-2xs)/1.2 var(--font-sans)", color: "var(--text-secondary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{a.role}</div> : null}
            </div>
          ))}
        </div>
      </div>
    );
  }

  function ChildGrid({ heading, kind, count, page, pages }) {
    const items = CHILD_ITEMS[kind] || [];
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        <h3 style={{ margin: 0, font: "var(--weight-semibold) var(--text-md)/1.2 var(--font-sans)", color: "var(--text-primary)" }}>{heading}</h3>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(130px, 1fr))", gap: 12 }}>
          {items.map((item, idx) => {
            const hue = (idx * 47 + kind.length * 13) % 360;
            return (
              <div key={item.id} style={{ display: "flex", flexDirection: "column", gap: 6, cursor: "pointer" }}>
                <div style={{ position: "relative", borderRadius: "var(--radius-sm)", overflow: "hidden", border: "1px solid var(--border-hairline)", background: `linear-gradient(160deg, hsl(${hue} 24% 20%), hsl(${hue} 26% 12%))`, height: 150 }}>
                  <div style={{ position: "absolute", inset: 0, backgroundImage: `repeating-linear-gradient(135deg, hsl(${hue} 22% 10% / .5) 0 1px, transparent 1px 9px)` }} />
                  <div style={{ position: "absolute", top: 6, right: 6, display: "flex", alignItems: "center", justifyContent: "center", width: 24, height: 24, borderRadius: "var(--radius-sm)", background: "rgba(0,0,0,0.45)", backdropFilter: "blur(2px)" }}>
                    <Ico n={kind === "video" ? "Music" : "PlayCircle"} s={13} color="rgba(255,255,255,0.85)" />
                  </div>
                </div>
                <div style={{ font: "var(--weight-medium) var(--text-xs)/1.2 var(--font-sans)", color: "var(--text-primary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{item.title}</div>
                <div style={{ ...mono, font: "var(--text-2xs)/1 var(--font-mono)", color: "var(--text-disabled)" }}>{item.sub}</div>
              </div>
            );
          })}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 4, font: "var(--text-xs)/1 var(--font-sans)", color: "var(--text-secondary)" }}>
          <span style={mono}>{count}</span>
          <span style={{ flex: 1 }} />
          <IconButton size="sm" title="Previous page" disabled={page <= 1}><Ico n="ChevronLeft" s={15} /></IconButton>
          <span>Page <span style={mono}>{page}</span> of <span style={mono}>{pages}</span></span>
          <IconButton size="sm" title="Next page" disabled={page >= pages}><Ico n="ChevronRight" s={15} /></IconButton>
        </div>
      </div>
    );
  }

  function MediaInfoDialog({ open, onClose }) {
    if (!open) return null;
    return (
      <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.5)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 50 }} onClick={onClose}>
        <div onClick={(e) => e.stopPropagation()} style={{ width: 720, maxWidth: "90vw", maxHeight: "85vh", overflow: "auto", background: "var(--surface-raised)", border: "1px solid var(--border-hairline)", borderRadius: "var(--radius-md)", boxShadow: "var(--shadow-lg)" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 18px", borderBottom: "1px solid var(--border-hairline)" }}>
            <span style={{ font: "var(--weight-semibold) var(--text-md)/1 var(--font-sans)", color: "var(--text-primary)" }}>Media Info</span>
            <IconButton size="sm" title="Close" onClick={onClose}><Ico n="X" s={16} /></IconButton>
          </div>
          <div style={{ padding: 18, display: "flex", flexDirection: "column", gap: 16 }}>
            <dl style={{ display: "grid", gridTemplateColumns: "max-content 1fr", gap: "6px 12px", margin: 0 }}>
              <dt style={{ color: "var(--text-disabled)", font: "var(--text-2xs)/1 var(--font-sans)", textTransform: "uppercase", letterSpacing: "0.04em" }}>Kind</dt>
              <dd style={{ margin: 0, color: "var(--text-primary)", font: "var(--text-sm)/1 var(--font-sans)" }}>Movie</dd>
              <dt style={{ color: "var(--text-disabled)", font: "var(--text-2xs)/1 var(--font-sans)", textTransform: "uppercase", letterSpacing: "0.04em" }}>Library</dt>
              <dd style={{ margin: 0, color: "var(--text-primary)", font: "var(--text-sm)/1 var(--font-sans)" }}>Movies (Plex)</dd>
              <dt style={{ color: "var(--text-disabled)", font: "var(--text-2xs)/1 var(--font-sans)", textTransform: "uppercase", letterSpacing: "0.04em" }}>Duration</dt>
              <dd style={{ ...mono, margin: 0, color: "var(--text-primary)", fontSize: "var(--text-sm)" }}>7:37</dd>
              <dt style={{ color: "var(--text-disabled)", font: "var(--text-2xs)/1 var(--font-sans)", textTransform: "uppercase", letterSpacing: "0.04em" }}>Resolution</dt>
              <dd style={{ ...mono, margin: 0, color: "var(--text-primary)", fontSize: "var(--text-sm)" }}>1920×1080</dd>
              <dt style={{ color: "var(--text-disabled)", font: "var(--text-2xs)/1 var(--font-sans)", textTransform: "uppercase", letterSpacing: "0.04em" }}>Aspect Ratio</dt>
              <dd style={{ margin: 0, color: "var(--text-primary)", font: "var(--text-sm)/1 var(--font-sans)" }}>1.78:1</dd>
            </dl>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <h4 style={{ margin: 0, font: "var(--weight-semibold) var(--text-md)/1.2 var(--font-sans)", color: "var(--text-primary)" }}>Streams</h4>
              <div style={{ border: "1px solid var(--border-hairline)", borderRadius: "var(--radius-sm)", overflow: "hidden" }}>
                <table style={{ width: "100%", borderCollapse: "collapse" }}>
                  <thead>
                    <tr>
                      {["#", "Kind", "Codec", "Language", "Title"].map((h) => (
                        <th key={h} style={{ textAlign: "left", padding: "6px 10px", font: "var(--weight-medium) var(--text-2xs)/1 var(--font-sans)", textTransform: "uppercase", letterSpacing: "0.04em", color: "var(--text-disabled)", background: "var(--ctv-bg-sunken)", borderBottom: "1px solid var(--border-hairline)" }}>{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {STREAMS.map((s) => (
                      <tr key={s.kind} style={{ borderTop: "1px solid var(--border-hairline)" }}>
                        <td style={{ ...mono, padding: "6px 10px", fontSize: "var(--text-sm)", color: "var(--text-secondary)" }}>{s.i}</td>
                        <td style={{ padding: "6px 10px", font: "var(--text-sm)/1 var(--font-sans)", color: "var(--text-primary)" }}>{s.kind}</td>
                        <td style={{ ...mono, padding: "6px 10px", fontSize: "var(--text-sm)", color: "var(--text-secondary)" }}>{s.codec}</td>
                        <td style={{ padding: "6px 10px", font: "var(--text-sm)/1 var(--font-sans)", color: "var(--text-secondary)" }}>{s.lang}</td>
                        <td style={{ padding: "6px 10px", font: "var(--text-sm)/1 var(--font-sans)", color: "var(--text-secondary)" }}>{s.title}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  function MediaDetail() {
    const [kind, setKind] = React.useState("movie");
    const [infoOpen, setInfoOpen] = React.useState(false);
    const d = KINDS[kind];

    const Segmented = () => (
      <div style={{ display: "inline-flex", gap: 2, padding: 2, borderRadius: "var(--radius-sm)", background: "var(--ctv-bg-sunken)", border: "1px solid var(--border-hairline)" }}>
        {Object.keys(KINDS).map((k) => {
          const on = k === kind;
          return (
            <button key={k} type="button" onClick={() => setKind(k)}
              style={{ display: "inline-flex", alignItems: "center", height: 26, padding: "0 11px", border: "none", borderRadius: "var(--radius-xs)", cursor: "pointer", background: on ? "var(--ctv-surface-3)" : "transparent", color: on ? "var(--text-primary)" : "var(--text-secondary)", font: `${on ? "var(--weight-medium)" : "var(--weight-normal)"} var(--text-xs)/1 var(--font-sans)` }}>
              {KINDS[k].label}
            </button>
          );
        })}
      </div>
    );

    return (
      <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
        {/* preview switcher — not part of the live screen, lets this mockup demo all 4 detail kinds */}
        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 20px", borderBottom: "1px solid var(--border-hairline)", flex: "0 0 auto", minHeight: 58 }}>
          <Button size="sm" variant="ghost" startIcon={<Ico n="ArrowLeft" s={14} />}>{d.back}</Button>
          <span style={{ width: 1, height: 18, background: "var(--border-hairline)" }} />
          <span style={{ font: "var(--text-2xs)/1 var(--font-sans)", textTransform: "uppercase", letterSpacing: "0.04em", color: "var(--text-disabled)" }}>Preview kind</span>
          <Segmented />
          <span style={{ flex: 1 }} />
        </div>

        <div style={{ flex: 1, overflow: "auto", padding: "20px" }}>
          <div style={{ position: "relative", display: "flex", flexDirection: "column", gap: 14, maxWidth: 1040, margin: "0 auto" }}>
            {d.fanart && (
              <div style={{ position: "absolute", inset: "-8px -8px auto -8px", height: 220, borderRadius: "var(--radius-md)", pointerEvents: "none", zIndex: 0, background: "linear-gradient(160deg, var(--ctv-accent-soft), transparent 70%)", opacity: 0.5, maskImage: "linear-gradient(to bottom, black, transparent)", WebkitMaskImage: "linear-gradient(to bottom, black, transparent)" }} />
            )}

            <div style={{ position: "relative", zIndex: 1, display: "flex", gap: 16, flexWrap: "wrap" }}>
              {d.poster ? <PosterThumb size={200} radius="var(--radius-sm)" hue={(d.title.length * 29) % 360} /> : null}
              <div style={{ display: "flex", flexDirection: "column", gap: 8, minWidth: 260, flex: 1 }}>
                <h2 style={{ margin: 0, font: "var(--weight-semibold) var(--text-xl)/1.2 var(--font-sans)", color: "var(--text-primary)" }}>{d.title}</h2>
                {d.subtitle ? <div style={{ font: "var(--text-sm)/1 var(--font-sans)", color: "var(--text-secondary)" }}>{d.subtitle}</div> : null}
                {d.plot ? <p style={{ margin: 0, color: "var(--text-primary)", lineHeight: 1.5, maxWidth: "70ch", font: "var(--text-sm)/1.5 var(--font-sans)" }}>{d.plot}</p> : null}
                {d.state === "FileNotFound" && (
                  <div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "6px 10px", borderRadius: "var(--radius-sm)", background: "var(--ctv-error-soft)", color: "var(--status-error)", font: "var(--text-xs)/1.2 var(--font-sans)", width: "fit-content" }}>
                    <Ico n="TriangleAlert" s={14} /><span>File not found</span>
                  </div>
                )}
                <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginTop: 4 }}>
                  {d.actions.includes("info") && <Button size="sm" variant="secondary" startIcon={<Ico n="Info" s={14} />} onClick={() => setInfoOpen(true)}>Media Info</Button>}
                  {d.actions.includes("troubleshoot") && <Button size="sm" variant="secondary" startIcon={<Ico n="Stethoscope" s={14} />}>Troubleshoot Playback</Button>}
                  {d.actions.includes("scan") && (
                    <React.Fragment>
                      <Button size="sm" variant="secondary" startIcon={<Ico n="ScanSearch" s={14} />}>Quick scan</Button>
                      <Button size="sm" variant="secondary" startIcon={<Ico n="ScanSearch" s={14} />}>Deep scan</Button>
                    </React.Fragment>
                  )}
                  {d.actions.includes("addto") && <Button size="sm" variant="primary" startIcon={<Ico n="Plus" s={14} />} endIcon={<Ico n="ChevronDown" s={13} />}>Add to…</Button>}
                </div>
              </div>
            </div>

            {d.chips.length > 0 && (
              <Card padded>
                <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                  {d.chips.map((c) => <ChipRow key={c.label} label={c.label} values={c.values} />)}
                </div>
              </Card>
            )}

            <ActorsRow actors={d.actors} />

            {d.path ? <div style={{ ...mono, position: "relative", zIndex: 1, fontSize: "var(--text-xs)", color: "var(--text-secondary)", wordBreak: "break-all" }}>{d.path}</div> : null}

            {d.grid && <ChildGrid heading={d.grid.heading} kind={d.grid.kind} count={d.grid.count} page={d.grid.page} pages={d.grid.pages} />}
          </div>
        </div>

        <MediaInfoDialog open={infoOpen} onClose={() => setInfoOpen(false)} />
      </div>
    );
  }

  window.CTVMediaDetail = MediaDetail;
})();
