import {
  GENRE_FILTERS,
  LIBRARY_CATEGORIES,
  PLATFORM_FILTERS,
  PLAY_STATE_LABELS,
  SORT_OPTIONS,
  SOURCE_LABELS,
  TYPE_LABELS,
  formatPlaytime,
  formatShortDate,
  initialsForTitle,
  summarizeLibrary,
} from "./libraryModel.js";

const escapeHtml = (value) =>
  String(value ?? "")
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#039;");

const providerLabel = (source) => SOURCE_LABELS[source] ?? source;
const typeLabel = (type) => TYPE_LABELS[type] ?? type;

const navButton = ({ className, row, col, key, action, label, active = false, extra = "" }) => `
  <button
    class="${className} focusable ${active ? "is-active" : ""}"
    data-focusable="true"
    data-row="${row}"
    data-col="${col}"
    data-focus-key="${escapeHtml(key)}"
    data-action="${escapeHtml(action)}"
    aria-selected="${active ? "true" : "false"}"
    ${extra}
  >${label}</button>
`;

export const renderLibraryShell = () => `
<section class="view library-view" data-view="library">
  <header class="library-topbar">
    <div>
      <p class="library-eyebrow">Unified Library</p>
      <h1 class="library-title">Library</h1>
    </div>
    <div class="library-topbar-right">
      <div class="library-system-status">
        <span class="library-status-dot" aria-hidden="true"></span>
        <span data-date>---</span>
        <strong data-clock>--:--</strong>
      </div>
      <div class="library-actions">
        ${navButton({ className: "library-action", row: 0, col: 7, key: "library-scan", action: "scan", label: "Start Scan" })}
        ${navButton({ className: "library-action", row: 0, col: 8, key: "library-refresh", action: "refresh", label: "Refresh" })}
      </div>
    </div>
  </header>

  <main class="library-console" data-focus-root>
    <section class="library-main">
      <nav class="library-category-tabs" aria-label="Library categories" data-library-categories></nav>
      <nav class="library-genre-tabs" aria-label="Library filters" data-library-genres></nav>
      <section class="library-content-row">
        <aside class="library-sidebar">
          <section class="library-summary-card" data-library-summary></section>
          <section class="library-filter-card" data-library-filters></section>
        </aside>
        <section class="library-grid-region">
          <div class="library-grid-header">
            <div>
              <p class="library-section-kicker" data-library-result-kicker>Ready</p>
              <h2 data-library-result-title>Controller Library</h2>
            </div>
            <p class="library-status-copy" data-library-status>Loading library...</p>
          </div>
          <div class="library-grid" data-library-grid></div>
        </section>
      </section>
    </section>
  </main>

  <aside class="library-details-panel" data-library-details aria-hidden="true"></aside>
  <aside class="library-sort-panel" data-library-sort-panel aria-hidden="true"></aside>
</section>
`;

export const renderCategoryTabs = (query) =>
  LIBRARY_CATEGORIES.map((category, index) =>
    navButton({
      className: "library-category-tab",
      row: 1,
      col: index,
      key: `library-category-${category.id}`,
      action: "category",
      label: escapeHtml(category.label),
      active: query.category === category.id,
      extra: `data-category="${category.id}"`,
    }),
  ).join("");

export const renderGenreTabs = (query) =>
  GENRE_FILTERS.map((genre, index) =>
    navButton({
      className: "library-genre-tab",
      row: 2,
      col: index,
      key: `library-genre-${index}`,
      action: "genre",
      label: escapeHtml(genre),
      active: query.genre === genre,
      extra: `data-genre="${escapeHtml(genre)}"`,
    }),
  ).join("");

export const renderSummary = (items, status, message) => {
  const summary = summarizeLibrary(items);
  return `
    <p class="library-section-kicker">Library Summary</p>
    <div class="library-summary-total">
      <strong>${summary.total}</strong>
      <span>Total apps</span>
    </div>
    <div class="library-stat-grid">
      <span><strong>${summary.games}</strong> Games</span>
      <span><strong>${summary.verified}</strong> Verified</span>
      <span><strong>${summary.hidden}</strong> Hidden</span>
      <span><strong>${summary.installed}</strong> Installed</span>
    </div>
    <div class="library-sync-status">
      <span class="library-status-dot" aria-hidden="true"></span>
      <div>
        <strong>${escapeHtml(status)}</strong>
        <p>${escapeHtml(message)}</p>
      </div>
    </div>
  `;
};

