const getTauriCore = async () => {
  const globalCore = window.__TAURI__?.core;
  if (typeof globalCore?.invoke === "function") {
    return {
      invoke: globalCore.invoke,
      convertFileSrc: typeof globalCore.convertFileSrc === "function" ? globalCore.convertFileSrc : null,
    };
  }

  try {
    const tauriCore = await import("@tauri-apps/api/core");
    return {
      invoke: typeof tauriCore.invoke === "function" ? tauriCore.invoke : null,
      convertFileSrc: typeof tauriCore.convertFileSrc === "function" ? tauriCore.convertFileSrc : null,
    };
  } catch (_error) {
    return { invoke: null, convertFileSrc: null };
  }
};

const sourceLabel = (source) => {
  const labels = {
    steam: "Steam",
    epic: "Epic Games",
    gog: "GOG",
    local: "Local",
    unknown: "Unknown",
  };
  return labels[source] ?? "Library";
};

const gameTitle = (game) => game?.userTitle || game?.title || "No games scanned yet";

const gameArtUrl = (game, convertFileSrc, key = "heroImage") => {
  const path = game?.[key] || game?.coverImage || game?.iconImage;
  if (!path || !convertFileSrc) return "";
  return convertFileSrc(path);
};

const initialsForTitle = (title) =>
  title
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase())
    .join("") || "OS";

