'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import {
  ChevronDown,
  LogIn, Settings, Users, BarChart3, Wallet, Package,
  ShoppingCart, UserCheck, Factory, Shield, Brain, Eye,
  Monitor, ToggleLeft, Network, Boxes, FileText, Zap,
  MessageSquare, Bot, Crown, Lock, History, RefreshCw,
  Terminal, TestTube, FileCode, GitBranch, Cpu,
  DollarSign, CreditCard, Receipt, PiggyBank,
  Truck, ClipboardList,
  Store, Printer,
  Target, Phone, Mail,
  Hammer, Play, Download, Upload,
  AlertTriangle, CheckCircle, Key, Database,
  Calendar, Clock, Archive,
} from 'lucide-react';

/* ------------------------------------------------------------------ */
/*  Chapter accordion component                                       */
/* ------------------------------------------------------------------ */

function Chapter({
  id,
  number,
  title,
  icon: Icon,
  color,
  children,
}: {
  id: string;
  number: number;
  title: string;
  icon: React.ElementType;
  color: string;
  children: React.ReactNode;
}) {
  const [open, setOpen] = useState(false);

  React.useEffect(() => {
    if (typeof window !== 'undefined' && window.location.hash === `#${id}`) {
      setOpen(true);
    }
  }, [id]);

  return (
    <section id={id} className="scroll-mt-28 mb-6">
      <button
        onClick={() => {
          setOpen(!open);
          const el = document.getElementById(id);
          if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }}
        aria-expanded={open}
        className="w-full flex items-center gap-4 p-6 bg-slate-800/80 border border-slate-700 rounded-2xl hover:border-brand-deep/50 transition-all text-left group"
      >
        <div
          className={`flex-shrink-0 w-14 h-14 rounded-xl bg-gradient-to-br ${color} flex items-center justify-center`}
        >
          <Icon className="w-7 h-7 text-white" />
        </div>
        <div className="flex-1 min-w-0">
          <div className="text-xs text-gray-500 uppercase tracking-widest mb-1">
            Chapter {number}
          </div>
          <h2 className="text-xl md:text-2xl font-bold text-white group-hover:text-brand transition-colors">
            {title}
          </h2>
        </div>
        <ChevronDown
          className={`w-6 h-6 text-gray-400 transition-transform duration-300 ${
            open ? 'rotate-180' : ''
          }`}
        />
      </button>

      {open && (
        <div className="mt-2 bg-slate-800/50 border border-slate-700/60 rounded-2xl p-6 md:p-8 space-y-8 text-gray-300 leading-relaxed">
          {children}
        </div>
      )}
    </section>
  );
}

/* ------------------------------------------------------------------ */
/*  Reusable sub-section heading                                      */
/* ------------------------------------------------------------------ */

function SubSection({
  icon: Icon,
  title,
  children,
}: {
  icon: React.ElementType;
  title: string;
  children: React.ReactNode;
}) {
  return (
    <div>
      <div className="flex items-center gap-2 mb-3">
        <Icon className="w-5 h-5 text-brand" />
        <h3 className="text-lg font-semibold text-white">{title}</h3>
      </div>
      <div className="space-y-3 pl-7">{children}</div>
    </div>
  );
}