export const renderFilters = (query) => {
  const platformButtons = PLATFORM_FILTERS.map((platform, index) =>
    navButton({
      className: "library-filter-chip",
      row: 4 + index,
      col: 0,
      key: `library-platform-${platform}`,
      action: "platform",
      label: platform === "all" ? "All Platforms" : providerLabel(platform),
      active: query.platform === platform,
      extra: `data-platform="${platform}"`,
    }),
  ).join("");

  return `
    <p class="library-section-kicker">Filter Toggles</p>
    <div class="library-filter-group">
      <span class="library-filter-label">By Platform</span>
      ${platformButtons}
    </div>
    <div class="library-filter-group">
      ${navButton({
        className: "library-filter-chip",
        row: 11,
        col: 0,
        key: "library-installed-only",
        action: "toggle-installed",
        label: "Installed Only",
        active: query.installedOnly,
      })}
      ${navButton({
        className: "library-filter-chip",
        row: 12,
        col: 0,
        key: "library-play-state",
        action: "cycle-play-state",
        label: `Play State: ${PLAY_STATE_LABELS[query.playState]}`,
        active: query.playState !== "all",
      })}
      ${navButton({
        className: "library-filter-chip",
        row: 13,
        col: 0,
        key: "library-coop",
        action: "toggle-coop",
        label: "Co-op",
        active: query.coOpOnly,
      })}
      ${navButton({
        className: "library-filter-chip",
        row: 14,
        col: 0,
        key: "library-achievements",
        action: "toggle-achievements",
        label: "Achievements",
        active: query.achievementsOnly,
      })}
    </div>
  `;
};

export const renderGrid = (items, focusedId) => {
  if (!items.length) {
    return `
      <article class="library-empty-card">
        <p class="library-section-kicker">No Matches</p>
        <h3>No apps match these filters.</h3>
        <p>Press Y to open sorting and filters, or clear toggles from the left panel.</p>
      </article>
    `;
  }

  return items
    .map((item, index) => {
      const row = 4 + Math.floor(index / 4);
      const col = 2 + (index % 4);
      const artStyle = item.coverImage
        ? `style="--library-art: url('${escapeHtml(item.coverImage)}'); --library-accent: ${escapeHtml(item.accent)};"`
        : `style="--library-accent: ${escapeHtml(item.accent)};"`;
      const achievementCopy = item.achievementsSupported
        ? `${item.achievementsUnlocked ?? 0}/${item.achievementsTotal ?? "?"} achievements`
        : "No achievements";

      return `
        <button
          class="library-card focusable ${focusedId === item.id ? "is-selected-card" : ""}"
          data-focusable="true"
          data-row="${row}"
          data-col="${col}"
          data-focus-key="library-card-${escapeHtml(item.id)}"
          data-action="card"
          data-item-id="${escapeHtml(item.id)}"
          aria-label="${escapeHtml(item.title)}"
        >
          <div class="library-card-art ${item.coverImage ? "has-image" : ""}" ${artStyle}>
            <span>${escapeHtml(initialsForTitle(item.title))}</span>
            ${item.steamDeckVerified ? `<em class="library-verified-badge">Verified</em>` : ""}
          </div>
          <div class="library-card-body">
            <div class="library-card-title-row">
              <h3>${escapeHtml(item.title)}</h3>
              <span>${item.installed ? "Installed" : "Not installed"}</span>
            </div>
            <p>${escapeHtml(providerLabel(item.source))} · ${escapeHtml(typeLabel(item.type))}</p>
            <div class="library-card-meta-row">
              <span>${escapeHtml(formatShortDate(item.lastPlayed))}</span>
              <span>${escapeHtml(formatPlaytime(item.playtimeMinutes))}</span>
            </div>
            <p class="library-card-focus-copy">${escapeHtml(item.description)}</p>
            <p class="library-card-achievements">${escapeHtml(achievementCopy)}</p>
          </div>
        </button>
      `;
    })
    .join("");
};