const HOME_TEMPLATE = `
<section class="view home-view" data-view="home">

  <!-- ── Top status bar ─────────────────────────────── -->
  <header class="home-topbar">
    <span class="home-time" data-clock>--:--</span>
    <div class="home-status-icons" aria-label="System status">
      <span class="home-status-icon" title="Wi-Fi">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
          <path d="M5 12.55a11 11 0 0 1 14.08 0"/><path d="M1.42 9a16 16 0 0 1 21.16 0"/><path d="M8.53 16.11a6 6 0 0 1 6.95 0"/><circle cx="12" cy="20" r="1" fill="currentColor"/>
        </svg>
      </span>
      <span class="home-status-icon" title="Controller">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
          <rect x="2" y="6" width="20" height="12" rx="6"/><path d="M6 12h4m-2-2v4"/><circle cx="17" cy="11" r="1" fill="currentColor"/><circle cx="15" cy="13" r="1" fill="currentColor"/>
        </svg>
      </span>
      <span class="home-status-icon" title="Battery">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
          <rect x="1" y="6" width="18" height="12" rx="2"/><path d="M23 11v2" stroke-width="2.5" stroke-linecap="round"/><rect x="3" y="8" width="12" height="8" rx="1" fill="currentColor" stroke="none"/>
        </svg>
      </span>
    </div>
  </header>

  <!-- ── Main body: center + right panel ───────────── -->
  <div class="home-body">

    <!-- ── Center column ──────────────────────────── -->
    <div class="home-center">

      <!-- Category tabs -->
      <nav class="home-tabs" aria-label="Content categories">
        <button
          class="home-tab is-active focusable"
          data-focusable="true" data-row="0" data-col="0"
          data-focus-key="tab-now-playing"
          aria-selected="true"
        >Now Playing</button>
        <button
          class="home-tab focusable"
          data-focusable="true" data-row="0" data-col="1"
          data-focus-key="tab-featured"
          aria-selected="false"
        >Featured</button>
        <span class="tab-hint" aria-hidden="true">
          <span class="btn-glyph">LT</span> / <span class="btn-glyph">RT</span>
          to cycle categories
        </span>
      </nav>

      <!-- Hero game card -->
      <article class="hero-card" aria-label="Library hero" data-home-hero>
        <div class="hero-art" aria-hidden="true" data-hero-art>
          <div class="hero-art-bg"></div>
          <div class="hero-art-mid"></div>
          <div class="hero-art-character"></div>
          <div class="hero-title-watermark" aria-hidden="true" data-hero-watermark>NEBULA<br>LIBRARY</div>
          <div class="hero-ctrl-overlay" aria-hidden="true">
            <svg class="ctrl-glyph ctrl-analog" width="48" height="48" viewBox="0 0 48 48" fill="none">
              <circle cx="24" cy="24" r="22" stroke="rgba(255,255,255,0.3)" stroke-width="2"/>
              <circle cx="24" cy="24" r="10" stroke="rgba(255,255,255,0.25)" stroke-width="1.5"/>
              <circle cx="24" cy="24" r="4" fill="rgba(255,255,255,0.2)"/>
            </svg>
            <svg class="ctrl-glyph ctrl-dpad" width="40" height="40" viewBox="0 0 40 40" fill="none">
              <rect x="13" y="4" width="14" height="32" rx="3" fill="rgba(255,255,255,0.18)"/>
              <rect x="4" y="13" width="32" height="14" rx="3" fill="rgba(255,255,255,0.18)"/>
              <rect x="15" y="15" width="10" height="10" rx="2" fill="rgba(255,255,255,0.1)"/>
            </svg>
            <span class="hero-l-badge">L</span>
          </div>
        </div>

        <!-- Gradient overlay + info -->
        <div class="hero-overlay">
          <div class="hero-info">
            <p class="hero-game-meta" data-hero-meta>Scan your device to populate Home</p>
            <h1 class="hero-game-title" data-hero-title>No games scanned yet</h1>
            <div class="hero-actions">
              <button
                class="hero-btn hero-btn-primary focusable"
                data-focusable="true" data-row="1" data-col="0"
                data-focus-key="btn-continue"
                data-target="library"
              >
                <span class="btn-prompt btn-a" aria-label="A button">A</span>
                Open Library
              </button>
              <button
                class="hero-btn focusable"
                data-focusable="true" data-row="1" data-col="1"
                data-focus-key="btn-progress"
                data-target="library"
              >
                <span class="btn-prompt btn-x" aria-label="X button">X</span>
                Manage Games
              </button>
              <button
                class="hero-btn focusable"
                data-focusable="true" data-row="1" data-col="2"
                data-focus-key="btn-community"
                data-target="library"
              >
                <span class="btn-prompt btn-y" aria-label="Y button">Y</span>
                Review Matches
              </button>
            </div>
          </div>
          <div class="hero-dots" aria-hidden="true">
            <span class="hero-dot is-active"></span>
            <span class="hero-dot"></span>
            <span class="hero-dot"></span>
            <span class="hero-dot"></span>
            <span class="hero-dot"></span>
          </div>
        </div>
      </article>

      <!-- Featured strip -->
      <section class="featured-strip" aria-label="Featured games">
        <h2 class="section-label">Featured</h2>
        <div class="featured-row">
          <button class="featured-thumb focusable" data-focusable="true" data-row="3" data-col="0" data-focus-key="feat-0" data-featured-slot="0" aria-label="Featured game"></button>
          <button class="featured-thumb focusable" data-focusable="true" data-row="3" data-col="1" data-focus-key="feat-1" data-featured-slot="1" aria-label="Featured game"></button>
          <button class="featured-thumb focusable" data-focusable="true" data-row="3" data-col="2" data-focus-key="feat-2" data-featured-slot="2" aria-label="Featured game"></button>
          <button class="featured-thumb focusable" data-focusable="true" data-row="3" data-col="3" data-focus-key="feat-3" data-featured-slot="3" aria-label="Featured game"></button>
        </div>
      </section>
    </div>

    <!-- ── Right panel ─────────────────────────────── -->
    <aside class="home-right-panel" aria-label="Quick launch and activity">

      <!-- Quick Launch grid -->
      <section class="quick-launch" aria-label="Quick launch">
        <div class="panel-header-row">
          <h2 class="panel-heading">Quick Launch</h2>
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
            <rect x="1" y="1" width="6" height="6" rx="1" fill="rgba(79,216,255,0.5)"/>
            <rect x="9" y="1" width="6" height="6" rx="1" fill="rgba(79,216,255,0.5)"/>
            <rect x="1" y="9" width="6" height="6" rx="1" fill="rgba(79,216,255,0.5)"/>
            <rect x="9" y="9" width="6" height="6" rx="1" fill="rgba(79,216,255,0.5)"/>
          </svg>
        </div>
        <div class="quick-grid">
          <button class="quick-tile focusable" data-focusable="true" data-row="1" data-col="3" data-focus-key="ql-0" data-quick-slot="0" aria-label="Library slot">
            <div class="quick-tile-art" aria-hidden="true"><span class="quick-tile-initials">OS</span></div>
            <div class="quick-tile-footer">
              <p class="quick-tile-name">Scan Library</p>
              <p class="quick-tile-meta">No game yet</p>
            </div>
          </button>
          <button class="quick-tile focusable" data-focusable="true" data-row="1" data-col="4" data-focus-key="ql-1" data-quick-slot="1" aria-label="Library slot">
            <div class="quick-tile-art" aria-hidden="true"><span class="quick-tile-initials">OS</span></div>
            <div class="quick-tile-footer">
              <p class="quick-tile-name">Scan Library</p>
              <p class="quick-tile-meta">No game yet</p>
            </div>
          </button>
          <button class="quick-tile focusable" data-focusable="true" data-row="1" data-col="5" data-focus-key="ql-2" data-quick-slot="2" aria-label="Library slot">
            <div class="quick-tile-art" aria-hidden="true"><span class="quick-tile-initials">OS</span></div>
            <div class="quick-tile-footer">
              <p class="quick-tile-name">Scan Library</p>
              <p class="quick-tile-meta">No game yet</p>
            </div>
          </button>
          <button class="quick-tile focusable" data-focusable="true" data-row="2" data-col="3" data-focus-key="ql-3" data-quick-slot="3" aria-label="Library slot">
            <div class="quick-tile-art" aria-hidden="true"><span class="quick-tile-initials">OS</span></div>
            <div class="quick-tile-footer">
              <p class="quick-tile-name">Scan Library</p>
              <p class="quick-tile-meta">No game yet</p>
            </div>
          </button>
          <button class="quick-tile focusable" data-focusable="true" data-row="2" data-col="4" data-focus-key="ql-4" data-quick-slot="4" aria-label="Library slot">
            <div class="quick-tile-art" aria-hidden="true"><span class="quick-tile-initials">OS</span></div>
            <div class="quick-tile-footer">
              <p class="quick-tile-name">Scan Library</p>
              <p class="quick-tile-meta">No game yet</p>
            </div>
          </button>
          <button class="quick-tile focusable" data-focusable="true" data-row="2" data-col="5" data-focus-key="ql-5" data-quick-slot="5" aria-label="Library slot">
            <div class="quick-tile-art" aria-hidden="true"><span class="quick-tile-initials">OS</span></div>
            <div class="quick-tile-footer">
              <p class="quick-tile-name">Scan Library</p>
              <p class="quick-tile-meta">No game yet</p>
            </div>
          </button>
        </div>
      </section>

      <!-- Friends + System Activity -->
      <div class="side-bottom-panels">
        <section class="friends-panel" aria-label="Friends online">
          <div class="panel-header-row">
            <h3 class="panel-heading-sm">Friends Online</h3>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
              <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>
            </svg>
          </div>
          <div class="friends-avatars" aria-label="Future account integrations">
            <p class="home-placeholder-copy">Account integrations coming later.</p>
          </div>
        </section>

        <section class="activity-panel" aria-label="System activity">
          <h3 class="panel-heading-sm">System Activity</h3>
          <div class="activity-row">
            <span class="activity-label" data-home-library-count>0 Games</span>
          </div>
          <p class="activity-hint" data-home-activity-hint>Scan from Library to populate Home.</p>
        </section>
      </div>

    </aside>
  </div>
</section>
`;

