import {
  NAVIGABLE_VIEWS,
  PRIMARY_NAV,
  QUICK_ACTIONS,
  RECENT_ITEMS,
  SOURCE_LABELS,
} from "./sidebarData.js";

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

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

const renderRailNav = () =>
  PRIMARY_NAV.map(
    (item, index) => `
    <li
      class="guide-rail-item focusable"
      role="listitem"
      data-sidebar-nav="${item.id}"
      data-target="${item.target}"
      data-nav-region="sidebar"
      data-focusable="true"
      data-row="${index}"
      data-col="-1"
      data-focus-key="rail-${item.id}"
      aria-label="${escapeHtml(item.label)}"
    >
      <span class="guide-rail-icon" aria-hidden="true">${item.icon}</span>
    </li>
  `,
  ).join("");

const renderPanelNav = () =>
  PRIMARY_NAV.map(
    (item, index) => `
    <li
      class="guide-nav-item focusable"
      role="listitem"
      data-sidebar-nav="${item.id}"
      data-target="${item.target}"
      data-nav-region="guide"
      data-focusable="true"
      data-row="${index}"
      data-col="0"
      data-focus-key="guide-nav-${item.id}"
    >
      <span class="guide-nav-icon" aria-hidden="true">${item.icon}</span>
      <span class="guide-nav-label">${escapeHtml(item.label)}</span>
    </li>
  `,
  ).join("");

const renderQuickActions = () =>
  QUICK_ACTIONS.map(
    (item, index) => `
    <button
      type="button"
      class="guide-quick-item focusable"
      data-guide-action="${item.id}"
      data-panel="${item.panel ?? ""}"
      data-action-type="${item.action ?? "panel"}"
      data-nav-region="guide"
      data-focusable="true"
      data-row="${PRIMARY_NAV.length + 1 + Math.floor(index / 2)}"
      data-col="${index % 2}"
      data-focus-key="guide-quick-${item.id}"
      aria-label="${escapeHtml(item.label)}"
    >
      <span class="guide-quick-icon" aria-hidden="true">${item.icon}</span>
      <span class="guide-quick-label">${escapeHtml(item.label)}</span>
    </button>
  `,
  ).join("");

const renderRecentItems = () => {
  if (!RECENT_ITEMS.length) {
    return `
      <div class="guide-recent-empty" aria-live="polite">
        <span class="guide-recent-empty-icon" aria-hidden="true">⊟</span>
        <p class="guide-recent-empty-title">No recent activity</p>
        <p class="guide-recent-empty-copy">Launch a game from your library to see it here.</p>
      </div>
    `;
  }

  return RECENT_ITEMS.map(
    (item, index) => `
    <button
      type="button"
      class="guide-recent-item focusable"
      data-recent-id="${item.id}"
      data-nav-region="guide"
      data-focusable="true"
      data-row="${PRIMARY_NAV.length + 4 + index}"
      data-col="0"
      data-focus-key="guide-recent-${item.id}"
      aria-label="${escapeHtml(item.title)}, ${escapeHtml(SOURCE_LABELS[item.source] ?? item.source)}"
    >
      <span class="guide-recent-cover" style="--recent-accent: ${item.accent}" aria-hidden="true"></span>
      <span class="guide-recent-meta">
        <span class="guide-recent-title">${escapeHtml(item.title)}</span>
        <span class="guide-recent-sub">
          <span class="guide-source-badge" data-source="${item.source}">${escapeHtml(SOURCE_LABELS[item.source] ?? item.source)}</span>
          <span class="guide-recent-time">${escapeHtml(item.lastPlayed)}</span>
        </span>
      </span>
    </button>
  `,
  ).join("");
};