/* helper for a quick-reference field table */
function FieldTable({ rows }: { rows: [string, string][] }) {
  return (
    <div className="overflow-x-auto">
      <table className="w-full text-sm border-collapse">
        <thead>
          <tr className="border-b border-white/10">
            <th className="text-left py-2 pr-4 text-gray-400 font-medium">Field / Control</th>
            <th className="text-left py-2 text-gray-400 font-medium">Description</th>
          </tr>
        </thead>
        <tbody>
          {rows.map(([field, desc]) => (
            <tr key={field} className="border-b border-white/5">
              <td className="py-2 pr-4 text-white font-medium whitespace-nowrap">{field}</td>
              <td className="py-2 text-gray-400">{desc}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Main export                                                       */
/* ------------------------------------------------------------------ */

export function UserManualContent() {
  return (
    <div>
      {/* ============================================================ */}
      {/*  CHAPTER 1 — GETTING STARTED                                 */}
      {/* ============================================================ */}
      <Chapter id="ch1" number={1} title="Getting Started" icon={LogIn} color="from-brand-deep to-blue-500">
        <SubSection icon={Monitor} title="What Is Hearth Control?">
          <p>
            Ghost Control is the unified command center for the entire Foundry Familiars
            platform. Think of it as the cockpit of an aircraft — a single interface that
            surfaces every operational module, every AI agent, every report, and every
            configuration setting your organization needs. Ghost Control is where human
            operators collaborate with AI executives to run the business.
          </p>
          <p>
            The dashboard adapts to your role and tier. In <strong>Standard Mode</strong>,
            you see a clean ERP interface where agents work quietly behind the scenes —
            automating bookkeeping, monitoring inventory, processing CRM actions, and
            flagging anomalies. In <strong>GOD MODE</strong> (Enterprise tier), the dashboard
            expands to expose The Hearth, system evolution controls, micro-app
            generation, and the full self-modification engine.
          </p>
        </SubSection>

        <SubSection icon={LogIn} title="Logging In">
          <p>
            Navigate to <Link href="/ghost-control" className="text-brand hover:underline">/ghost-control</Link> on
            the site. You will be prompted for the authentication passphrase.
            Enter the passphrase provided by your account administrator and click
            &ldquo;Enter Ghost Control.&rdquo; The system stores an authentication
            token in your browser session so subsequent visits within the same
            session do not require re-entry.
          </p>
          <p>
            <strong>Tip:</strong> If you are locked out or have forgotten the passphrase,
            contact your GFS administrator. Passphrase rotation is recommended every 90 days
            for security.
          </p>
        </SubSection>

        <SubSection icon={Monitor} title="Dashboard Overview">
          <p>
            Once authenticated, you land on the <strong>Unified Dashboard</strong>. The
            top navigation bar provides links to every major area: Dashboard, Configuration,
            Operations, Agents, Reports, Autonomy, The Hearth, Heartbeat, and more.
            The dashboard itself shows:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li><strong>Active Module Count</strong> — how many ERP modules are currently enabled.</li>
            <li><strong>Agent Status Grid</strong> — a live view of every AI agent, its current task, and health indicator.</li>
            <li><strong>Recent Activity Feed</strong> — the last 20 system events (agent actions, user logins, module toggles, alerts).</li>
            <li><strong>Quick Actions</strong> — one-click shortcuts to spawn an agent, create a The Hearth project, or open the Familiar Brief.</li>
          </ul>
          <p>
            The sidebar collapses on mobile for a responsive experience. Every page inside
            Ghost Control follows the same dark-themed design language with cyan and purple
            accent gradients.
          </p>
        </SubSection>

        <SubSection icon={Crown} title="Standard Mode vs. GOD MODE">
          <p>
            Foundry Familiars ships with two tiers, each unlocking progressively more
            capability. Understanding which tier you are on determines what you see in
            Ghost Control.
          </p>
          <FieldTable
            rows={[
              ['Standard Mode', 'Full ERP automation, agent chat, reports, compliance — agents operate within guardrails and require human approval for critical actions.'],
              ['GOD MODE (Enterprise)', 'Everything in Standard plus: The Hearth access, self-modification engine, zero-friction overrides, autonomous agent evolution, and micro-app generation.'],
            ]}
          />
          <p>
            For a detailed feature-by-feature comparison, see the{' '}
            <Link href="/docs/product-tiers" className="text-brand hover:underline">Product Tiers documentation</Link>.
          </p>
        </SubSection>
      </Chapter>

      {/* ============================================================ */}
      {/*  CHAPTER 2 — CONFIGURATION CENTER                            */}
      {/* ============================================================ */}
      <Chapter id="ch2" number={2} title="Configuration Center" icon={Settings} color="from-brand-deep to-brand-secondary">
        <SubSection icon={ToggleLeft} title="Module Control">
          <p>
            The Configuration Center is your master control panel for deciding which parts
            of the platform are active. Navigate to <strong>Configuration</strong> from
            the top nav bar. The main view is the <strong>Module Control</strong> grid — a
            visual card layout of every available module.
          </p>
          <p>
            Each card displays the module name, a brief description, a status badge
            (Active / Inactive / Core), and a toggle switch. <strong>Core modules</strong>
            (GFS orchestration, Identity, Heartbeat) cannot be disabled — they form the
            nervous system the rest of the platform relies on. Optional modules (Finance,
            Inventory, CRM, POS, HR, The Hearth, etc.) can be toggled on or off at any
            time.
          </p>
          <p>
            When you toggle a module <strong>on</strong>, the system automatically:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li>Activates the corresponding AI agent (e.g., toggling Finance on activates the <em>Ledger</em> agent).</li>
            <li>Registers the module in the agent hierarchy so other agents can delegate tasks to it.</li>
            <li>Creates any required database tables or schema if they don&apos;t already exist.</li>
            <li>Adds a navigation entry under <strong>Operations</strong> for the new module.</li>
          </ul>
          <p>
            When you toggle a module <strong>off</strong>, the agent is deactivated and
            the nav entry is hidden — but <em>no data is deleted</em>. You can re-enable
            a module at any time and pick up exactly where you left off.
          </p>
        </SubSection>

        <SubSection icon={Network} title="Agent Hierarchy">
          <p>
            Below Module Control, you&apos;ll find the <strong>Agent Hierarchy</strong> view.
            This is a tree diagram showing how agents relate to one another. At the top
            is <strong>Tes</strong> (Agent CEO) — the master orchestrator. Below Tes sit
            domain executives:
          </p>
          <FieldTable
            rows={[
              ['Tes', 'Agent CEO — orchestrates all other agents, handles cross-domain requests, generates the Familiar Brief.'],
              ['Sentinel', 'Chief Compliance Officer — audit trails, guardrails, breach detection, RBAC policy enforcement.'],
              ['Ledger', 'CFO — general ledger, AP/AR, invoicing, budgets, financial analytics.'],
              ['Nexus', 'VP of Sales & CRM — leads, contacts, opportunities, sales orders, pipeline forecasting.'],
              ['Harmony', 'VP of HR — employees, leave management, time tracking, payroll integration, benefits.'],
              ['StockWatch', 'VP of Supply Chain — inventory levels, supplier management, purchase orders, reorder alerts.'],
              ['Pipeline', 'VP of Revenue Operations — order-to-cash flow, revenue recognition, billing automation.'],
              ['Conductor', 'VP of Operations — task orchestration, workflow routing, SLA monitoring.'],
              ['Milestone', 'VP of Projects — The Hearth project management, sprint tracking, deliverable sign-off.'],
            ]}
          />
          <p>
            The hierarchy is <em>dynamic</em> — when you enable or disable modules, the
            tree updates in real time. Agents that are offline appear greyed out. You can
            click any agent node to view its profile, recent activity log, and performance
            metrics.
          </p>
        </SubSection>

        <SubSection icon={Brain} title="AI & LLM Settings">
          <p>
            The Configuration Center also includes an <strong>AI Settings</strong> panel
            where administrators can adjust:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li><strong>Default LLM Model</strong> — choose which language model powers agent responses (GPT-4o, Claude, etc.).</li>
            <li><strong>Temperature</strong> — control randomness vs. determinism in agent outputs.</li>
            <li><strong>Max Tokens</strong> — set a ceiling on response length to manage costs.</li>
            <li><strong>System Prompts</strong> — view and (in GOD MODE) edit the master system prompts that define each agent&apos;s personality and behavior.</li>
          </ul>
        </SubSection>

        <SubSection icon={Database} title="Backup & Restore">
          <p>
            From Configuration you can access the <strong>Backup & Restore</strong> panel.
            Three backup types are supported:
          </p>
          <FieldTable
            rows={[
              ['Snapshot', 'A lightweight backup of module configs, agent profiles, and system settings — no transactional data.'],
              ['Full Export', 'Everything: modules, agent data, all ERP records (finance, inventory, CRM, HR), The Hearth projects, memory stores.'],
              ['Selective', 'Pick specific entity types to back up (e.g., only Finance + CRM records).'],
            ]}
          />
          <p>
            Backups can be triggered manually or scheduled (hourly, daily, weekly) via the
            <strong> Backup Schedule</strong> configuration. Each schedule has a retention
            policy — backups older than the retention window are automatically purged.
          </p>
        </SubSection>
      </Chapter>

      {/* ============================================================ */}
      {/*  CHAPTER 3 — AGENTS & CHAT                                   */}
      {/* ============================================================ */}
      <Chapter id="ch3" number={3} title="Agents & Chat" icon={Users} color="from-emerald-500 to-teal-500">
        <SubSection icon={Bot} title="Talking to Your AI Executives">
          <p>
            One of the most powerful features of Ghost Control is the ability to have a
            real-time conversation with any AI agent. Navigate to <strong>Agents</strong>
            from the top nav to see a list of all active agents. Click any agent to open
            a chat window.
          </p>
          <p>
            The chat interface supports natural language questions and commands. For example:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li>&ldquo;Ledger, show me this month&apos;s AP aging summary.&rdquo;</li>
            <li>&ldquo;Sentinel, run a compliance audit on the last 30 days of transactions.&rdquo;</li>
            <li>&ldquo;Nexus, which leads have the highest conversion probability this quarter?&rdquo;</li>
            <li>&ldquo;Tes, generate a Familiar Brief for the executive team.&rdquo;</li>
          </ul>
          <p>
            Agents can also <em>cross-delegate</em>. If you ask Tes a finance question,
            Tes routes the query to Ledger, aggregates the answer, and returns it in the
            same conversation thread. This cross-domain routing is handled transparently —
            you see who answered, and you can follow up with the specialist agent directly.
          </p>
        </SubSection>

        <SubSection icon={MessageSquare} title="Chat Features">
          <p>
            The chat panel includes several productivity features:
          </p>
          <FieldTable
            rows={[
              ['Message History', 'Scroll back through the full conversation. Messages persist across sessions via the Memory System.'],
              ['Rich Formatting', 'Agents respond with markdown — tables, bullet lists, code blocks, and highlighted metrics render inline.'],
              ['Action Cards', 'When an agent proposes an action (e.g., "create an invoice"), an action card appears with Approve / Reject buttons (Standard Mode) or auto-executes (GOD MODE).'],
              ['Attachments', 'You can upload documents (PDFs, CSVs, images) into the chat. The Perception System processes them and the agent responds with extracted data.'],
              ['Voice Input', 'Click the microphone icon to dictate a message. Speech-to-text converts it and sends it to the agent.'],
            ]}
          />
        </SubSection>

        <SubSection icon={Users} title="Agent Profiles & Spawn">
          <p>
            Each agent has a profile page showing its name, role description, capabilities,
            recent activity log, memory statistics (episodic count, semantic patterns
            extracted), and performance metrics (response time, task completion rate).
          </p>
          <p>
            In GOD MODE, you can also <strong>spawn</strong> new agents. The Agent Spawn
            interface lets you define a name, role, system prompt, and parent agent in the
            hierarchy. Spawned agents appear in the hierarchy tree immediately and begin
            accepting tasks. This is useful for creating domain-specific specialists — for
            example, a &ldquo;Compliance-Finance&rdquo; agent that sits under both Sentinel
            and Ledger.
          </p>
        </SubSection>

        <SubSection icon={Brain} title="Tes — Your AI Companion">
          <p>
            Tes (Tactical Executive Synthesizer) is the agent at the top of the hierarchy.
            Unlike other agents who specialize in a single domain, Tes is a generalist
            orchestrator. Tes can:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li>Answer questions about any part of the business by routing to the right specialist.</li>
            <li>Generate the <strong>Familiar Brief</strong> — a weekly executive summary covering every domain.</li>
            <li>Execute multi-step workflows that span departments (e.g., &ldquo;onboard a new client&rdquo; touches CRM, Finance, and HR).</li>
            <li>Learn from interactions and consolidate organizational knowledge into the Memory System.</li>
          </ul>
          <p>
            Tes also has a visual presence on the public website — cycling through themed
            costumes on the landing page and narrating the platform demo video.
          </p>
        </SubSection>
      </Chapter>

      {/* ============================================================ */}
      {/*  CHAPTER 4 — REPORTS & INTELLIGENCE                          */}
      {/* ============================================================ */}
      <Chapter id="ch4" number={4} title="Reports & Intelligence" icon={BarChart3} color="from-blue-500 to-indigo-500">
        <SubSection icon={FileText} title="The Familiar Brief">
          <p>
            The <strong>Familiar Brief</strong> is an AI-generated weekly executive
            summary produced by Tes. It pulls data from every active module —
            finance (revenue, expenses, cash flow), CRM (pipeline value, new leads),
            inventory (stock alerts, PO status), HR (headcount, leave utilization), and
            compliance (audit findings, guardrail breaches) — and distills it into a
            concise narrative with recommendations.
          </p>
          <p>
            The Brief is available from <strong>Reports &rarr; Familiar Brief</strong>
            in Ghost Control. You can also schedule it to be emailed to stakeholders
            on a recurring basis. Each Brief includes:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li><strong>Executive Summary</strong> — 2–3 paragraph overview of the week.</li>
            <li><strong>Market Intelligence</strong> — competitor alerts and industry trends (if external data feeds are connected).</li>
            <li><strong>Operations Health</strong> — tasks automated, agent accuracy, time saved, anomalies caught.</li>
            <li><strong>Proactive Fixes</strong> — issues the agents identified and resolved before they became problems.</li>
            <li><strong>Recommended Actions</strong> — what the AI suggests the human team focus on next week.</li>
          </ul>
        </SubSection>

        <SubSection icon={BarChart3} title="Custom Report Builder">
          <p>
            For ad-hoc analysis, the <strong>Custom Report Builder</strong> (Reports &rarr;
            Builder) lets you construct reports by selecting data sources, filters,
            groupings, and visualization types. The builder supports:
          </p>
          <FieldTable
            rows={[
              ['Data Sources', 'Finance transactions, CRM records, inventory movements, HR data, agent activity logs, The Hearth builds.'],
              ['Filters', 'Date range, module, agent, status, amount thresholds, custom tags.'],
              ['Groupings', 'Group by day/week/month, by agent, by module, by department, by customer.'],
              ['Visualizations', 'Tables, bar charts, line charts, pie charts, area charts, KPI cards.'],
              ['Export', 'Download as CSV, PDF, or schedule recurring email delivery.'],
            ]}
          />
          <p>
            Reports can be saved and shared with team members. Saved reports appear in
            the Reports dashboard for quick access.
          </p>
        </SubSection>

        <SubSection icon={Eye} title="KPI Dashboards">
          <p>
            Several pre-built KPI dashboards are available out of the box:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li><strong>Financial Overview</strong> — revenue, expenses, profit margin, cash position, AP/AR aging.</li>
            <li><strong>Sales Pipeline</strong> — lead count by stage, conversion rates, forecast vs. actual.</li>
            <li><strong>Inventory Health</strong> — stock levels, reorder alerts, supplier performance, COGS trends.</li>
            <li><strong>Agent Performance</strong> — tasks completed, average response time, accuracy rate, memory utilization.</li>
            <li><strong>Compliance Scorecard</strong> — guardrail breaches, audit findings, resolution time.</li>
          </ul>
        </SubSection>
      </Chapter>

      {/* ============================================================ */}
      {/*  CHAPTER 5 — FINANCE OPERATIONS                              */}
      {/* ============================================================ */}
      <Chapter id="ch5" number={5} title="Finance Operations" icon={Wallet} color="from-green-500 to-emerald-500">
        <SubSection icon={DollarSign} title="General Ledger & Chart of Accounts">
          <p>
            The Finance module is powered by the <strong>Ledger</strong> agent. Navigate to
            <strong> Operations &rarr; Finance &amp; Accounting</strong> to access it. The
            landing page shows the <strong>Chart of Accounts</strong> — a hierarchical list
            of all accounts organized by type (Assets, Liabilities, Equity, Revenue, Expenses).
          </p>
          <p>
            Each account displays its name, account number, type, current balance, and
            status (Active / Frozen). You can add new accounts, edit existing ones, or
            deactivate accounts that are no longer in use. The Ledger agent monitors
            account balances in real time and flags unusual patterns (e.g., a sudden spike
            in a specific expense category).
          </p>
        </SubSection>

        <SubSection icon={Receipt} title="Transactions & Journal Entries">
          <p>
            The <strong>Transactions</strong> tab shows every financial transaction — debits,
            credits, transfers, adjustments. Each entry includes:
          </p>
          <FieldTable
            rows={[
              ['Date', 'When the transaction occurred.'],
              ['Reference', 'Auto-generated or manual reference number for traceability.'],
              ['Account', 'Which GL account was affected.'],
              ['Debit / Credit', 'The amount and direction of the entry.'],
              ['Description', 'Free-text description of the transaction purpose.'],
              ['Agent', 'Which agent created or approved the entry (Ledger, Pipeline, or a human user).'],
              ['Status', 'Posted, Pending Approval, or Reversed.'],
            ]}
          />
          <p>
            In Standard Mode, journal entries above a configurable threshold require human
            approval before posting. In GOD MODE, the Ledger agent can auto-post within
            pre-defined guardrails.
          </p>
        </SubSection>

        <SubSection icon={PiggyBank} title="Budgets & Forecasting">
          <p>
            The <strong>Budgets</strong> tab lets you create annual or quarterly budgets
            by department or account category. The budget view shows:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li><strong>Budgeted Amount</strong> — the planned spend for the period.</li>
            <li><strong>Actual Spend</strong> — real-time actuals pulled from the GL.</li>
            <li><strong>Variance</strong> — the difference, highlighted in green (under budget) or red (over budget).</li>
            <li><strong>Forecast</strong> — the Ledger agent&apos;s projection for the remainder of the period based on current run rate and historical patterns.</li>
          </ul>
          <p>
            Budget alerts can be configured to notify you (or trigger an agent action)
            when spend exceeds a percentage threshold of the budgeted amount.
          </p>
        </SubSection>

        <SubSection icon={CreditCard} title="Invoicing, AP & AR">
          <p>
            Accounts Payable and Accounts Receivable workflows live under
            <strong> Finance &rarr; Transactions</strong>. Key workflows include:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li><strong>Invoice Creation</strong> — generate invoices from CRM sales orders or manually. Invoices auto-assign a GL entry.</li>
            <li><strong>Payment Tracking</strong> — mark invoices as paid, partially paid, or overdue. The Ledger agent sends overdue reminders.</li>
            <li><strong>Vendor Bills</strong> — record incoming bills, schedule payments, and match against purchase orders.</li>
            <li><strong>Reconciliation</strong> — the agent flags discrepancies between expected and actual payments.</li>
          </ul>
        </SubSection>
      </Chapter>

      {/* ============================================================ */}
      {/*  CHAPTER 6 — INVENTORY & SUPPLY CHAIN                        */}
      {/* ============================================================ */}
      <Chapter id="ch6" number={6} title="Inventory & Supply Chain" icon={Package} color="from-orange-500 to-amber-500">
        <SubSection icon={Package} title="Product Catalog">
          <p>
            Navigate to <strong>Operations &rarr; Inventory &amp; Supply Chain</strong>.
            The <strong>Products</strong> tab shows your entire product catalog — name,
            SKU, category, unit cost, selling price, current stock level, and reorder
            point. You can add products individually or import via CSV.
          </p>
          <p>
            The <strong>StockWatch</strong> agent continuously monitors stock levels. When
            a product drops below its reorder point, StockWatch can:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li>Send an alert to the dashboard.</li>
            <li>Automatically generate a purchase order draft (Standard Mode: requires approval; GOD MODE: auto-submits).</li>
            <li>Notify the assigned supplier via email.</li>
          </ul>
        </SubSection>

        <SubSection icon={Truck} title="Suppliers & Purchase Orders">
          <p>
            The <strong>Suppliers</strong> tab maintains your vendor directory — company
            name, contact info, lead time, payment terms, and performance rating. The
            <strong> Purchase Orders</strong> tab tracks all POs from draft through
            received. Each PO shows line items, quantities, expected delivery date,
            and status (Draft, Submitted, Partially Received, Received, Cancelled).
          </p>
          <p>
            StockWatch tracks supplier reliability over time and factors lead-time
            variability into reorder calculations. If a supplier consistently delivers
            late, the agent adjusts reorder points upward and flags the supplier for
            review.
          </p>
        </SubSection>

        <SubSection icon={ClipboardList} title="Stock Movements & Adjustments">
          <p>
            Every change to inventory — receiving goods, shipping orders, internal
            transfers, waste/shrinkage adjustments — is recorded as a
            <strong> stock movement</strong>. The movement log provides full traceability:
            what moved, how much, who/which agent authorized it, and the resulting
            balance.
          </p>
          <p>
            Manual adjustments (e.g., stocktake corrections) require a reason code.
            Sentinel monitors adjustment patterns and flags unusual activity — for
            example, repeated downward adjustments on the same product may indicate
            shrinkage or theft.
          </p>
        </SubSection>
      </Chapter>

      {/* ============================================================ */}
      {/*  CHAPTER 7 — POINT OF SALE (POS)                             */}
      {/* ============================================================ */}
      <Chapter id="ch7" number={7} title="Point of Sale (POS)" icon={ShoppingCart} color="from-pink-500 to-rose-500">
        <SubSection icon={Store} title="POS Overview">
          <p>
            The Point of Sale module is a full-featured register system built directly
            into Ghost Control. To enable it, go to <strong>Configuration &rarr;
            Module Control</strong> and toggle <strong>POS</strong> on. Once active,
            you&apos;ll find it under <strong>Operations &rarr; Point of Sale</strong>.
          </p>
          <p>
            POS is designed for retail, food service, and any business that processes
            in-person transactions. It integrates tightly with the Inventory and Finance
            modules — every sale automatically decrements stock and creates a GL entry.
          </p>
        </SubSection>

        <SubSection icon={Terminal} title="The Terminal">
          <p>
            The <strong>POS Terminal</strong> is a touch-optimized register interface.
            Key features include:
          </p>
          <FieldTable
            rows={[
              ['Product Grid', 'Browse products by category with large, tap-friendly tiles. Supports product images, variant selection, and quick search.'],
              ['Cart', 'Add items, adjust quantities, apply discounts (percentage or fixed), add notes (e.g., "no onions"). Running subtotal, tax, and grand total update in real time.'],
              ['Payment', 'Accept cash, card, or split payments. Record tips. Process voids and refunds. Print or email receipts.'],
              ['Hold & Recall', 'Park an order (e.g., customer forgot their wallet), serve the next customer, then recall the held order later.'],
              ['Quick Keys', 'Configurable shortcut buttons for your most popular items or combos.'],
            ]}
          />
        </SubSection>

        <SubSection icon={Printer} title="Kitchen Tickets & Multi-Printer Routing">
          <p>
            For food-service operations, the POS supports <strong>kitchen ticket
            printing</strong>. When an order is submitted, items are automatically
            routed to the correct printer/station based on category rules (e.g.,
            drinks to the bar printer, food to the kitchen printer). Ticket formatting
            is configurable — you can include order number, table number, item
            modifications, and timestamps.
          </p>
        </SubSection>

        <SubSection icon={Settings} title="POS Administration">
          <p>
            The <strong>POS Admin</strong> page lets managers:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li>Manage <strong>menu items</strong> — add/edit products, set prices, assign categories, upload images.</li>
            <li>Configure <strong>stations</strong> — define register terminals and assign them to locations.</li>
            <li>View <strong>order history</strong> — search, filter, and export all POS transactions.</li>
            <li>Run <strong>end-of-day reports</strong> — cash drawer reconciliation, sales by category, tips collected, voids/refunds.</li>
            <li>Set <strong>tax rates</strong> and <strong>service charges</strong> per location or category.</li>
          </ul>
        </SubSection>
      </Chapter>

      {/* ============================================================ */}
      {/*  CHAPTER 8 — CRM & SALES PIPELINE                            */}
      {/* ============================================================ */}
      <Chapter id="ch8" number={8} title="CRM & Sales Pipeline" icon={UserCheck} color="from-violet-500 to-orange-500">
        <SubSection icon={Target} title="Leads & Opportunities">
          <p>
            The CRM module is powered by the <strong>Nexus</strong> agent. Navigate to
            <strong> Operations &rarr; CRM</strong>. The CRM landing page shows a
            pipeline overview — total leads, qualified opportunities, deals in
            negotiation, and closed-won revenue.
          </p>
          <p>
            The <strong>Leads</strong> tab captures potential customers. Each lead record
            includes company name, contact name, email, phone, source (web form,
            referral, event, etc.), and a lead score assigned by Nexus based on
            engagement signals. Leads progress through stages: New &rarr; Contacted &rarr;
            Qualified &rarr; Converted (becomes an Opportunity) or Disqualified.
          </p>
          <p>
            <strong>Opportunities</strong> represent qualified deals. Each opportunity
            has a value, expected close date, probability, assigned rep, and stage
            (Discovery, Proposal, Negotiation, Closed-Won, Closed-Lost). Nexus monitors
            opportunities and alerts you when a deal has been stalled in a stage beyond
            the average cycle time.
          </p>
        </SubSection>

        <SubSection icon={Phone} title="Contacts & Customers">
          <p>
            The <strong>Contacts</strong> tab is your address book — every person your
            organization interacts with. Contacts link to leads, opportunities, and
            customer accounts. The <strong>Customers</strong> tab shows converted
            accounts with full transaction history, lifetime value, and associated
            sales orders.
          </p>
        </SubSection>

        <SubSection icon={Mail} title="Sales Orders">
          <p>
            When an opportunity closes, it generates a <strong>Sales Order</strong>.
            Sales orders bridge CRM and Finance — they create corresponding invoices
            in the Finance module and decrement inventory when fulfilled. Each order
            tracks line items, quantities, pricing, discounts, tax, shipping, and
            fulfillment status.
          </p>
          <p>
            The Pipeline agent manages the order-to-cash flow, ensuring that every
            closed deal results in a posted invoice and accurate revenue recognition.
          </p>
        </SubSection>
      </Chapter>

      {/* ============================================================ */}
      {/*  CHAPTER 9 — DARK FACTORY & CODE GENERATION                  */}
      {/* ============================================================ */}
      <Chapter id="ch9" number={9} title="The Hearth & Code Generation" icon={Factory} color="from-orange-500 to-pink-500">
        <SubSection icon={Play} title="What Is The Hearth?">
          <p>
            The The Hearth is Foundry Familiars&apos;s self-building software
            factory. Available in <strong>GOD MODE</strong> (Enterprise tier), it lets
            you describe what you want in plain English, choose a tech stack, and watch
            a three-agent pipeline generate production-ready code.
          </p>
          <p>
            Access The Hearth from the top nav in Ghost Control. The landing page
            shows your <strong>project list</strong> — all current and past generation
            projects with status (In Progress, Completed, Failed), creation date, and
            a link to the generated output.
          </p>
          <p>
            For full technical documentation, see the{' '}
            <Link href="/docs/dark-factory" className="text-brand hover:underline">The Hearth docs</Link>.
          </p>
        </SubSection>

        <SubSection icon={Hammer} title="Creating a Project">
          <p>
            Click <strong>New Project</strong> to start a generation. You&apos;ll provide:
          </p>
          <FieldTable
            rows={[
              ['Project Name', 'A descriptive name for the generation (e.g., "Customer Portal v2").'],
              ['Specification', 'A natural-language description of what the software should do. Be as detailed as you like — the Prompt Engineer agent refines it.'],
              ['Tech Stack', 'Choose framework (React, Next.js, Vue), database (Postgres, SQLite), styling (Tailwind, CSS Modules), and LLM backend.'],
              ['Deploy Target', 'Where the output should be deployed — internal preview, staging, or production.'],
            ]}
          />
          <p>
            Once submitted, the three-agent pipeline kicks off:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li><strong>Prompt Engineer</strong> — refines your spec into a detailed technical plan with file structure, component hierarchy, and data models.</li>
            <li><strong>UI Engineer</strong> — generates the actual code files, implementing every component, API route, and database migration.</li>
            <li><strong>QA Agent</strong> — writes and runs automated tests, checks for build errors, validates functionality, and reports results.</li>
          </ul>
        </SubSection>

        <SubSection icon={TestTube} title="Sandbox & Iteration">
          <p>
            The <strong>Sandbox</strong> provides a live preview of generated code. You
            can inspect every file, view build logs, see test results, and request
            iterations. If the QA Agent finds issues, it automatically sends the code
            back to the UI Engineer for fixes — this loop continues until all tests
            pass or a maximum iteration count is reached.
          </p>
          <p>
            You can also manually request changes from the Sandbox — for example,
            &ldquo;change the header color to purple&rdquo; or &ldquo;add a search
            bar to the products page.&rdquo; Each request triggers a new generation
            cycle through the pipeline.
          </p>
        </SubSection>

        <SubSection icon={GitBranch} title="Weft Engine">
          <p>
            Under the hood, The Hearth uses the <strong>Weft Engine</strong> — a
            template and code-generation engine that maintains consistency across
            generated files. Weft handles:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li>File scaffolding and directory structure.</li>
            <li>Component and API route boilerplate.</li>
            <li>Database schema generation and migration scripts.</li>
            <li>Import resolution and dependency management.</li>
            <li>Style system integration (design tokens, theming).</li>
          </ul>
          <p>
            For a deep technical dive, see the{' '}
            <Link href="/docs/dark-factory/weft" className="text-brand hover:underline">Weft Engine documentation</Link>.
          </p>
        </SubSection>
      </Chapter>

      {/* ============================================================ */}
      {/*  CHAPTER 10 — AUTONOMY, COMPLIANCE & ADMINISTRATION          */}
      {/* ============================================================ */}
      <Chapter id="ch10" number={10} title="Autonomy, Compliance & Administration" icon={Shield} color="from-red-500 to-orange-500">
        <SubSection icon={Shield} title="Guardrails & Approval Workflows">
          <p>
            The <strong>Autonomy</strong> page (top nav &rarr; Autonomy) is where you
            define the boundaries of what agents can do without human approval. In
            Standard Mode, guardrails are enforced by default:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li><strong>Financial Threshold</strong> — transactions above a set dollar amount require human approval before posting.</li>
            <li><strong>Data Deletion</strong> — agents cannot delete records without explicit human confirmation.</li>
            <li><strong>External Communications</strong> — emails or messages sent outside the organization require review.</li>
            <li><strong>Schema Changes</strong> — any modification to the data model requires approval.</li>
          </ul>
          <p>
            In GOD MODE, these guardrails can be relaxed or removed entirely, giving
            agents full autonomy to act without human intervention. However, even in
            GOD MODE, a <strong>circuit breaker</strong> system exists — if an agent
            takes an action that falls outside statistical norms (e.g., deleting 90%
            of records in a table), the circuit breaker trips and pauses the agent
            pending human review.
          </p>
        </SubSection>

        <SubSection icon={History} title="Audit Trails">
          <p>
            Every action taken by every agent — and every human user — is logged in
            an immutable audit trail. The audit log captures:
          </p>
          <FieldTable
            rows={[
              ['Timestamp', 'When the action occurred (UTC).'],
              ['Actor', 'Which agent or user performed the action.'],
              ['Action Type', 'CREATE, UPDATE, DELETE, APPROVE, REJECT, LOGIN, EXPORT, etc.'],
              ['Entity', 'What was affected (e.g., "Invoice #1042", "Product SKU-9001").'],
              ['Before / After', 'For updates, a diff showing the previous and new values.'],
              ['Justification', 'The agent\'s reasoning for why it took the action (auto-generated by the AI).'],
            ]}
          />
          <p>
            Audit logs are searchable and filterable. Sentinel can generate
            compliance reports from audit data — for example, &ldquo;show me all
            financial actions taken by the Ledger agent in the last 30 days that
            exceeded $10,000.&rdquo;
          </p>
        </SubSection>

        <SubSection icon={Key} title="RBAC — Role-Based Access Control">
          <p>
            The <strong>Identity &amp; Access</strong> section (accessible from
            Autonomy &rarr; Identity) lets administrators define roles, assign
            permissions, and manage user accounts. Pre-built roles include:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li><strong>Administrator</strong> — full access to everything, including Configuration and GOD MODE controls.</li>
            <li><strong>Operator</strong> — access to Operations modules, agent chat, and reports; cannot change configuration.</li>
            <li><strong>Viewer</strong> — read-only access to dashboards and reports; cannot create or modify records.</li>
            <li><strong>Auditor</strong> — access to audit trails, compliance reports, and guardrail configurations; cannot modify operational data.</li>
          </ul>
          <p>
            Custom roles can be created by combining granular permissions (e.g.,
            &ldquo;can view Finance but not CRM, can chat with agents but not
            spawn new ones&rdquo;).
          </p>
        </SubSection>

        <SubSection icon={RefreshCw} title="Self-Modification & Evolution">
          <p>
            In GOD MODE, the <strong>System Evolution</strong> engine allows agents to
            modify their own behavior over time. This includes:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li><strong>Prompt Evolution</strong> — agents refine their system prompts based on task outcomes and user feedback.</li>
            <li><strong>Capability Extension</strong> — agents can request new tools or API integrations when they encounter tasks they can&apos;t handle.</li>
            <li><strong>Memory Consolidation</strong> — the Memory System periodically distills episodic memories into semantic knowledge, making agents faster and more accurate.</li>
            <li><strong>Cross-Agent Learning</strong> — insights from one agent are shared with others via the event bus (e.g., Sentinel learning about a new compliance rule broadcasts it to all agents).</li>
          </ul>
          <p>
            All evolution events are logged in the audit trail and can be reviewed
            or rolled back by an administrator.
          </p>
        </SubSection>

        <SubSection icon={AlertTriangle} title="Heartbeat Monitoring">
          <p>
            The <strong>Heartbeat</strong> page (top nav &rarr; Heartbeat) provides a
            real-time health dashboard for the entire platform. It monitors:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li><strong>Agent Health</strong> — is each agent responsive? What&apos;s its current workload?</li>
            <li><strong>API Latency</strong> — response times for internal and external API calls.</li>
            <li><strong>Database Performance</strong> — query times, connection pool utilization, storage usage.</li>
            <li><strong>Event Bus Throughput</strong> — how many events are flowing through the system per minute.</li>
            <li><strong>Error Rate</strong> — percentage of failed operations across all modules.</li>
          </ul>
          <p>
            Heartbeat runs continuous checks at configurable intervals. If any metric
            exceeds its threshold, an alert is triggered — appearing as a notification
            in Ghost Control and optionally sent via email.
          </p>
        </SubSection>

        <SubSection icon={Archive} title="Data Management & Administration">
          <p>
            Administrative functions available to users with the Administrator role:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li><strong>Backup & Restore</strong> — create, schedule, and restore backups (see Chapter 2 for details).</li>
            <li><strong>Data Export</strong> — bulk export any module&apos;s data as CSV or JSON.</li>
            <li><strong>System Logs</strong> — raw application logs for debugging and troubleshooting.</li>
            <li><strong>Environment Settings</strong> — API keys, integration endpoints, email configuration, and LLM model selection.</li>
            <li><strong>White-Label Configuration</strong> — brand colors, company name, logo, and vocabulary can be customized for each deployment (useful for MSPs and consultancies serving multiple clients).</li>
          </ul>
        </SubSection>
      </Chapter>
    </div>
  );
}
