// Logs screen — recent log entries with sortable timestamp/level columns, free-text filtering, and pagination.
(function () {
  const NS = window.ChicoryTVDesignSystem_eb3b61;
  const { Button, IconButton, Badge, Card, Input, Select, Spinner } = NS;
  const Ico = window.Ico;
  const mono = { fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" };

  const LEVEL_TONE = {
    Debug: 'neutral',
    Error: 'error',
    Fatal: 'error',
    Information: 'accent',
    Verbose: 'neutral',
    Warning: 'warn'
  };

  const mockEntries = [
    { timestamp: '2026-07-17 14:32:18.547', level: 'Information', message: 'Channel "HBO" started streaming' },
    { timestamp: '2026-07-17 14:31:45.123', level: 'Debug', message: 'FFmpeg process spawned (PID: 2847)' },
    { timestamp: '2026-07-17 14:30:22.891', level: 'Information', message: 'Scheduler triggered collection refresh' },
    { timestamp: '2026-07-17 14:28:55.456', level: 'Warning', message: 'Playout guide generation took 12.3s (expected <10s)' },
    { timestamp: '2026-07-17 14:27:30.234', level: 'Debug', message: 'Cache hit: channel logo for "HBO"' },
    { timestamp: '2026-07-17 14:25:12.789', level: 'Information', message: 'Database backup completed (8.4 MB)' },
    { timestamp: '2026-07-17 14:23:44.321', level: 'Error', message: 'FFmpeg failed for channel "News24" (exit code 1)' },
    { timestamp: '2026-07-17 14:22:15.654', level: 'Warning', message: 'Jellyfin API response time: 523ms' },
    { timestamp: '2026-07-17 14:20:08.987', level: 'Debug', message: 'XMLTV generator skipped 2 inactive channels' },
    { timestamp: '2026-07-17 14:18:30.445', level: 'Information', message: 'M3U playlist regenerated (128 channels)' },
    { timestamp: '2026-07-17 14:16:55.112', level: 'Warning', message: 'Slow query detected: GetChannelGuide (847ms)' },
    { timestamp: '2026-07-17 14:15:22.678', level: 'Debug', message: 'LRU cache evicted 3 stale entries' },
  ];

  const PAGE_SIZE_OPTIONS = ['25', '50', '100'];

  const th = {
    textAlign: "left",
    padding: "0 var(--pad-cell-x)",
    height: 34,
    font: "var(--weight-medium) var(--text-2xs)/1 var(--font-sans)",
    letterSpacing: "0.04em",
    textTransform: "uppercase",
    color: "var(--text-disabled)",
    whiteSpace: "nowrap",
    position: "sticky",
    top: 0,
    background: "var(--surface-card)",
    borderBottom: "1px solid var(--border-hairline)",
    zIndex: 2
  };

  const td = {
    padding: "0 var(--pad-cell-x)",
    height: 56,
    font: "var(--text-sm)/1.3 var(--font-sans)",
    color: "var(--text-primary)",
    verticalAlign: "middle"
  };

  function Logs() {
    const [filterInput, setFilterInput] = React.useState('');
    const [filter, setFilter] = React.useState('');
    const [pageNum, setPageNum] = React.useState(0);
    const [pageSize, setPageSize] = React.useState(50);
    const [sortField, setSortField] = React.useState('timestamp');
    const [sortDirection, setSortDirection] = React.useState('desc');
    const [isLoading, setIsLoading] = React.useState(false);

    // Mock: filter entries
    let filtered = mockEntries;
    if (filter) {
      const lowerFilter = filter.toLowerCase();
      filtered = filtered.filter(e =>
        e.level.toLowerCase().includes(lowerFilter) ||
        e.message.toLowerCase().includes(lowerFilter)
      );
    }

    // Mock: sort entries
    const sorted = [...filtered].sort((a, b) => {
      let cmp = 0;
      if (sortField === 'timestamp') {
        cmp = a.timestamp.localeCompare(b.timestamp);
      } else if (sortField === 'level') {
        cmp = a.level.localeCompare(b.level);
      }
      return sortDirection === 'desc' ? -cmp : cmp;
    });

    const totalCount = sorted.length;
    const totalPages = Math.max(1, Math.ceil(totalCount / pageSize));
    const start = pageNum * pageSize;
    const entries = sorted.slice(start, start + pageSize);

    const handleFilterChange = (e) => {
      setFilterInput(e.target.value);
      setPageNum(0);
      setFilter(e.target.value.trim());
    };

    const handlePageSizeChange = (e) => {
      setPageNum(0);
      setPageSize(Number(e.target.value));
    };

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

    const toggleSort = (field) => {
      setPageNum(0);
      if (field === sortField) {
        setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
      } else {
        setSortField(field);
        setSortDirection('asc');
      }
    };

    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
        }}>
          <Input
            leadingIcon={<Ico n="Search" s={14} />}
            onChange={handleFilterChange}
            placeholder="Filter by level or message…"
            value={filterInput}
            size="md"
          />
          <span style={{ flex: 1 }} />
          <Select
            onChange={handlePageSizeChange}
            options={PAGE_SIZE_OPTIONS}
            value={String(pageSize)}
            size="sm"
            style={{ width: 96 }}
          />
          <Button
            onClick={handleRefresh}
            size="sm"
            variant="secondary"
            startIcon={<Ico n="RefreshCw" s={14} />}
            loading={isLoading}
          >
            Refresh
          </Button>
        </div>

        {/* main content area */}
        <div style={{ flex: 1, overflow: "auto", padding: "16px 20px" }}>
          <Card padded={false}>
            {isLoading ? (
              <div style={{
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
                justifyContent: "center",
                gap: 12,
                padding: 48,
                color: "var(--text-secondary)"
              }}>
                <Spinner size={18} tone="accent" />
                <span style={{ font: "var(--text-sm)/1 var(--font-sans)" }}>Loading logs…</span>
              </div>
            ) : entries.length === 0 ? (
              <div style={{
                padding: 48,
                textAlign: "center",
                color: "var(--text-secondary)",
                font: "var(--text-sm)/1 var(--font-sans)"
              }}>
                {filter ? 'No log entries match this filter.' : 'No log entries found.'}
              </div>
            ) : (
              <div style={{ display: "flex", flexDirection: "column" }}>
                <div style={{ overflowX: "auto" }}>
                  <table style={{ width: "100%", borderCollapse: "collapse" }}>
                    <thead>
                      <tr>
                        <th style={{ ...th, width: 220 }}>
                          <button
                            type="button"
                            onClick={() => toggleSort('timestamp')}
                            style={{
                              display: "inline-flex",
                              alignItems: "center",
                              gap: 6,
                              background: "none",
                              border: "none",
                              cursor: "pointer",
                              color: "inherit",
                              font: "inherit",
                              padding: 0
                            }}
                          >
                            Timestamp
                            {sortField === 'timestamp' && (
                              <Ico n={sortDirection === 'asc' ? 'ChevronUp' : 'ChevronDown'} s={13} />
                            )}
                          </button>
                        </th>
                        <th style={{ ...th, width: 130 }}>
                          <button
                            type="button"
                            onClick={() => toggleSort('level')}
                            style={{
                              display: "inline-flex",
                              alignItems: "center",
                              gap: 6,
                              background: "none",
                              border: "none",
                              cursor: "pointer",
                              color: "inherit",
                              font: "inherit",
                              padding: 0
                            }}
                          >
                            Level
                            {sortField === 'level' && (
                              <Ico n={sortDirection === 'asc' ? 'ChevronUp' : 'ChevronDown'} s={13} />
                            )}
                          </button>
                        </th>
                        <th style={th}>Message</th>
                      </tr>
                    </thead>
                    <tbody>
                      {entries.map((entry, idx) => (
                        <tr key={idx} style={{ borderTop: "1px solid var(--border-hairline)" }}>
                          <td style={{ ...td, ...mono, width: 220, whiteSpace: "nowrap" }}>
                            {entry.timestamp}
                          </td>
                          <td style={{ ...td, width: 130 }}>
                            <Badge tone={LEVEL_TONE[entry.level] || 'neutral'}>
                              {entry.level}
                            </Badge>
                          </td>
                          <td style={{ ...td, ...mono }}>
                            {entry.message}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                {/* footer */}
                <div style={{
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "space-between",
                  padding: "10px 16px",
                  borderTop: "1px solid var(--border-hairline)",
                  font: "var(--text-xs)/1 var(--font-sans)",
                  color: "var(--text-secondary)",
                  flex: "0 0 auto"
                }}>
                  <span>
                    <span style={mono}>{totalCount}</span> entr{totalCount === 1 ? 'y' : 'ies'}
                    {filter && ` matching "${filter}"`}
                  </span>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                    <IconButton
                      size="sm"
                      title="Previous page"
                      disabled={pageNum === 0}
                      onClick={() => setPageNum(Math.max(0, pageNum - 1))}
                    >
                      <Ico n="ChevronLeft" s={15} />
                    </IconButton>
                    <span style={{ ...mono, fontSize: "var(--text-xs)", padding: "0 6px" }}>
                      {pageNum + 1} / {totalPages}
                    </span>
                    <IconButton
                      size="sm"
                      title="Next page"
                      disabled={pageNum + 1 >= totalPages}
                      onClick={() => setPageNum(pageNum + 1)}
                    >
                      <Ico n="ChevronRight" s={15} />
                    </IconButton>
                  </span>
                </div>
              </div>
            )}
          </Card>
        </div>

        {/* callout section */}
        <div style={{
          display: "flex",
          alignItems: "flex-start",
          gap: 12,
          padding: "12px 20px",
          margin: "12px 20px 0",
          borderRadius: "var(--radius-md)",
          background: "var(--ctv-accent-soft)",
          border: "1px solid var(--ctv-accent-ring)",
          font: "var(--text-xs)/1.5 var(--font-sans)",
          color: "var(--text-primary)"
        }}>
          <Ico n="Info" s={14} style={{ flex: "0 0 auto", marginTop: 1, color: "var(--ctv-accent)" }} />
          <span>
            Logs are read from the current server log file. Older, rotated log files aren't available here — check the config folder's <code style={{ ...mono, fontSize: "var(--text-xs)", color: "var(--text-secondary)" }}>logs</code> directory for history.
          </span>
        </div>
      </div>
    );
  }

  window.CTVLogs = Logs;
})();