const GUIDE_MARKUP = `
<aside class="guide-shell" id="guide-sidebar" aria-label="Nebula guide navigation">
  <div class="guide-rail" id="guide-rail" data-guide-rail>
    <button
      type="button"
      class="guide-rail-brand focusable"
      data-nav-region="sidebar"
      data-focusable="true"
      data-row="-1"
      data-col="-1"
      data-focus-key="rail-brand"
      data-guide-action="toggle"
      aria-label="Open Nebula guide"
      aria-expanded="false"
      aria-controls="guide-panel"
    >
      <span class="guide-brand-mark" aria-hidden="true">✦</span>
    </button>

    <ul class="guide-rail-nav" role="list">
      ${renderRailNav()}
    </ul>

    <div class="guide-rail-footer">
      <button
        type="button"
        class="guide-rail-expand focusable"
        data-guide-action="toggle"
        data-nav-region="sidebar"
        data-focusable="true"
        data-row="99"
        data-col="-1"
        data-focus-key="rail-expand"
        aria-label="Open guide panel"
      >
        <span class="guide-rail-expand-icon" aria-hidden="true">☰</span>
      </button>
      <button
        type="button"
        class="guide-rail-profile focusable"
        data-guide-action="profile"
        data-nav-region="sidebar"
        data-focusable="true"
        data-row="100"
        data-col="-1"
        data-focus-key="rail-profile"
        aria-label="Profile"
      >
        <span class="guide-rail-avatar" data-profile-avatar aria-hidden="true"></span>
      </button>
    </div>
  </div>

  <div
    class="guide-panel"
    id="guide-panel"
    role="dialog"
    aria-modal="true"
    aria-label="Nebula guide"
    aria-hidden="true"
    hidden
  >
    <div class="guide-panel-inner" data-guide-focus-root>
      <header class="guide-header">
        <div class="guide-profile">
          <span class="guide-profile-avatar" data-profile-avatar aria-hidden="true"></span>
          <div class="guide-profile-copy">
            <p class="guide-profile-name" data-profile-name>Nebula User</p>
            <p class="guide-profile-status">
              <span class="guide-status-dot" aria-hidden="true"></span>
              <span data-profile-status>Online</span>
            </p>
          </div>
        </div>
        <div class="guide-header-meta">
          <p class="guide-header-time" data-clock>--:--</p>
          <p class="guide-header-date" data-date></p>
          <div class="guide-header-indicators" aria-label="System status">
            <span class="guide-indicator" title="Network connected" aria-hidden="true">◉</span>
            <span class="guide-indicator" title="Controller ready" aria-hidden="true">🎮</span>
          </div>
        </div>
        <p class="guide-header-brand">
          <span class="guide-header-brand-mark" aria-hidden="true">✦</span>
          Nebula OS
        </p>
      </header>

      <hr class="guide-divider" />

      <section class="guide-section" aria-labelledby="guide-nav-heading">
        <h2 class="guide-section-title" id="guide-nav-heading">Navigate</h2>
        <ul class="guide-nav-list" role="list">
          ${renderPanelNav()}
        </ul>
      </section>

      <hr class="guide-divider" />

      <section class="guide-section" aria-labelledby="guide-quick-heading">
        <h2 class="guide-section-title" id="guide-quick-heading">Quick actions</h2>
        <div class="guide-quick-grid">
          ${renderQuickActions()}
        </div>
      </section>

      <hr class="guide-divider" />

      <section class="guide-section guide-section-recent" aria-labelledby="guide-recent-heading">
        <h2 class="guide-section-title" id="guide-recent-heading">Recent</h2>
        <div class="guide-recent-list">
          ${renderRecentItems()}
        </div>
      </section>

      <footer class="guide-footer">
        <button
          type="button"
          class="guide-footer-btn focusable"
          data-guide-action="profile"
          data-nav-region="guide"
          data-focusable="true"
          data-row="200"
          data-col="0"
          data-focus-key="guide-footer-profile"
          aria-label="Profile"
        >
          <span class="guide-footer-avatar" data-profile-avatar aria-hidden="true"></span>
          <span>Profile</span>
        </button>
        <button
          type="button"
          class="guide-footer-btn focusable"
          data-target="settings"
          data-nav-region="guide"
          data-focusable="true"
          data-row="200"
          data-col="1"
          data-focus-key="guide-footer-settings"
        >
          <span aria-hidden="true">⚙</span>
          <span>Settings</span>
        </button>
        <button
          type="button"
          class="guide-footer-btn focusable"
          data-guide-action="power"
          data-nav-region="guide"
          data-focusable="true"
          data-row="200"
          data-col="2"
          data-focus-key="guide-footer-power"
        >
          <span aria-hidden="true">⏻</span>
          <span>Power</span>
        </button>
        <p class="guide-version" data-guide-version>NebulaOS · Shell Preview</p>
      </footer>
    </div>
  </div>
</aside>
`;

