<script lang="ts">
  import { onMount, createEventDispatcher } from 'svelte';
  import { marked } from 'marked';
  import { fetchNav, fetchModule, submitFeedback } from '../lib/api';
  import type { NavApp, ModuleView } from '../lib/api';
  import { addToast } from '../lib/stores';

  const dispatch = createEventDispatcher();
  export let userEmail = '';
  export let userRole = '';

  let nav: NavApp[] = [];
  let loadingNav = true;
  let module: ModuleView | null = null;
  let loadingModule = false;
  let activeModuleKey = '';
  let activeTab = 0;
  let search = '';
  // collapse state: 'modules' | 'platform' | 'technical' | 'app:<name>'
  let open: Record<string, boolean> = { modules: true };
  function toggle(key: string) { open = { ...open, [key]: !open[key] }; }
  function expandFor(key: string) {
    const app = key.split('.')[0];
    if (app === 'platform') open = { ...open, platform: true };
    else if (app === 'devops') open = { ...open, devops: true };
    else if (app === 'technical') open = { ...open, technical: true };
    else if (app === 'processes') open = { ...open, processes: true };
    else open = { ...open, modules: true, ['app:' + app]: true };
  }

  // ── Feedback (in-guide bug/enhancement → Gitea) ──────────
  const FB_AREAS = ['fleet','devices','incident','transactions','analytics','reports','messaging',
    'claims','recon','vault','aria','msp','dashboard','profile','mobile','agent','guide'];
  let fbOpen = false;
  let fbType = 'Bug';
  let fbArea = 'guide';
  let fbTitle = '';
  let fbDescription = '';
  let fbSubmitting = false;
  let fbResult: { number: number; url: string } | null = null;
  let fbError = '';

  function openFeedback() {
    const parts = activeModuleKey.split('.');
    const app = parts[0];
    fbArea = FB_AREAS.includes(app) ? app
      : (app === 'technical' && FB_AREAS.includes(parts[1]) ? parts[1] : 'guide');
    fbType = 'Bug'; fbTitle = ''; fbDescription = ''; fbResult = null; fbError = ''; fbOpen = true;
  }
  async function sendFeedback() {
    if (!fbTitle.trim() || !fbDescription.trim()) { fbError = 'Title and description are required.'; return; }
    fbSubmitting = true; fbError = '';
    try {
      fbResult = await submitFeedback({ type: fbType, area: fbArea, title: fbTitle, description: fbDescription, module: activeModuleKey });
    } catch (e: any) {
      fbError = e?.response?.data?.error ?? e?.message ?? 'Failed to submit.';
    } finally { fbSubmitting = false; }
  }

  marked.setOptions({ gfm: true, breaks: false });
  const render = (md: string): string => marked.parse(md, { async: false }) as string;

  // pretty app label: "platform" → "Platform", "agent-proxy" → "Agent Proxy"
  const appLabel = (a: string) =>
    a.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');

  // role-tab icons (Customer / Internal / Architect / Claude)
  const ROLE_ICON: Record<string, string> = {
    Customer: '👤', Internal: '🔧', Architect: '📐', Testing: '🧪', Claude: '✨', Overview: '📄', Data: '🗄️', Technical: '📐',
  };

  $: filtered = !search.trim()
    ? nav
    : nav
        .map(a => ({
          ...a,
          modules: a.modules.filter(m =>
            (m.title + ' ' + m.module).toLowerCase().includes(search.toLowerCase())
          ),
        }))
        .filter(a => a.modules.length > 0);

  // group nav: product-app "Modules" section (all except platform/technical) + platform + technical
  $: searching = !!search.trim();
  const SPECIAL = ['platform', 'devops', 'technical', 'processes'];
  $: productApps = filtered.filter(a => !SPECIAL.includes(a.app));
  $: platformApp = filtered.find(a => a.app === 'platform') ?? null;
  $: devopsApp = filtered.find(a => a.app === 'devops') ?? null;
  $: technicalApp = filtered.find(a => a.app === 'technical') ?? null;
  $: processesApp = filtered.find(a => a.app === 'processes') ?? null;

  async function loadNav() {
    loadingNav = true;
    try {
      nav = await fetchNav();
      // auto-select the first product module (or first available)
      const first = (nav.find(a => a.app !== 'platform' && a.app !== 'technical' && a.modules.length)
        ?? nav.find(a => a.modules.length))?.modules[0];
      if (first) { expandFor(first.module); selectModule(first.module); }
    } catch (e: any) {
      addToast('error', 'Failed to load guides', e?.response?.data?.message ?? e?.message ?? '');
    } finally {
      loadingNav = false;
    }
  }

  async function selectModule(key: string) {
    if (key === activeModuleKey && module) return;
    expandFor(key);
    activeModuleKey = key;
    loadingModule = true;
    module = null;
    try {
      module = await fetchModule(key);
      activeTab = 0;
    } catch (e: any) {
      addToast('error', 'Failed to load module', e?.response?.data?.message ?? e?.message ?? '');
    } finally {
      loadingModule = false;
    }
  }

  onMount(loadNav);
