(function initDocsPage() {
  const diagrams = {
    workflow: `
flowchart LR
    ED["ED / Executive Director<br/>Command · Orders · Stats · Priorities"]
    D7["Division 7<br/>Policy · Admin Control · Compliance"]
    D1["Division 1<br/>Lines · Routing · Templates"]
    D2["Division 2<br/>Dissemination · Campaign Briefs · Handoffs"]
    D3["Division 3<br/>Treasury · Invoice Maker · Collections"]
    D4["Division 4<br/>Production · Assets · Staging · Scope"]
    D5["Division 5<br/>QA · Zero-Bug · Release Gates"]
    D6["Division 6<br/>Client Success · Reviews · Support · Referrals"]
    MEM["Sentient Memory + Skills"]
    AI["AI Co-Pilot"]

    ED -->|"Executive orders + battle plans"| D7
    ED -->|"Executive orders + battle plans"| D1
    ED -->|"Executive orders + battle plans"| D2
    ED -->|"Executive orders + battle plans"| D3
    ED -->|"Executive orders + battle plans"| D4
    ED -->|"Executive orders + battle plans"| D5
    ED -->|"Executive orders + battle plans"| D6

    D1 -->|"Communication flow"| D2
    D2 -->|"Demand + live workflows"| D3
    D3 -->|"Invoice + treasury cleared"| D4
    D4 -->|"Production readiness"| D5
    D5 -->|"Release gate passed"| D6
    D6 -->|"Reviews + retention + feedback"| ED

    MEM --> AI
    AI --> D7
    AI --> D1
    AI --> D2
    AI --> D3
    AI --> D4
    AI --> D5
    AI --> D6
`,
    lifecycle: `
flowchart LR
    LEAD["Lead / New Opportunity"] --> COMM["Div 1<br/>Message routing and templates"]
    COMM --> MARKET["Div 2<br/>Campaign brief, outreach, positioning"]
    MARKET --> CASH["Div 3<br/>Invoice, deposit, collections, approvals"]
    CASH --> BUILD["Div 4<br/>Assets, staging, blockers, scope control"]
    BUILD --> QA["Div 5<br/>Checks, release gates, bug control"]
    QA --> PUBLIC["Div 6<br/>Onboarding, support, reviews, referrals"]
    PUBLIC --> LOOP["Long-term value loop<br/>Retention, upsell, reputation"]
    LOOP --> EDV["ED visibility<br/>Stats, bottlenecks, command decisions"]
`,
    'ai-layer': `
flowchart TB
    SETTINGS["Business identity<br/>Owner · company · city"]
    SERVICES["Configured services<br/>Offers · pricing · ideal clients"]
    VFPS["Division VFPs + division info"]
    SKILLS["Skills library<br/>Core skills + sub-skills"]
    MEMORY["Memory logs + embeddings"]
    DATA["Live operating data<br/>Orders · workflows · metrics · invoices · QA gates"]

    SETTINGS --> CORE["AI operating context"]
    SERVICES --> CORE
    VFPS --> CORE
    SKILLS --> CORE
    MEMORY --> CORE
    DATA --> CORE

    CORE --> TASKS["Guided task generation"]
    CORE --> BPLANS["Battle plan generation"]
    CORE --> ADVISOR["Division AI advisor"]
    CORE --> SOP["SOP / skill rewriting"]
    CORE --> BRIEF["Daily briefing"]
`
  };

  function escapeHtml(value) {
    return String(value || '')
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;');
  }

  async function getJson(path) {
    const res = await fetch(path, { cache: 'no-store' });
    if (!res.ok) throw new Error(`${path} failed`);
    return res.json();
  }

  async function hydrateContext() {
    try {
      const settingsData = await getJson('/api/docs/context');
      const company = settingsData.company_name || 'Org Board AI';
      const owner = settingsData.owner_name || 'the owner';
      const city = settingsData.city || 'the current market';

      const companyNode = document.getElementById('docsCompanyName');
      const ownerNode = document.getElementById('docsOwnerLine');
      const servicesNode = document.getElementById('docsServicesList');

      if (companyNode) companyNode.textContent = company;
      if (ownerNode) ownerNode.textContent = `${owner} uses this board to run delivery, cashflow, QA, and client success from ${city}.`;

      if (!servicesNode) return;

      const services = Array.isArray(settingsData.services) ? settingsData.services : [];
      if (!services.length) {
        servicesNode.innerHTML = '<p class="docs-empty-state">No services configured yet. Once services are added, AI uses them as live business context.</p>';
        return;
      }

      servicesNode.innerHTML = services.map((service) => `
        <article class="docs-service-pill">
          <strong>${escapeHtml(service.name)}</strong>
          <span>${escapeHtml(service.description || 'Configured service context for AI and planning.')}</span>
        </article>
      `).join('');
    } catch (_error) {
      const servicesNode = document.getElementById('docsServicesList');
      if (servicesNode) {
        servicesNode.innerHTML = '<p class="docs-empty-state">Live service context could not be loaded right now, but the workflow map below still reflects the system structure.</p>';
      }
    }
  }

  async function renderDiagrams() {
    if (typeof mermaid === 'undefined') return;
    mermaid.initialize({
      startOnLoad: false,
      theme: 'base',
      securityLevel: 'loose',
      themeVariables: {
        background: '#0b1020',
        primaryColor: '#11182d',
        primaryTextColor: '#f8fbff',
        primaryBorderColor: '#6366f1',
        secondaryColor: '#10213b',
        secondaryTextColor: '#dbeafe',
        secondaryBorderColor: '#22c55e',
        tertiaryColor: '#141a2b',
        tertiaryTextColor: '#f5d0fe',
        tertiaryBorderColor: '#a855f7',
        lineColor: '#94a3b8',
        textColor: '#e2e8f0',
        clusterBkg: '#0b1020',
        clusterBorder: '#334155',
        fontFamily: 'Plus Jakarta Sans'
      },
      flowchart: {
        curve: 'basis',
        nodeSpacing: 40,
        rankSpacing: 56,
        htmlLabels: true
      }
    });

    const nodes = document.querySelectorAll('.docs-mermaid-canvas[data-diagram]');
    for (const node of nodes) {
      const source = (diagrams[node.dataset.diagram] || '').trim();
      if (!source) continue;
      try {
        const renderId = `mermaid-${node.dataset.diagram}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
        const { svg } = await mermaid.render(renderId, source);
        node.innerHTML = svg;
      } catch (error) {
        node.innerHTML = `<div class="docs-mermaid-error">Diagram failed to render.</div>`;
        console.error('Docs Mermaid render failed:', node.dataset.diagram, error);
      }
    }
  }

  function initDiagramInteractions() {
    const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
    const states = new Map();

    function getState(canvas) {
      if (!states.has(canvas)) {
        states.set(canvas, {
          zoom: 1,
          panX: 0,
          panY: 0,
          pointers: new Map(),
          dragPointerId: null,
          lastPos: null,
          pinchStart: null
        });
      }
      return states.get(canvas);
    }

    function updateResetLabel(canvas, zoom) {
      const toolbar = canvas.closest('.docs-mermaid-frame')?.querySelector('.docs-mermaid-toolbar');
      const resetBtn = toolbar?.querySelector('.docs-zoom-btn[data-zoom-action="reset"]');
      if (resetBtn) resetBtn.textContent = `${Math.round(zoom * 100)}%`;
    }

    function applyState(canvas) {
      const state = getState(canvas);
      canvas.style.setProperty('--docs-zoom', String(state.zoom));
      canvas.style.setProperty('--docs-pan-x', `${state.panX}px`);
      canvas.style.setProperty('--docs-pan-y', `${state.panY}px`);
      canvas.dataset.zoom = String(state.zoom);
      updateResetLabel(canvas, state.zoom);
    }

    function zoomAt(canvas, desiredZoom, anchorX, anchorY) {
      const state = getState(canvas);
      const nextZoom = clamp(Number(desiredZoom.toFixed(3)), 0.55, 2.8);
      const prevZoom = state.zoom;
      if (nextZoom === prevZoom) return;
      const ratio = nextZoom / prevZoom;
      state.panX = anchorX - (anchorX - state.panX) * ratio;
      state.panY = anchorY - (anchorY - state.panY) * ratio;
      state.zoom = nextZoom;
      applyState(canvas);
    }

    function resetView(canvas) {
      const state = getState(canvas);
      state.zoom = 1;
      state.panX = 0;
      state.panY = 0;
      state.pinchStart = null;
      applyState(canvas);
    }

    function pointerPoint(canvas, event) {
      const rect = canvas.getBoundingClientRect();
      return {
        x: event.clientX - rect.left,
        y: event.clientY - rect.top
      };
    }

    function distance(a, b) {
      return Math.hypot(a.x - b.x, a.y - b.y);
    }

    function midpoint(a, b) {
      return {
        x: (a.x + b.x) / 2,
        y: (a.y + b.y) / 2
      };
    }

    document.querySelectorAll('.docs-mermaid-canvas').forEach((canvas) => {
      applyState(canvas);

      canvas.addEventListener('wheel', (event) => {
        event.preventDefault();
        const point = pointerPoint(canvas, event);
        const state = getState(canvas);
        const nextZoom = state.zoom * (event.deltaY < 0 ? 1.12 : 0.9);
        zoomAt(canvas, nextZoom, point.x, point.y);
      }, { passive: false });

      canvas.addEventListener('pointerdown', (event) => {
        const state = getState(canvas);
        const point = pointerPoint(canvas, event);
        state.pointers.set(event.pointerId, point);
        canvas.setPointerCapture(event.pointerId);
        canvas.classList.add('is-dragging');

        if (state.pointers.size === 1) {
          state.dragPointerId = event.pointerId;
          state.lastPos = point;
          state.pinchStart = null;
        } else if (state.pointers.size === 2) {
          const [first, second] = [...state.pointers.values()];
          state.pinchStart = {
            distance: distance(first, second),
            zoom: state.zoom,
            panX: state.panX,
            panY: state.panY,
            midpoint: midpoint(first, second)
          };
        }
      });

      canvas.addEventListener('pointermove', (event) => {
        const state = getState(canvas);
        if (!state.pointers.has(event.pointerId)) return;
        const point = pointerPoint(canvas, event);
        state.pointers.set(event.pointerId, point);

        if (state.pointers.size === 2) {
          const [first, second] = [...state.pointers.values()];
          if (!state.pinchStart) {
            state.pinchStart = {
              distance: distance(first, second),
              zoom: state.zoom,
              panX: state.panX,
              panY: state.panY,
              midpoint: midpoint(first, second)
            };
          }
          const start = state.pinchStart;
          const currentDistance = distance(first, second);
          const currentMid = midpoint(first, second);
          const nextZoom = clamp(start.zoom * (currentDistance / start.distance), 0.55, 2.8);
          const localX = (start.midpoint.x - start.panX) / start.zoom;
          const localY = (start.midpoint.y - start.panY) / start.zoom;
          state.zoom = nextZoom;
          state.panX = currentMid.x - localX * nextZoom;
          state.panY = currentMid.y - localY * nextZoom;
          applyState(canvas);
          return;
        }

        if (state.dragPointerId === event.pointerId && state.lastPos) {
          state.panX += point.x - state.lastPos.x;
          state.panY += point.y - state.lastPos.y;
          state.lastPos = point;
          applyState(canvas);
        }
      });

      function endPointer(event) {
        const state = getState(canvas);
        state.pointers.delete(event.pointerId);
        if (state.pointers.size < 2) state.pinchStart = null;

        if (state.pointers.size === 1) {
          const [remainingId, remainingPoint] = [...state.pointers.entries()][0];
          state.dragPointerId = remainingId;
          state.lastPos = remainingPoint;
        } else {
          state.dragPointerId = null;
          state.lastPos = null;
          canvas.classList.remove('is-dragging');
        }
      }

      canvas.addEventListener('pointerup', endPointer);
      canvas.addEventListener('pointercancel', endPointer);
      canvas.addEventListener('pointerleave', (event) => {
        const state = getState(canvas);
        if (state.pointers.size <= 1 && !canvas.hasPointerCapture(event.pointerId)) {
          canvas.classList.remove('is-dragging');
        }
      });
    });

    document.querySelectorAll('.docs-zoom-btn[data-target]').forEach((button) => {
      button.addEventListener('click', () => {
        const canvas = document.getElementById(button.dataset.target);
        if (!canvas) return;
        const state = getState(canvas);
        if (button.dataset.zoomAction === 'reset') {
          resetView(canvas);
          return;
        }
        const rect = canvas.getBoundingClientRect();
        const anchorX = rect.width / 2;
        const anchorY = rect.height / 2;
        const nextZoom = button.dataset.zoomAction === 'in'
          ? state.zoom + 0.16
          : state.zoom - 0.16;
        zoomAt(canvas, nextZoom, anchorX, anchorY);
      });
    });
  }

  function initRevealSequence() {
    const nodes = document.querySelectorAll('.docs-reveal');
    if (!nodes.length) return;
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) return;
        entry.target.classList.add('is-visible');
        observer.unobserve(entry.target);
      });
    }, {
      threshold: 0.2,
      rootMargin: '0px 0px -8% 0px'
    });
    nodes.forEach((node, index) => {
      node.style.transitionDelay = `${Math.min(index * 0.05, 0.25)}s`;
      observer.observe(node);
    });
  }

  document.addEventListener('DOMContentLoaded', async () => {
    await hydrateContext();
    await renderDiagrams();
    initDiagramInteractions();
    initRevealSequence();
  });
})();
