// Trash screen — media browser showing items with missing files, grouped by media type,
// with bulk selection and delete controls. Grid layout with poster cards.
(function () {
  const NS = window.ChicoryTVDesignSystem_eb3b61;
  const { Button, Spinner, Card } = NS;
  const Ico = window.Ico;
  const mono = { fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" };

  // Mock data: media type groups with items and counts
  const TRASH_DATA = {
    movies: {
      label: "Movies",
      totalCount: 12,
      items: [
        { id: 1, title: "The Long Goodbye", mediaType: "Movie", hue: 120 },
        { id: 2, title: "Blade Runner 2049", mediaType: "Movie", hue: 180 },
        { id: 3, title: "Stalker", mediaType: "Movie", hue: 240 }
      ]
    },
    shows: {
      label: "TV Shows",
      totalCount: 8,
      items: [
        { id: 4, title: "The Wire", mediaType: "TelevisionShow", hue: 300 },
        { id: 5, title: "Twin Peaks", mediaType: "TelevisionShow", hue: 30 },
        { id: 6, title: "The Sopranos", mediaType: "TelevisionShow", hue: 60 },
        { id: 7, title: "Mindhunter", mediaType: "TelevisionShow", hue: 90 }
      ]
    },
    episodes: {
      label: "Episodes",
      totalCount: 34,
      items: [
        { id: 8, title: "Ozymandias", mediaType: "Episode", hue: 150 },
        { id: 9, title: "Half Measures", mediaType: "Episode", hue: 210 }
      ]
    },
    images: {
      label: "Images",
      totalCount: 5,
      items: [
        { id: 10, title: "Landscape Photo", mediaType: "Image", hue: 45 }
      ]
    }
  };

  // Deterministic color based on hue
  function posterGradient(hue) {
    return `linear-gradient(160deg, hsl(${hue} 24% 17%), hsl(${hue} 26% 12%))`;
  }

  // Icon type mapping
  const TYPE_ICON = {
    Movie: "Film",
    TelevisionShow: "Tv",
    TelevisionSeason: "BookOpen",
    Episode: "Play",
    Artist: "Music",
    MusicVideo: "Music",
    Song: "Music",
    OtherVideo: "Video",
    Image: "Image",
    RemoteStream: "Radio"
  };

  function PosterCard({ item, selected, onToggle }) {
    const icon = TYPE_ICON[item.mediaType] || "Film";
    return (
      <div
        onClick={() => onToggle(item.id)}
        style={{
          position: "relative",
          cursor: "pointer",
          userSelect: "none",
          opacity: selected ? 1 : 0.95,
          transition: "opacity var(--dur-fast)",
          display: "flex",
          flexDirection: "column",
          height: "100%"
        }}
      >
        {/* Poster */}
        <div
          style={{
            position: "relative",
            width: "100%",
            aspectRatio: "2 / 3",
            background: posterGradient(item.hue),
            borderRadius: "var(--radius-md)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            overflow: "hidden",
            border: selected ? "2px solid var(--ctv-accent)" : "1px solid var(--border-hairline)",
            boxShadow: selected ? "0 0 0 3px var(--ctv-accent-soft)" : "none",
            transition: "border var(--dur-fast), box-shadow var(--dur-fast)"
          }}
        >
          <div
            style={{
              position: "absolute",
              inset: 0,
              backgroundImage: `repeating-linear-gradient(135deg, hsl(${item.hue} 22% 10% / .55) 0 1px, transparent 1px 9px)`
            }}
          />
          <Ico n={icon} s={24} color={`hsl(${item.hue} 30% 68%)`} />
          {selected && (
            <div
              style={{
                position: "absolute",
                top: 6,
                right: 6,
                width: 24,
                height: 24,
                borderRadius: "var(--radius-xs)",
                background: "var(--ctv-accent)",
                color: "white",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                fontSize: 14,
                fontWeight: "var(--weight-bold)"
              }}
            >
              ✓
            </div>
          )}
        </div>
        {/* Title + meta */}
        <div style={{ marginTop: 8, minWidth: 0 }}>
          <div
            style={{
              font: "var(--weight-medium) var(--text-xs)/1.3 var(--font-sans)",
              color: "var(--text-primary)",
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
              title: item.title
            }}
            title={item.title}
          >
            {item.title}
          </div>
          <div style={{ font: "var(--text-2xs)/1 var(--font-sans)", color: "var(--text-secondary)", marginTop: 2 }}>
            {item.mediaType}
          </div>
        </div>
      </div>
    );
  }

  function Trash() {
    const [selected, setSelected] = React.useState(new Set());
    const [showError, setShowError] = React.useState(false);
    const [isLoading, setIsLoading] = React.useState(false);

    const totalCount = Object.values(TRASH_DATA).reduce((sum, g) => sum + g.totalCount, 0);
    const selectedCount = selected.size;

    const toggleItem = (itemId) => {
      const next = new Set(selected);
      if (next.has(itemId)) {
        next.delete(itemId);
      } else {
        next.add(itemId);
      }
      setSelected(next);
    };

    const selectAll = () => {
      const all = new Set();
      Object.values(TRASH_DATA).forEach((group) => {
        group.items.forEach((item) => all.add(item.id));
      });
      setSelected(all);
    };

    const clearSelection = () => setSelected(new Set());

    const handleRefresh = () => {
      setIsLoading(true);
      setTimeout(() => setIsLoading(false), 1000);
    };

    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,
            background: "var(--surface-card)"
          }}
        >
          {selectedCount > 0 ? (
            <>
              <span style={{ font: "var(--weight-medium) var(--text-sm)/1 var(--font-sans)", color: "var(--text-primary)" }}>
                <span style={mono}>{selectedCount}</span> selected
              </span>
              <span style={{ width: 1, height: 18, background: "var(--border-hairline)" }} />
              <Button size="sm" variant="danger" startIcon={<Ico n="Trash2" s={14} />}>
                Delete
              </Button>
              <span style={{ flex: 1 }} />
              <Button size="sm" variant="ghost" onClick={clearSelection}>
                Clear
              </Button>
            </>
          ) : (
            <>
              <Button size="sm" variant="secondary" disabled={totalCount === 0} onClick={selectAll}>
                Select all
              </Button>
              <span style={{ flex: 1 }} />
              <Button size="sm" variant="secondary" startIcon={<Ico n="RefreshCw" s={14} />} onClick={handleRefresh}>
                Refresh
              </Button>
              <Button size="sm" variant="danger" disabled={totalCount === 0} startIcon={<Ico n="Trash2" s={14} />}>
                Empty Trash
              </Button>
            </>
          )}
        </div>

        {/* Error banner */}
        {showError && (
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 12,
              padding: "12px 20px",
              background: "var(--ctv-error-soft)",
              borderBottom: "1px solid var(--status-error)",
              color: "var(--status-error)"
            }}
            role="alert"
          >
            <Ico n="AlertTriangle" s={15} />
            <span style={{ font: "var(--text-sm)/1.3 var(--font-sans)", flex: 1 }}>
              Failed to load trash items. Please try again.
            </span>
            <span style={{ flex: 1 }} />
            <Button size="sm" variant="secondary" onClick={() => setShowError(false)}>
              Dismiss
            </Button>
          </div>
        )}

        {/* Loading state */}
        {isLoading && (
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              justifyContent: "center",
              gap: 12,
              padding: "80px 20px",
              flex: 1
            }}
            role="status"
          >
            <Spinner size={24} tone="accent" />
            <span style={{ font: "var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-secondary)" }}>
              Loading trash…
            </span>
          </div>
        )}

        {/* Empty state */}
        {!isLoading && totalCount === 0 && (
          <div style={{ flex: 1, overflow: "auto", padding: "40px 20px" }}>
            <Card padded>
              <div
                style={{
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  justifyContent: "center",
                  gap: 12,
                  padding: "60px 20px",
                  textAlign: "center"
                }}
              >
                <Ico n="CheckCircle2" s={32} color="var(--status-ok)" />
                <div>
                  <div style={{ font: "var(--weight-medium) var(--text-md)/1.3 var(--font-sans)", color: "var(--text-primary)" }}>
                    Trash is empty
                  </div>
                  <div style={{ font: "var(--text-sm)/1.4 var(--font-sans)", color: "var(--text-secondary)", marginTop: 4 }}>
                    No missing files detected.
                  </div>
                </div>
              </div>
            </Card>
          </div>
        )}

        {/* Content — sections */}
        {!isLoading && totalCount > 0 && (
          <div style={{ flex: 1, overflow: "auto", padding: "16px 20px" }}>
            {Object.entries(TRASH_DATA).map(([key, group]) => {
              if (group.totalCount === 0 || group.items.length === 0) {
                return null;
              }
              const hasMore = group.items.length < group.totalCount;

              return (
                <section key={key} style={{ marginBottom: 40 }}>
                  {/* Section header */}
                  <div
                    style={{
                      display: "flex",
                      alignItems: "baseline",
                      gap: 12,
                      marginBottom: 16,
                      paddingBottom: 8,
                      borderBottom: "1px solid var(--border-hairline)"
                    }}
                  >
                    <h2 style={{ font: "var(--weight-semibold) var(--text-lg)/1.2 var(--font-sans)", color: "var(--text-primary)", margin: 0 }}>
                      {group.label}
                    </h2>
                    <span style={{ ...mono, font: "var(--text-xs)/1 var(--font-mono)", color: "var(--text-secondary)" }}>
                      {group.totalCount} missing
                    </span>
                  </div>

                  {/* Grid of cards */}
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "repeat(auto-fill, minmax(120px, 1fr))",
                      gap: 16,
                      marginBottom: hasMore ? 16 : 0
                    }}
                  >
                    {group.items.map((item) => (
                      <PosterCard
                        key={`${item.mediaType}-${item.id}`}
                        item={item}
                        selected={selected.has(item.id)}
                        onToggle={toggleItem}
                      />
                    ))}
                  </div>

                  {/* "See all" button */}
                  {hasMore && (
                    <div style={{ display: "flex", justifyContent: "center", paddingTop: 12 }}>
                      <Button size="sm" variant="secondary">
                        See all {group.totalCount} {group.label.toLowerCase()}
                      </Button>
                    </div>
                  )}
                </section>
              );
            })}
          </div>
        )}
      </div>
    );
  }

  window.CTVTrash = Trash;
})();