export const renderDetailsPanel = (item) => {
  if (!item) return "";
  
  const achievements = item.achievementsSupported
    ? `${item.achievementsUnlocked ?? 0} / ${item.achievementsTotal ?? "?"}`
    : "Not supported";
  
  const screenshotsHtml = item.screenshots && item.screenshots.length > 0
    ? `
      <div class="game-detail-screenshots">
        <h3 class="game-detail-section-title">Screenshots</h3>
        <div class="screenshots-carousel">
          ${item.screenshots.map((screenshot, index) => `
            <div class="screenshot-item" data-screenshot-index="${index}">
              <img src="${escapeHtml(screenshot)}" alt="Screenshot ${index + 1}" />
            </div>
          `).join("")}
        </div>
      </div>
    `
    : '';
  
  const achievementsHtml = item.achievementsSupported
    ? `
      <div class="game-detail-achievements">
        <h3 class="game-detail-section-title">Achievements</h3>
        <div class="achievements-container">
          <div class="achievements-progress">
            <div class="achievement-stat">
              <span class="achievement-number">${item.achievementsUnlocked ?? 0}</span>
              <span class="achievement-label">Unlocked</span>
            </div>
            <div class="achievement-bar">
              <div class="achievement-bar-fill" style="width: ${item.achievementsTotal ? Math.round((item.achievementsUnlocked ?? 0) / item.achievementsTotal * 100) : 0}%"></div>
            </div>
            <div class="achievement-stat">
              <span class="achievement-number">${item.achievementsTotal ?? "?"}</span>
              <span class="achievement-label">Total</span>
            </div>
          </div>
        </div>
      </div>
    `
    : '';
  
  const featuresHtml = `
    <div class="game-detail-features">
      <h3 class="game-detail-section-title">Features</h3>
      <div class="features-grid">
        ${item.supportsController ? '<span class="feature-badge">Controller Support</span>' : ''}
        ${item.steamDeckVerified ? '<span class="feature-badge verified">Steam Deck Verified</span>' : ''}
        ${item.multiplayer ? '<span class="feature-badge">Multiplayer</span>' : ''}
        ${item.coOp ? '<span class="feature-badge">Co-op</span>' : ''}
      </div>
    </div>
  `;

  return `
    <div class="library-details-backdrop" data-action="close-details"></div>
    <section class="game-detail-view" data-focus-root>
      <div class="game-detail-header-image" style="${
        item.bannerImage || item.coverImage
          ? `background-image: url('${escapeHtml(item.bannerImage || item.coverImage)}');`
          : `background: linear-gradient(135deg, ${escapeHtml(item.accent)}, ${escapeHtml(item.accent)}cc);`
      }">
        <div class="game-detail-header-overlay"></div>
      </div>
      
      <div class="game-detail-content" data-focus-root>
        <div class="game-detail-header">
          <div class="game-detail-title-section">
            <p class="library-section-kicker">${escapeHtml(providerLabel(item.source))} · ${escapeHtml(typeLabel(item.type))}</p>
            <h1 class="game-detail-title">${escapeHtml(item.title)}</h1>
            <div class="game-detail-meta">
              <span>${item.installed ? '✓ Installed' : 'Not installed'}</span>
              ${item.lastPlayed ? `<span>Last played: ${escapeHtml(formatShortDate(item.lastPlayed))}</span>` : ''}
              ${item.playtimeMinutes > 0 ? `<span>${escapeHtml(formatPlaytime(item.playtimeMinutes))}</span>` : ''}
            </div>
          </div>
          
          <div class="game-detail-play-button-container">
            <button
              class="game-detail-play-button focusable"
              data-focusable="true"
              data-row="3"
              data-col="2"
              data-action="launch"
              data-focus-key="game-detail-play-button"
            >
              <span class="play-icon">▶</span>
              <span class="play-text">${item.installed ? 'PLAY' : 'INSTALL'}</span>
            </button>
          </div>
        </div>
        
        <div class="game-detail-main">
          <div class="game-detail-left-column">
            <div class="game-detail-description">
              <h3 class="game-detail-section-title">About</h3>
              <p>${escapeHtml(item.description)}</p>
              ${item.longDescription ? `<p class="long-description">${escapeHtml(item.longDescription)}</p>` : ''}
            </div>
            
            <div class="game-detail-info">
              <h3 class="game-detail-section-title">Details</h3>
              <dl class="game-detail-info-list">
                <div>
                  <dt>Genres</dt>
                  <dd>${escapeHtml(item.genre.join(', '))}</dd>
                </div>
                <div>
                  <dt>Source</dt>
                  <dd>${escapeHtml(providerLabel(item.source))}</dd>
                </div>
                ${item.installed ? `<div>
                  <dt>Install Location</dt>
                  <dd>${escapeHtml(item.installPath)}</dd>
                </div>` : ''}
                ${item.installedAt ? `<div>
                  <dt>Installed</dt>
                  <dd>${escapeHtml(formatShortDate(item.installedAt))}</dd>
                </div>` : ''}
                ${item.playtimeMinutes > 0 ? `<div>
                  <dt>Playtime</dt>
                  <dd>${escapeHtml(formatPlaytime(item.playtimeMinutes))}</dd>
                </div>` : ''}
              </dl>
            </div>
            
            ${screenshotsHtml}
          </div>
          
          <div class="game-detail-right-column">
            ${featuresHtml}
            ${achievementsHtml}
            
            <div class="game-detail-actions">
              ${["Hide", "Open Folder"]
                .filter(label => {
                  if (label === "Open Folder" && !item.installed) return false;
                  return true;
                })
                .map(
                  (label, index) => `
                    <button
                      class="library-detail-button focusable"
                      data-focusable="true"
                      data-row="${8 + index}"
                      data-col="2"
                      data-action="${escapeHtml(label.toLowerCase().replaceAll(" ", "-"))}"
                      data-focus-key="game-detail-action-${index}"
                    >${escapeHtml(label)}</button>
                  `,
                )
                .join("")}
            </div>
          </div>
        </div>
      </div>
    </section>
  `;
};

export const renderSortPanel = (query) => `
  <div class="library-sort-backdrop" data-action="close-sort"></div>
  <section class="library-sort-card">
    <p class="library-section-kicker">Sort Library</p>
    <h2>Filter / Sort</h2>
    <p>Use Y to close. These options immediately reorder the visible grid.</p>
    <div class="library-sort-options">
      ${SORT_OPTIONS.map((option, index) =>
        navButton({
          className: "library-sort-option",
          row: 18 + index,
          col: 6,
          key: `library-sort-${option.id}`,
          action: "sort",
          label: escapeHtml(option.label),
          active: query.sortBy === option.id,
          extra: `data-sort="${option.id}"`,
        }),
      ).join("")}
    </div>
  </section>
`;