export const createHomeView = ({ state, renderView, openPowerMenu }) => ({
  id: "home",
  render: () => HOME_TEMPLATE,
  mount: async () => {
    const view = document.querySelector("[data-view='home']");
    if (!view) return;

    view.querySelectorAll(".home-tab").forEach((tab) => {
      tab.addEventListener("click", () => {
        view.querySelectorAll(".home-tab").forEach((t) => {
          t.classList.remove("is-active");
          t.setAttribute("aria-selected", "false");
        });
        tab.classList.add("is-active");
        tab.setAttribute("aria-selected", "true");
      });
    });

    await hydrateHomeLibrary(view);
  },
  getNavigationContract: () => {
    const root = document.querySelector("[data-view='home']");
    return {
      focusRoot: root,
      defaultFocus: root?.querySelector("[data-focus-key='btn-continue']") ?? null,
      layout: { type: "grid", cols: 6, rows: 4 },
      hintsTemplate: "#global-hints-template",
      nebulaNavigation: state.nebula.navigation,
      useNebulaNavigation: false,
      onAccept: (element) => {
        if (!element) return;
        const target = element.dataset.target;
        const focusKey = element.dataset.focusKey;

        if (target === "power") {
          openPowerMenu();
          return;
        }
        if (target) {
          state.activeView = target;
          renderView(target);
          return;
        }

        if (element.dataset.gameId || element.dataset.quickSlot || element.dataset.featuredSlot) {
          state.activeView = "library";
          renderView("library");
          return;
        }

        if (focusKey === "tab-now-playing" || focusKey === "tab-featured") {
          element.click();
        }
      },
      onBack: () => {
        state.locked = true;
        state.activeView = "lock";
        renderView("lock");
      },
      onMenu: () => {},
    };
  },
});