export const createGuideSidebar = ({
  state,
  renderView,
  openPowerMenu,
  openGuidePanel,
  onGuideChange,
}) => {
  let shellEl = null;
  let backdropEl = null;
  let panelEl = null;
  let expanded = false;
  let lastFocusedKey = null;

  const syncProfile = () => {
    if (!shellEl) return;
    const name = state.profileName || "Nebula User";
    const initials = initialsFor(name);
    shellEl.querySelectorAll("[data-profile-name]").forEach((el) => {
      el.textContent = name;
    });
    shellEl.querySelectorAll("[data-profile-avatar], .guide-rail-avatar, .guide-footer-avatar").forEach((el) => {
      el.textContent = initials;
      el.setAttribute("aria-label", name);
    });
  };

  const setExpanded = (next) => {
    expanded = next;
    document.body.classList.toggle("guide-expanded", expanded);

    if (panelEl) {
      panelEl.hidden = !expanded;
      panelEl.setAttribute("aria-hidden", expanded ? "false" : "true");
    }

    if (backdropEl) {
      backdropEl.hidden = !expanded;
    }

    shellEl?.querySelectorAll("[data-guide-action='toggle'], .guide-rail-brand").forEach((btn) => {
      btn.setAttribute("aria-expanded", expanded ? "true" : "false");
    });

    onGuideChange?.({ expanded });
  };

  const open = () => {
    if (expanded) return;
    const focused = document.querySelector(".is-focused");
    lastFocusedKey = focused?.dataset?.focusKey ?? null;
    setExpanded(true);
    window.dispatchEvent(new CustomEvent("nebula-guide-open"));
  };

  const close = () => {
    if (!expanded) return;
    setExpanded(false);
    window.dispatchEvent(
      new CustomEvent("nebula-guide-close", {
        detail: { focusKey: lastFocusedKey },
      }),
    );
  };

  const toggle = () => {
    if (expanded) {
      close();
    } else {
      open();
    }
  };

  const navigateTo = (target) => {
    if (!target || !NAVIGABLE_VIEWS.has(target)) {
      return false;
    }
    close();
    renderView(target);
    return true;
  };

  const handleGuideAction = (element) => {
    const action = element?.dataset?.guideAction;
    if (action === "toggle") {
      toggle();
      return true;
    }
    if (action === "power") {
      close();
      openPowerMenu?.();
      return true;
    }
    if (action === "profile") {
      console.log("[Guide] Profile panel (placeholder)");
      return true;
    }

    const panel = element?.dataset?.panel;
    if (panel) {
      close();
      openGuidePanel?.(panel);
      return true;
    }

    return false;
  };

  const handleAccept = (focused) => {
    if (!focused) return false;

    const target = focused.dataset.target;
    if (target && focused.dataset.navRegion) {
      return navigateTo(target);
    }

    if (focused.dataset.recentId) {
      console.log(`[Guide] Recent item: ${focused.dataset.recentId}`);
      return true;
    }

    return handleGuideAction(focused);
  };

  const updateActiveView = (viewId) => {
    if (!shellEl) return;
    shellEl.querySelectorAll("[data-sidebar-nav]").forEach((item) => {
      const matches = item.dataset.sidebarNav === viewId;
      item.classList.toggle("is-active", matches);
      if (matches) {
        item.setAttribute("aria-current", "page");
      } else {
        item.removeAttribute("aria-current");
      }
    });
  };

  const bindPointer = () => {
    shellEl?.addEventListener("click", (event) => {
      const item = event.target.closest("[data-focusable='true']");
      if (!item || item.dataset.disabled === "true") return;

      if (item.dataset.guideAction === "toggle" && !expanded) {
        open();
        return;
      }

      if (item.dataset.target || item.dataset.guideAction || item.dataset.recentId || item.dataset.panel) {
        handleAccept(item);
        window.dispatchEvent(
          new CustomEvent("nebula-navigation-refresh", {
            detail: { focusKey: item.dataset.focusKey },
          }),
        );
      }
    });

    backdropEl?.addEventListener("click", () => close());
  };

  const mount = ({ shellRoot, backdropRoot }) => {
    shellRoot.innerHTML = GUIDE_MARKUP;
    shellEl = shellRoot.querySelector("#guide-sidebar") ?? shellRoot;
    panelEl = shellRoot.querySelector("#guide-panel");
    backdropEl = backdropRoot;
    syncProfile();
    bindPointer();
    setExpanded(false);
  };

  const getFocusRoots = () => {
    if (!shellEl || document.body.classList.contains("body-no-sidebar")) {
      return [];
    }
    if (expanded) {
      const root = shellEl.querySelector("[data-guide-focus-root]");
      return root ? [root] : [];
    }
    const rail = shellEl.querySelector("[data-guide-rail]");
    return rail ? [rail] : [];
  };

  return {
    mount,
    open,
    close,
    toggle,
    isExpanded: () => expanded,
    updateActiveView,
    getFocusRoots,
    handleAccept,
    syncProfile,
  };
};