</script>

<div class="reader">
  <!-- Nav sidebar -->
  <aside class="side">
    <div class="side-head">
      <img src="/hiveiq_logo.png" alt="HiveIQ" class="side-logo" />
      <span class="side-title">Guide</span>
    </div>

    <div class="side-search">
      <input type="text" placeholder="Search guides…" bind:value={search} />
    </div>

    <nav class="side-nav">
      {#if loadingNav}
        <div class="side-msg">Loading…</div>
      {:else if filtered.length === 0}
        <div class="side-msg">No guides found.</div>
      {:else}
        <!-- MODULES (product apps) -->
        {#if productApps.length}
          <div class="nav-sec">
            <button class="sec-head" on:click={() => toggle('modules')}>
              <span class="chev">{(searching || open['modules']) ? '▾' : '▸'}</span> Modules
            </button>
            {#if (searching || open['modules'])}
              {#each productApps as app (app.app)}
                <div class="nav-app">
                  <button class="app-head" on:click={() => toggle('app:' + app.app)}>
                    <span class="chev">{(searching || open['app:' + app.app]) ? '▾' : '▸'}</span> {appLabel(app.app)}
                  </button>
                  {#if (searching || open['app:' + app.app])}
                    {#each app.modules as m (m.module)}
                      <button class="nav-item nested" class:active={m.module === activeModuleKey}
                        on:click={() => selectModule(m.module)} title={m.module}>{m.title}</button>
                    {/each}
                  {/if}
                </div>
              {/each}
            {/if}
          </div>
        {/if}

        <!-- PLATFORM -->
        {#if platformApp}
          <div class="nav-sec">
            <button class="sec-head" on:click={() => toggle('platform')}>
              <span class="chev">{(searching || open['platform']) ? '▾' : '▸'}</span> Platform
            </button>
            {#if (searching || open['platform'])}
              {#each platformApp.modules as m (m.module)}
                <button class="nav-item" class:active={m.module === activeModuleKey}
                  on:click={() => selectModule(m.module)} title={m.module}>{m.title}</button>
              {/each}
            {/if}
          </div>
        {/if}

        <!-- DEVOPS -->
        {#if devopsApp}
          <div class="nav-sec">
            <button class="sec-head" on:click={() => toggle('devops')}>
              <span class="chev">{(searching || open['devops']) ? '▾' : '▸'}</span> DevOps
            </button>
            {#if (searching || open['devops'])}
              {#each devopsApp.modules as m (m.module)}
                <button class="nav-item" class:active={m.module === activeModuleKey}
                  on:click={() => selectModule(m.module)} title={m.module}>{m.title}</button>
              {/each}
            {/if}
          </div>
        {/if}

        <!-- TECHNICAL -->
        {#if technicalApp}
          <div class="nav-sec">
            <button class="sec-head" on:click={() => toggle('technical')}>
              <span class="chev">{(searching || open['technical']) ? '▾' : '▸'}</span> Technical
            </button>
            {#if (searching || open['technical'])}
              {#each technicalApp.modules as m (m.module)}
                <button class="nav-item" class:active={m.module === activeModuleKey}
                  on:click={() => selectModule(m.module)} title={m.module}>{m.title}</button>
              {/each}
            {/if}
          </div>
        {/if}

        <!-- PROCESSES (BCOS admin only — API-gated) -->
        {#if processesApp}
          <div class="nav-sec">
            <button class="sec-head" on:click={() => toggle('processes')}>
              <span class="chev">{(searching || open['processes']) ? '▾' : '▸'}</span> Processes
            </button>
            {#if (searching || open['processes'])}
              {#each processesApp.modules as m (m.module)}
                <button class="nav-item" class:active={m.module === activeModuleKey}
                  on:click={() => selectModule(m.module)} title={m.module}>{m.title}</button>
              {/each}
            {/if}
          </div>
        {/if}
      {/if}
    </nav>

    <button class="side-feedback" on:click={openFeedback}>💬 Send feedback</button>
    {#if userEmail}
      <div class="side-user">
        <span class="side-user-label">Signed in as</span>
        <span class="side-user-email" title={userEmail}>{userEmail}</span>
        {#if userRole}<span class="side-user-role">{userRole}</span>{/if}
      </div>
    {/if}
    <button class="side-logout" on:click={() => dispatch('logout')}>Sign out</button>
  </aside>

  <!-- Content -->
  <main class="content">
    {#if loadingModule}
      <div class="content-msg"><div class="spinner"></div></div>
    {:else if !module}
      <div class="content-msg">Select a guide from the left.</div>
    {:else}
      <div class="content-head">
        <div class="content-title">{module.title}</div>
        <div class="content-key">{module.module}</div>
      </div>

      {#if module.tabs.length > 1}
        <div class="tabs" role="tablist">
          {#each module.tabs as t, i}
            <button
              class="tab"
              class:active={activeTab === i}
              role="tab"
              aria-selected={activeTab === i}
              on:click={() => (activeTab = i)}
            >
              {#if ROLE_ICON[t.tab]}<span class="tab-ic">{ROLE_ICON[t.tab]}</span>{/if}
              {t.tab}
              {#if t.audience !== 'customer'}<span class="tab-int">{t.audience}</span>{/if}
            </button>
          {/each}
        </div>
      {/if}

      <div class="body">
        {#if module.tabs[activeTab]}
          {#if module.tabs[activeTab].audience === 'internal'}
            <div class="int-banner">Internal — visible to admins only</div>
          {/if}
          <div class="md">{@html render(module.tabs[activeTab].body)}</div>
        {/if}
      </div>
    {/if}
  </main>
</div>

<!-- Feedback → Gitea -->
{#if fbOpen}
  <div class="fb-overlay" on:click={() => (fbOpen = false)} role="presentation"></div>
  <div class="fb-panel" role="dialog" aria-modal="true" aria-label="Send feedback">
    <div class="fb-head">
      <span>Send feedback</span>
      <button class="fb-close" on:click={() => (fbOpen = false)} aria-label="Close">✕</button>
    </div>
    <div class="fb-body">
      {#if fbResult}
        <div class="fb-success">✅ Created <strong>#{fbResult.number}</strong> — thank you!</div>
        <a class="fb-link" href={fbResult.url} target="_blank" rel="noopener">View on Gitea →</a>
        <button class="fb-submit" on:click={() => (fbOpen = false)}>Done</button>
      {:else}
        <label class="fb-label">Type</label>
        <div class="fb-types">
          <button class="fb-type" class:active={fbType === 'Bug'} on:click={() => (fbType = 'Bug')}>🐞 Bug</button>
          <button class="fb-type" class:active={fbType === 'Enhancement'} on:click={() => (fbType = 'Enhancement')}>✨ Enhancement</button>
        </div>
        <label class="fb-label" for="fb-area">Area</label>
        <select id="fb-area" class="fb-input" bind:value={fbArea}>
          {#each FB_AREAS as a}<option value={a}>{a}</option>{/each}
        </select>
        <label class="fb-label" for="fb-title">Title</label>
        <input id="fb-title" class="fb-input" bind:value={fbTitle} placeholder="Short summary" />
        <label class="fb-label" for="fb-desc">Description</label>
        <textarea id="fb-desc" class="fb-input" rows="6" bind:value={fbDescription}
          placeholder="What happened / what you'd like — steps, page, account used…"></textarea>
        {#if fbError}<div class="fb-error">{fbError}</div>{/if}
        <button class="fb-submit" disabled={fbSubmitting} on:click={sendFeedback}>
          {fbSubmitting ? 'Sending…' : `Submit ${fbType}`}
        </button>
        {#if activeModuleKey}<div class="fb-ctx">Filed against <code>{fbArea}</code> · from <code>{activeModuleKey}</code></div>{/if}
      {/if}
    </div>
  </div>
{/if}

<style>
  .reader { display: flex; height: 100vh; overflow: hidden; font-size: 14px; }

  /* ── Sidebar ─────────────────────────────────────────── */
  .side {
    width: 264px; min-width: 264px;
    background: linear-gradient(180deg, #081651 0%, #1c49b8 100%);
    display: flex; flex-direction: column;
    box-shadow: 2px 0 8px rgba(0,0,0,0.1);
  }
  .side-head { display: flex; align-items: center; gap: 0.6rem; padding: 1.25rem 1.25rem 0.75rem; }
  .side-logo { height: 26px; width: auto; filter: brightness(0) invert(1); }
  .side-title { color: white; font-weight: 700; font-size: 1.05rem; letter-spacing: 0.3px; }

  .side-search { padding: 0.25rem 1rem 0.75rem; }
  .side-search input {
    width: 100%; padding: 0.45rem 0.7rem; border-radius: 6px;
    border: 1px solid rgba(255,255,255,0.2); background: rgba(255,255,255,0.12);
    color: white; font-size: 0.85rem;
  }
  .side-search input::placeholder { color: rgba(255,255,255,0.6); }
  .side-search input:focus { outline: none; border-color: rgba(255,255,255,0.5); background: rgba(255,255,255,0.18); }

  .side-nav { flex: 1; overflow-y: auto; padding: 0.25rem 0 1rem; }
  .side-msg { color: rgba(255,255,255,0.7); font-size: 0.85rem; padding: 0.75rem 1.25rem; }

  .nav-sec { margin-bottom: 0.1rem; }
  .sec-head {
    display: flex; align-items: center; gap: 0.4rem; width: 100%; text-align: left;
    background: none; border: none; cursor: pointer;
    color: rgba(255,255,255,0.9); font-size: 0.78rem; font-weight: 700;
    text-transform: uppercase; letter-spacing: 0.05em; padding: 0.6rem 1.1rem;
  }
  .sec-head:hover { background: rgba(255,255,255,0.06); }
  .app-head {
    display: flex; align-items: center; gap: 0.35rem; width: 100%; text-align: left;
    background: none; border: none; cursor: pointer;
    color: rgba(255,255,255,0.72); font-size: 0.82rem; font-weight: 600;
    padding: 0.35rem 1.1rem 0.35rem 1.5rem;
  }
  .app-head:hover { background: rgba(255,255,255,0.06); color: white; }
  .chev { font-size: 0.58rem; width: 9px; display: inline-block; color: rgba(255,255,255,0.55); flex-shrink: 0; }
  .nav-item {
    display: block; width: 100%; text-align: left;
    background: none; border: none; border-left: 3px solid transparent;
    color: rgba(255,255,255,0.82); font-size: 0.85rem;
    padding: 0.4rem 1.25rem 0.4rem 1.5rem; cursor: pointer;
  }
  .nav-item.nested { padding-left: 2.5rem; }
  .nav-item:hover { background: rgba(255,255,255,0.08); color: white; }
  .nav-item.active { background: rgba(255,255,255,0.14); color: white; border-left-color: white; font-weight: 600; }

  .side-user {
    margin: 0.4rem 1rem 0.2rem; padding: 0.5rem 0.15rem 0.4rem;
    border-top: 1px solid rgba(255,255,255,0.12);
    display: flex; flex-direction: column; gap: 1px;
  }
  .side-user-label { color: rgba(255,255,255,0.5); font-size: 0.62rem; text-transform: uppercase; letter-spacing: 0.05em; }
  .side-user-email { color: rgba(255,255,255,0.92); font-size: 0.78rem; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .side-user-role {
    align-self: flex-start; margin-top: 3px;
    color: #93c5fd; background: rgba(59,130,246,0.18); border: 1px solid rgba(59,130,246,0.35);
    font-size: 0.6rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em;
    border-radius: 4px; padding: 1px 6px;
  }
  .side-logout {
    margin: 0.5rem 1rem 1rem; padding: 0.5rem; border-radius: 6px;
    background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.2);
    color: white; font-size: 0.82rem; cursor: pointer;
  }
  .side-logout:hover { background: rgba(255,255,255,0.2); }

  .side-feedback {
    margin: 0.75rem 1rem 0; padding: 0.5rem; border-radius: 6px;
    background: rgba(59,130,246,0.2); border: 1px solid rgba(59,130,246,0.4);
    color: #bfdbfe; font-size: 0.82rem; font-weight: 600; cursor: pointer;
  }
  .side-feedback:hover { background: rgba(59,130,246,0.32); color: #fff; }

  /* Feedback panel */
  .fb-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.45); z-index: 1000; cursor: pointer; }
  .fb-panel {
    position: fixed; top: 0; right: 0; width: 420px; max-width: 92vw; height: 100vh;
    background: #111827; border-left: 1px solid #1e293b; z-index: 1001;
    display: flex; flex-direction: column; box-shadow: -6px 0 24px rgba(0,0,0,0.4);
    animation: fbIn 0.22s ease;
  }
  @keyframes fbIn { from { transform: translateX(100%); } to { transform: translateX(0); } }
  .fb-head {
    background: linear-gradient(180deg, #081651 0%, #1c49b8 100%);
    padding: 1rem 1.25rem; display: flex; align-items: center; justify-content: space-between;
    color: white; font-weight: 700; flex-shrink: 0;
  }
  .fb-close { background: rgba(255,255,255,0.15); border: none; color: white; width: 28px; height: 28px; border-radius: 6px; cursor: pointer; }
  .fb-close:hover { background: rgba(255,255,255,0.3); }
  .fb-body { flex: 1; overflow-y: auto; padding: 1.25rem; display: flex; flex-direction: column; gap: 0.3rem; }
  .fb-label { color: #94a3b8; font-size: 0.72rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; margin-top: 0.6rem; }
  .fb-types { display: flex; gap: 0.5rem; }
  .fb-type { flex: 1; padding: 0.5rem; border-radius: 6px; border: 1px solid #334155; background: #0f172a; color: #cbd5e1; font-size: 0.85rem; font-weight: 600; cursor: pointer; }
  .fb-type:hover { border-color: #3b82f6; }
  .fb-type.active { background: #1e3a5f; border-color: #3b82f6; color: #bfdbfe; }
  .fb-input { padding: 0.5rem 0.65rem; border-radius: 6px; border: 1px solid #334155; background: #0f172a; color: #e2e8f0; font-size: 0.85rem; font-family: inherit; width: 100%; box-sizing: border-box; }
  .fb-input:focus { outline: none; border-color: #3b82f6; }
  textarea.fb-input { resize: vertical; }
  .fb-error { background: #3b1a1a; border: 1px solid #7f1d1d; color: #fca5a5; font-size: 0.8rem; border-radius: 6px; padding: 0.5rem 0.65rem; margin-top: 0.5rem; }
  .fb-success { color: #86efac; font-size: 0.95rem; margin-bottom: 0.3rem; }
  .fb-link { color: #60a5fa; font-size: 0.85rem; text-decoration: none; }
  .fb-link:hover { text-decoration: underline; }
  .fb-submit { margin-top: 1rem; padding: 0.6rem; border-radius: 6px; border: none; background: #2563eb; color: white; font-size: 0.88rem; font-weight: 600; cursor: pointer; }
  .fb-submit:hover { background: #1d4ed8; }
  .fb-submit:disabled { opacity: 0.6; cursor: default; }
  .fb-ctx { color: #64748b; font-size: 0.72rem; margin-top: 0.6rem; }
  .fb-ctx code { color: #94a3b8; }

  /* ── Content ─────────────────────────────────────────── */
  .content { flex: 1; display: flex; flex-direction: column; overflow: hidden; background: #0b1220; }
  .content-msg { flex: 1; display: flex; align-items: center; justify-content: center; color: #94a3b8; }
  .spinner { width: 32px; height: 32px; border: 3px solid #e5e7eb; border-top-color: #2563eb; border-radius: 50%; animation: spin 0.7s linear infinite; }
  @keyframes spin { to { transform: rotate(360deg); } }

  .content-head {
    background: linear-gradient(180deg, #081651 0%, #1c49b8 100%);
    padding: 1.1rem 1.75rem; flex-shrink: 0;
  }
  .content-title { color: white; font-size: 1.3rem; font-weight: 700; }
  .content-key { color: rgba(255,255,255,0.6); font-size: 0.78rem; margin-top: 2px; font-family: ui-monospace, monospace; }

  .tabs { display: flex; gap: 2px; padding: 0 1.5rem; background: #0f172a; border-bottom: 1px solid #1e293b; flex-shrink: 0; overflow-x: auto; }
  .tab { background: transparent; border: none; border-bottom: 2px solid transparent; padding: 0.65rem 1rem; font-size: 0.85rem; font-weight: 600; color: #94a3b8; cursor: pointer; white-space: nowrap; display: flex; align-items: center; gap: 0.4rem; }
  .tab:hover { color: #e2e8f0; }
  .tab.active { color: #93c5fd; border-bottom-color: #3b82f6; }
  .tab-ic { font-size: 0.9rem; line-height: 1; }
  .tab-int { font-size: 0.62rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; color: #fcd34d; background: #422006; border: 1px solid #854d0e; border-radius: 4px; padding: 1px 4px; }

  .body { flex: 1; overflow-y: auto; padding: 1.5rem 1.75rem 3rem; }
  .int-banner { background: #422006; border: 1px solid #854d0e; color: #fcd34d; font-size: 0.8rem; border-radius: 6px; padding: 0.5rem 0.75rem; margin-bottom: 1rem; }

  .md { max-width: none; color: #cbd5e1; line-height: 1.6; }
  .md :global(h1), .md :global(h2), .md :global(h3) { color: #f1f5f9; font-weight: 700; line-height: 1.3; margin: 1.4rem 0 0.6rem; }
  .md :global(h1) { font-size: 1.4rem; }
  .md :global(h2) { font-size: 1.15rem; border-bottom: 1px solid #1e293b; padding-bottom: 0.3rem; }
  .md :global(h3) { font-size: 1rem; }
  .md :global(p) { margin: 0.5rem 0; }
  .md :global(ul), .md :global(ol) { margin: 0.5rem 0; padding-left: 1.4rem; }
  .md :global(li) { margin: 0.25rem 0; }
  .md :global(strong) { color: #f1f5f9; }
  .md :global(a) { color: #60a5fa; text-decoration: none; }
  .md :global(a:hover) { text-decoration: underline; }
  .md :global(code) { background: #1e293b; border: 1px solid #334155; border-radius: 4px; padding: 0.05rem 0.3rem; font-size: 0.85em; font-family: ui-monospace, monospace; color: #e2e8f0; }
  .md :global(pre) { background: #020617; border: 1px solid #1e293b; color: #e2e8f0; border-radius: 8px; padding: 0.9rem 1rem; overflow-x: auto; }
  .md :global(pre code) { background: none; border: none; color: inherit; padding: 0; }
  .md :global(blockquote) { border-left: 3px solid #3b82f6; margin: 0.75rem 0; padding: 0.4rem 0 0.4rem 0.9rem; color: #94a3b8; background: #131c2e; }
  .md :global(table) { width: 100%; border-collapse: collapse; margin: 0.75rem 0; font-size: 0.85rem; }
  .md :global(th), .md :global(td) { border: 1px solid #1e293b; padding: 0.4rem 0.6rem; text-align: left; }
  .md :global(th) { background: #0f172a; font-weight: 600; color: #cbd5e1; }
  .md :global(hr) { border: none; border-top: 1px solid #1e293b; margin: 1.25rem 0; }
</style>