const hydrateHomeLibrary = async (view) => {
  const { invoke, convertFileSrc } = await getTauriCore();
  if (!invoke) {
    setEmptyHomeState(view, "Run NebulaOS with Tauri to load your library.");
    return;
  }

  try {
    const games = await invoke("list_library_games");
    if (!Array.isArray(games) || games.length === 0) {
      setEmptyHomeState(view, "Open Library and scan your device to populate Home.");
      return;
    }

    const sortedGames = [...games].sort((left, right) => {
      if (left.userFavourite !== right.userFavourite) {
        return left.userFavourite ? -1 : 1;
      }
      return gameTitle(left).localeCompare(gameTitle(right));
    });

    renderHeroGame(view, sortedGames[0], convertFileSrc);
    renderQuickLaunch(view, sortedGames.slice(0, 6), convertFileSrc);
    renderFeatured(view, sortedGames.slice(0, 4), convertFileSrc);
    renderActivity(view, sortedGames);
  } catch (error) {
    setEmptyHomeState(view, String(error));
  }
};

const setEmptyHomeState = (view, message) => {
  view.querySelector("[data-hero-title]").textContent = "No games scanned yet";
  view.querySelector("[data-hero-meta]").textContent = message;
  view.querySelector("[data-home-library-count]").textContent = "0 Games";
  view.querySelector("[data-home-activity-hint]").textContent = "Scan from Library to populate Home.";
};

const renderHeroGame = (view, game, convertFileSrc) => {
  const title = gameTitle(game);
  const hero = view.querySelector("[data-home-hero]");
  const heroArt = view.querySelector("[data-hero-art]");
  const titleNode = view.querySelector("[data-hero-title]");
  const metaNode = view.querySelector("[data-hero-meta]");
  const watermark = view.querySelector("[data-hero-watermark]");
  const imageUrl = gameArtUrl(game, convertFileSrc, "heroImage");

  hero?.setAttribute("aria-label", `Featured game: ${title}`);
  titleNode.textContent = title;
  metaNode.textContent = `${sourceLabel(game.platformSource)} · ${game.metadataStatus === "needs_review" ? "Needs review" : "Ready"}`;
  watermark.textContent = title.toUpperCase();

  if (imageUrl) {
    heroArt.style.setProperty("--hero-image", `url("${imageUrl}")`);
    heroArt.classList.add("has-image");
  } else {
    heroArt.style.removeProperty("--hero-image");
    heroArt.classList.remove("has-image");
  }
};

const renderQuickLaunch = (view, games, convertFileSrc) => {
  view.querySelectorAll("[data-quick-slot]").forEach((tile, index) => {
    const game = games[index];
    const art = tile.querySelector(".quick-tile-art");
    const initials = tile.querySelector(".quick-tile-initials");
    const name = tile.querySelector(".quick-tile-name");
    const meta = tile.querySelector(".quick-tile-meta");

    if (!game) {
      tile.removeAttribute("data-game-id");
      tile.setAttribute("aria-label", "Empty library slot");
      art.style.removeProperty("--quick-image");
      art.classList.remove("has-image");
      initials.textContent = "OS";
      name.textContent = "Empty Slot";
      meta.textContent = "Scan for more games";
      return;
    }

    const title = gameTitle(game);
    const imageUrl = gameArtUrl(game, convertFileSrc, "coverImage");
    tile.dataset.gameId = String(game.id);
    tile.setAttribute("aria-label", title);
    name.textContent = title;
    meta.textContent = sourceLabel(game.platformSource);
    initials.textContent = initialsForTitle(title);

    if (imageUrl) {
      art.style.setProperty("--quick-image", `url("${imageUrl}")`);
      art.classList.add("has-image");
    } else {
      art.style.removeProperty("--quick-image");
      art.classList.remove("has-image");
    }
  });
};

const renderFeatured = (view, games, convertFileSrc) => {
  view.querySelectorAll("[data-featured-slot]").forEach((tile, index) => {
    const game = games[index];
    if (!game) {
      tile.removeAttribute("data-game-id");
      tile.setAttribute("aria-label", "Empty featured slot");
      tile.style.removeProperty("--featured-image");
      tile.classList.remove("has-image");
      return;
    }

    const title = gameTitle(game);
    const imageUrl = gameArtUrl(game, convertFileSrc, "heroImage");
    tile.dataset.gameId = String(game.id);
    tile.setAttribute("aria-label", title);
    if (imageUrl) {
      tile.style.setProperty("--featured-image", `url("${imageUrl}")`);
      tile.classList.add("has-image");
    } else {
      tile.style.removeProperty("--featured-image");
      tile.classList.remove("has-image");
    }
  });
};

const renderActivity = (view, games) => {
  const count = games.length;
  view.querySelector("[data-home-library-count]").textContent = `${count} ${count === 1 ? "Game" : "Games"}`;
  view.querySelector("[data-home-activity-hint]").textContent = "Home is showing your scanned local library.";
};
