import { mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";

const root = process.cwd();

const tones = {
  primary: { main: "var(--primary)", soft: "var(--primary-soft)" },
  success: { main: "var(--success)", soft: "var(--success-soft)" },
  warning: { main: "var(--warning)", soft: "var(--warning-soft)" },
  danger: { main: "var(--danger)", soft: "var(--danger-soft)" },
  info: { main: "var(--info)", soft: "var(--info-soft)" },
};

const customers = [
  { id: "CST-1042", name: "Aylin Demir", company: "Northstar Labs", email: "aylin@northstarlabs.io", plan: "Scale", seats: 18, status: "Active", mrr: 4800, lifetime: 38400, renewal: "2026-03-18", owner: "Deniz Kaya", location: "Istanbul, TR", health: 92, lastSeen: "12m ago" },
  { id: "CST-1048", name: "Kerem Yildiz", company: "Finloop CRM", email: "kerem@finloopcrm.com", plan: "Enterprise", seats: 46, status: "Active", mrr: 9600, lifetime: 77200, renewal: "2026-03-27", owner: "Selin Akca", location: "Berlin, DE", health: 95, lastSeen: "38m ago" },
  { id: "CST-1053", name: "Selin Aras", company: "Orbit Commerce", email: "selin@orbitcommerce.co", plan: "Growth", seats: 24, status: "Trial", mrr: 2400, lifetime: 9200, renewal: "2026-03-15", owner: "Mert Kaya", location: "London, UK", health: 81, lastSeen: "1h ago" },
  { id: "CST-1060", name: "Mert Cetin", company: "Bluepeak Ops", email: "mert@bluepeakops.io", plan: "Starter", seats: 9, status: "Active", mrr: 980, lifetime: 6040, renewal: "2026-03-22", owner: "Lara Soylu", location: "Izmir, TR", health: 88, lastSeen: "2h ago" },
  { id: "CST-1067", name: "Zeynep Akin", company: "Atlas HR", email: "zeynep@atlashr.io", plan: "Scale", seats: 31, status: "Risk", mrr: 3200, lifetime: 28600, renewal: "2026-03-16", owner: "Deniz Kaya", location: "Amsterdam, NL", health: 63, lastSeen: "4h ago" },
  { id: "CST-1075", name: "Berk Gunes", company: "NovaOps", email: "berk@novaops.co", plan: "Growth", seats: 15, status: "Paused", mrr: 1800, lifetime: 12400, renewal: "2026-04-01", owner: "Selin Akca", location: "Ankara, TR", health: 57, lastSeen: "1d ago" },
  { id: "CST-1081", name: "Elif Sahin", company: "Cloudmint", email: "elif@cloudmint.com", plan: "Scale", seats: 28, status: "Active", mrr: 5200, lifetime: 40200, renewal: "2026-03-25", owner: "Lara Soylu", location: "Paris, FR", health: 91, lastSeen: "3h ago" },
  { id: "CST-1086", name: "Can Ersoy", company: "RetailJet", email: "can@retailjet.io", plan: "Scale", seats: 34, status: "Onboarding", mrr: 4100, lifetime: 12300, renewal: "2026-04-07", owner: "Mert Kaya", location: "Madrid, ES", health: 79, lastSeen: "25m ago" },
  { id: "CST-1092", name: "Derya Alp", company: "SigmaPay", email: "derya@sigmapay.com", plan: "Enterprise", seats: 58, status: "Active", mrr: 8300, lifetime: 92100, renewal: "2026-03-29", owner: "Deniz Kaya", location: "Dubai, UAE", health: 97, lastSeen: "44m ago" },
  { id: "CST-1099", name: "Ozan Kara", company: "PulseDesk", email: "ozan@pulsedesk.io", plan: "Growth", seats: 16, status: "Renewal", mrr: 2700, lifetime: 19800, renewal: "2026-03-14", owner: "Selin Akca", location: "Boston, US", health: 72, lastSeen: "2d ago" },
];

const products = [
  { sku: "PRD-301", name: "Insight Pro Seat", category: "Analytics", price: 129, stock: 999, status: "Published", rating: 4.8, revenue: 48200, owner: "Growth Team" },
  { sku: "PRD-302", name: "CRM Workspace", category: "CRM", price: 189, stock: 999, status: "Published", rating: 4.9, revenue: 61200, owner: "Revenue Team" },
  { sku: "PRD-303", name: "Store Control", category: "Commerce", price: 159, stock: 999, status: "Published", rating: 4.7, revenue: 55400, owner: "Commerce Team" },
  { sku: "PRD-304", name: "Billing Automations", category: "Finance", price: 99, stock: 999, status: "Published", rating: 4.6, revenue: 19300, owner: "Finance Team" },
  { sku: "PRD-305", name: "Secure Access", category: "Security", price: 79, stock: 999, status: "Beta", rating: 4.3, revenue: 9200, owner: "Platform Team" },
  { sku: "PRD-306", name: "Support Portal", category: "Support", price: 109, stock: 999, status: "Published", rating: 4.5, revenue: 26700, owner: "CX Team" },
  { sku: "PRD-307", name: "Team HQ", category: "Workspace", price: 139, stock: 999, status: "Draft", rating: 4.2, revenue: 6400, owner: "Operations" },
  { sku: "PRD-308", name: "Forecast Studio", category: "Planning", price: 149, stock: 999, status: "Published", rating: 4.7, revenue: 31200, owner: "Strategy Team" },
];

const orders = [
  { id: "ORD-82011", customer: "Aylin Demir", company: "Northstar Labs", items: 4, amount: 1860, payment: "Paid", fulfillment: "Delivered", channel: "Web", date: "2026-03-11" },
  { id: "ORD-82014", customer: "Kerem Yildiz", company: "Finloop CRM", items: 8, amount: 4380, payment: "Paid", fulfillment: "Processing", channel: "Sales", date: "2026-03-11" },
  { id: "ORD-82017", customer: "Elif Sahin", company: "Cloudmint", items: 2, amount: 860, payment: "Pending", fulfillment: "Pending", channel: "Web", date: "2026-03-10" },
  { id: "ORD-82022", customer: "Derya Alp", company: "SigmaPay", items: 5, amount: 5920, payment: "Paid", fulfillment: "Delivered", channel: "Partner", date: "2026-03-10" },
  { id: "ORD-82027", customer: "Selin Aras", company: "Orbit Commerce", items: 3, amount: 1240, payment: "Refunded", fulfillment: "Returned", channel: "Web", date: "2026-03-09" },
  { id: "ORD-82030", customer: "Can Ersoy", company: "RetailJet", items: 6, amount: 2480, payment: "Paid", fulfillment: "Shipped", channel: "Inside Sales", date: "2026-03-09" },
  { id: "ORD-82035", customer: "Ozan Kara", company: "PulseDesk", items: 1, amount: 520, payment: "Pending", fulfillment: "Pending", channel: "Web", date: "2026-03-08" },
  { id: "ORD-82040", customer: "Berk Gunes", company: "NovaOps", items: 7, amount: 1740, payment: "Paid", fulfillment: "Delivered", channel: "Sales", date: "2026-03-08" },
  { id: "ORD-82044", customer: "Zeynep Akin", company: "Atlas HR", items: 3, amount: 1360, payment: "Failed", fulfillment: "Blocked", channel: "Partner", date: "2026-03-07" },
  { id: "ORD-82047", customer: "Mert Cetin", company: "Bluepeak Ops", items: 2, amount: 760, payment: "Paid", fulfillment: "Shipped", channel: "Web", date: "2026-03-07" },
];

const invoices = [
  { id: "INV-2109", customer: "Northstar Labs", amount: 4800, status: "Paid", issueDate: "2026-03-01", dueDate: "2026-03-08", paymentMethod: "Visa ending 4021" },
  { id: "INV-2110", customer: "Finloop CRM", amount: 9600, status: "Paid", issueDate: "2026-03-02", dueDate: "2026-03-09", paymentMethod: "ACH Transfer" },
  { id: "INV-2111", customer: "Orbit Commerce", amount: 2400, status: "Sent", issueDate: "2026-03-04", dueDate: "2026-03-14", paymentMethod: "Mastercard ending 9484" },
  { id: "INV-2112", customer: "Atlas HR", amount: 3200, status: "Overdue", issueDate: "2026-03-03", dueDate: "2026-03-10", paymentMethod: "SEPA Direct Debit" },
  { id: "INV-2113", customer: "Cloudmint", amount: 5200, status: "Paid", issueDate: "2026-03-05", dueDate: "2026-03-12", paymentMethod: "Visa ending 2987" },
  { id: "INV-2114", customer: "RetailJet", amount: 4100, status: "Draft", issueDate: "2026-03-07", dueDate: "2026-03-17", paymentMethod: "Wire Transfer" },
  { id: "INV-2115", customer: "SigmaPay", amount: 8300, status: "Paid", issueDate: "2026-03-06", dueDate: "2026-03-13", paymentMethod: "AMEX ending 5533" },
  { id: "INV-2116", customer: "PulseDesk", amount: 2700, status: "Sent", issueDate: "2026-03-08", dueDate: "2026-03-18", paymentMethod: "Visa ending 1793" },
];

const transactions = [
  { id: "TRX-9801", type: "Subscription", reference: "Northstar Labs / Scale", amount: 4800, method: "Visa", status: "Settled", date: "2026-03-11" },
  { id: "TRX-9802", type: "Upgrade", reference: "Finloop CRM / Enterprise", amount: 2100, method: "ACH", status: "Settled", date: "2026-03-11" },
  { id: "TRX-9803", type: "Refund", reference: "Orbit Commerce / Credit", amount: -420, method: "Mastercard", status: "Settled", date: "2026-03-10" },
  { id: "TRX-9804", type: "Subscription", reference: "Cloudmint / Scale", amount: 5200, method: "Visa", status: "Settled", date: "2026-03-10" },
  { id: "TRX-9805", type: "Invoice", reference: "Atlas HR / Overdue", amount: 3200, method: "SEPA", status: "Review", date: "2026-03-10" },
  { id: "TRX-9806", type: "Subscription", reference: "SigmaPay / Enterprise", amount: 8300, method: "AMEX", status: "Settled", date: "2026-03-09" },
  { id: "TRX-9807", type: "Chargeback", reference: "PulseDesk / Renewal", amount: -2700, method: "Visa", status: "Investigating", date: "2026-03-09" },
  { id: "TRX-9808", type: "Subscription", reference: "Bluepeak Ops / Starter", amount: 980, method: "Visa", status: "Settled", date: "2026-03-08" },
  { id: "TRX-9809", type: "Usage", reference: "RetailJet / Add-on", amount: 640, method: "Wire", status: "Pending", date: "2026-03-08" },
  { id: "TRX-9810", type: "Payout", reference: "Marketplace partner", amount: -1180, method: "Bank", status: "Scheduled", date: "2026-03-07" },
];

const tickets = [
  { id: "TCK-4102", subject: "SSO mapping fails for invited users", customer: "Finloop CRM", priority: "High", status: "Open", agent: "Mina Aksoy", updatedAt: "12m ago", channel: "Email", sla: "1h 24m" },
  { id: "TCK-4104", subject: "Invoice PDF is missing VAT lines", customer: "Northstar Labs", priority: "Medium", status: "Pending", agent: "Sarp Yilmaz", updatedAt: "38m ago", channel: "Chat", sla: "3h 10m" },
  { id: "TCK-4108", subject: "Bulk import wizard stalls at step three", customer: "Orbit Commerce", priority: "High", status: "Open", agent: "Mina Aksoy", updatedAt: "1h ago", channel: "Portal", sla: "2h 08m" },
  { id: "TCK-4110", subject: "Permissions matrix needs audit export", customer: "SigmaPay", priority: "Low", status: "Solved", agent: "Ali Gok", updatedAt: "2h ago", channel: "Email", sla: "Resolved" },
  { id: "TCK-4113", subject: "Webhook retry logs are delayed", customer: "Cloudmint", priority: "Medium", status: "Pending", agent: "Sarp Yilmaz", updatedAt: "3h ago", channel: "Portal", sla: "4h 20m" },
  { id: "TCK-4115", subject: "Need sandbox seats for procurement review", customer: "RetailJet", priority: "Low", status: "Open", agent: "Mina Aksoy", updatedAt: "5h ago", channel: "Email", sla: "7h 10m" },
  { id: "TCK-4117", subject: "Card updater marked healthy card as failed", customer: "PulseDesk", priority: "High", status: "Escalated", agent: "Ali Gok", updatedAt: "8h ago", channel: "Chat", sla: "45m" },
  { id: "TCK-4120", subject: "Need region-specific revenue export columns", customer: "Atlas HR", priority: "Medium", status: "Solved", agent: "Sarp Yilmaz", updatedAt: "1d ago", channel: "Portal", sla: "Resolved" },
];

const subscribers = customers.map((customer, index) => ({
  id: `SUB-${5000 + index}`,
  customer: customer.company,
  owner: customer.name,
  plan: customer.plan,
  seats: customer.seats,
  renewal: customer.renewal,
  status: customer.status,
  arpa: Math.round(customer.mrr / Math.max(customer.seats, 1)),
  country: customer.location,
}));

const teamMembers = [
  { name: "Deniz Kaya", role: "VP Revenue", team: "Executive", status: "Online", permissions: 21, email: "deniz@kanexus.io", location: "Istanbul" },
  { name: "Selin Akca", role: "Customer Success Lead", team: "Customer Success", status: "Online", permissions: 18, email: "selin@kanexus.io", location: "Berlin" },
  { name: "Mert Kaya", role: "Growth Manager", team: "Growth", status: "Focus", permissions: 14, email: "mert@kanexus.io", location: "London" },
  { name: "Lara Soylu", role: "Product Operations", team: "Operations", status: "Online", permissions: 16, email: "lara@kanexus.io", location: "Paris" },
  { name: "Mina Aksoy", role: "Support Manager", team: "Support", status: "Busy", permissions: 17, email: "mina@kanexus.io", location: "Ankara" },
  { name: "Sarp Yilmaz", role: "Support Engineer", team: "Support", status: "Away", permissions: 12, email: "sarp@kanexus.io", location: "Izmir" },
  { name: "Ali Gok", role: "Security Analyst", team: "Security", status: "Online", permissions: 19, email: "ali@kanexus.io", location: "Amsterdam" },
  { name: "Ece Uysal", role: "Finance Lead", team: "Finance", status: "Online", permissions: 18, email: "ece@kanexus.io", location: "Dubai" },
];

const files = [
  { name: "Q1-board-pack.pdf", type: "PDF", size: "8.4 MB", owner: "Deniz Kaya", updated: "12 Mar, 09:14", access: "Executive" },
  { name: "revops-playbook.docx", type: "DOCX", size: "1.2 MB", owner: "Mert Kaya", updated: "12 Mar, 08:42", access: "Growth" },
  { name: "pipeline-forecast.xlsx", type: "XLSX", size: "3.9 MB", owner: "Lara Soylu", updated: "11 Mar, 16:18", access: "Operations" },
  { name: "brand-assets.zip", type: "ZIP", size: "24.0 MB", owner: "Design Team", updated: "11 Mar, 14:02", access: "Marketing" },
  { name: "mrr-bridge.csv", type: "CSV", size: "640 KB", owner: "Ece Uysal", updated: "11 Mar, 11:33", access: "Finance" },
  { name: "sso-runbook.md", type: "MD", size: "26 KB", owner: "Ali Gok", updated: "10 Mar, 15:26", access: "Security" },
  { name: "nps-vocthemes.fig", type: "FIG", size: "18.2 MB", owner: "Design Team", updated: "10 Mar, 13:07", access: "Product" },
  { name: "support-macros.json", type: "JSON", size: "48 KB", owner: "Mina Aksoy", updated: "10 Mar, 09:55", access: "Support" },
];

const activities = [
  { title: "Northstar Labs renewed the Scale plan", detail: "Expansion of 6 seats confirmed by Stripe webhook", time: "10 minutes ago", tone: "success" },
  { title: "Risk alert triggered for Atlas HR", detail: "Weekly active seats dropped by 21 percent", time: "32 minutes ago", tone: "warning" },
  { title: "Security review exported by Ali Gok", detail: "Q1 audit package delivered to procurement", time: "1 hour ago", tone: "info" },
  { title: "Invoice INV-2112 flagged as overdue", detail: "Collections playbook moved the account to review", time: "2 hours ago", tone: "danger" },
  { title: "RetailJet onboarding checklist completed", detail: "Workspace templates and permissions were provisioned", time: "3 hours ago", tone: "primary" },
];

const inboxThreads = [
  { name: "Northstar Labs", topic: "Pricing alignment for annual commit", preview: "Can you share the updated enterprise tier notes?", time: "09:24", unread: 2 },
  { name: "Growth Team", topic: "April launch checklist", preview: "The campaign brief is ready for review.", time: "08:52", unread: 0 },
  { name: "SigmaPay", topic: "Security questionnaire", preview: "We attached the latest procurement list.", time: "Yesterday", unread: 1 },
  { name: "Support Ops", topic: "Weekend on-call", preview: "Coverage is confirmed for both shifts.", time: "Yesterday", unread: 0 },
];

const chatMessages = [
  { author: "Mina", body: "The SSO issue for Finloop is isolated to invited users. Logs point to an outdated attribute mapping.", direction: "incoming", time: "09:14" },
  { author: "You", body: "Please prep a workaround and update the ticket with the exact scope before noon.", direction: "outgoing", time: "09:16" },
  { author: "Ali", body: "I can validate the mapping in staging and share the revised SCIM sample.", direction: "incoming", time: "09:20" },
  { author: "You", body: "Perfect. I also want an impact estimate by contract value.", direction: "outgoing", time: "09:24" },
];

const calendarEvents = {
  3: [{ time: "09:30", title: "Exec standup", tone: "primary" }],
  6: [{ time: "12:00", title: "QBR prep", tone: "warning" }],
  8: [{ time: "15:00", title: "Northstar renewal", tone: "success" }],
  12: [{ time: "10:00", title: "Pipeline review", tone: "primary" }],
  14: [{ time: "13:30", title: "Board materials", tone: "info" }],
  18: [{ time: "11:00", title: "Onboarding audit", tone: "warning" }],
  21: [{ time: "16:00", title: "Security review", tone: "danger" }],
  27: [{ time: "14:00", title: "Pricing workshop", tone: "primary" }],
};

const kanbanColumns = [
  { title: "Backlog", count: 5, cards: [{ title: "Revise enterprise onboarding deck", meta: "Marketing / 2 subtasks", tone: "primary" }, { title: "Map overdue invoice follow-ups", meta: "Finance / 1 blocker", tone: "warning" }, { title: "Audit workspace permission labels", meta: "Security / 3 reviewers", tone: "info" }] },
  { title: "In Progress", count: 4, cards: [{ title: "Launch Q2 dashboard pack", meta: "Product / Due tomorrow", tone: "success" }, { title: "Build support routing heatmap", meta: "Support / SLA focus", tone: "primary" }, { title: "Finalize annual pricing matrix", meta: "Revenue / CFO review", tone: "danger" }] },
  { title: "Review", count: 3, cards: [{ title: "Mobile navigation accessibility pass", meta: "Design / QA", tone: "info" }, { title: "Billing recovery email refresh", meta: "Lifecycle / Legal review", tone: "warning" }] },
  { title: "Done", count: 9, cards: [{ title: "Customer health score revamp", meta: "Analytics / Live", tone: "success" }, { title: "Security settings redesign", meta: "Platform / Released", tone: "primary" }] },
];

const plans = [
  { name: "Starter", price: "$49", description: "For early-stage SaaS teams that need structure fast.", tone: "info", features: ["1 workspace", "Up to 10 team seats", "Billing and analytics basics", "Email support"] },
  { name: "Growth", price: "$129", description: "For scaling products that need cross-team visibility.", tone: "primary", features: ["5 workspaces", "Automated reports", "Advanced dashboards", "Role-based access"] },
  { name: "Scale", price: "$249", description: "For multi-team operators managing revenue and support at once.", tone: "success", features: ["Unlimited dashboards", "Custom lifecycle flows", "Priority support", "Audit exports"] },
  { name: "Enterprise", price: "Custom", description: "For large organizations with governance, security and procurement needs.", tone: "warning", features: ["SSO and SCIM", "Dedicated success manager", "Custom data retention", "Procurement support"] },
];

const permissionRows = [
  { area: "Billing", admin: true, manager: true, analyst: true, support: false },
  { area: "Subscriptions", admin: true, manager: true, analyst: true, support: true },
  { area: "Revenue Reports", admin: true, manager: true, analyst: true, support: false },
  { area: "Orders", admin: true, manager: true, analyst: false, support: true },
  { area: "Security Settings", admin: true, manager: false, analyst: false, support: false },
  { area: "Support Tickets", admin: true, manager: true, analyst: false, support: true },
];

const pageGroups = [
  { id: "dashboard", label: "Dashboards" },
  { id: "management", label: "Management" },
  { id: "business", label: "SaaS / Business" },
  { id: "productivity", label: "Productivity" },
  { id: "team", label: "Team & Account" },
  { id: "auth", label: "Auth" },
  { id: "utility", label: "Utility" },
];

const pages = [
  { id: "home", path: "index.html", title: "Dashboard Overview", navLabel: "Overview Home", group: "dashboard", shell: "app", activeNav: "dashboard-overview", render: "dashboardOverview", description: "Primary operating dashboard for revenue, users and support health." },
  { id: "dashboard-overview", path: "pages/dashboard/overview.html", title: "Dashboard Overview", navLabel: "Overview", group: "dashboard", shell: "app", activeNav: "dashboard-overview", render: "dashboardOverview", description: "Primary operating dashboard for revenue, users and support health." },
  { id: "analytics-dashboard", path: "pages/dashboard/analytics.html", title: "Analytics Dashboard", navLabel: "Analytics", group: "dashboard", shell: "app", activeNav: "analytics-dashboard", render: "analyticsDashboard", description: "Traffic quality, acquisition efficiency and cohort depth in one workspace." },
  { id: "crm-dashboard", path: "pages/dashboard/crm.html", title: "CRM Dashboard", navLabel: "CRM", group: "dashboard", shell: "app", activeNav: "crm-dashboard", render: "crmDashboard", description: "Pipeline coverage, account health and renewals for revenue teams." },
  { id: "ecommerce-dashboard", path: "pages/dashboard/ecommerce.html", title: "E-Commerce Dashboard", navLabel: "E-Commerce", group: "dashboard", shell: "app", activeNav: "ecommerce-dashboard", render: "ecommerceDashboard", description: "Commerce funnel, order volume and catalog performance." },
  { id: "customers-list", path: "pages/management/customers-list.html", title: "Customers List", navLabel: "Customers List", group: "management", shell: "app", activeNav: "customers-list", render: "customersList", description: "Searchable customer directory with account health and revenue context." },
  { id: "customer-detail", path: "pages/management/customer-detail.html", title: "Customer Detail", navLabel: "Customer Detail", group: "management", shell: "app", activeNav: "customers-list", parent: "customers-list", render: "customerDetail", description: "Single account profile with billing, adoption and lifecycle detail." },
  { id: "orders-list", path: "pages/management/orders-list.html", title: "Orders List", navLabel: "Orders List", group: "management", shell: "app", activeNav: "orders-list", render: "ordersList", description: "Operational order queue with payment and fulfillment states." },
  { id: "order-detail", path: "pages/management/order-detail.html", title: "Order Detail", navLabel: "Order Detail", group: "management", shell: "app", activeNav: "orders-list", parent: "orders-list", render: "orderDetail", description: "Order summary with line items, shipment and billing trail." },
  { id: "products-list", path: "pages/management/products-list.html", title: "Products List", navLabel: "Products List", group: "management", shell: "app", activeNav: "products-list", render: "productsList", description: "Catalog management table with pricing and revenue output." },
  { id: "product-detail", path: "pages/management/product-detail.html", title: "Product Detail", navLabel: "Product Detail", group: "management", shell: "app", activeNav: "products-list", parent: "products-list", render: "productDetail", description: "Product profile with inventory posture and trendline performance." },
  { id: "add-product", path: "pages/management/add-new-product.html", title: "Add New Product", navLabel: "Add New Product", group: "management", shell: "app", activeNav: "products-list", parent: "products-list", render: "addNewProduct", description: "Structured form to create a new product or plan bundle." },
  { id: "categories", path: "pages/management/categories.html", title: "Categories", navLabel: "Categories", group: "management", shell: "app", activeNav: "categories", render: "categories", description: "Category mix, owned revenue and publishing posture." },
  { id: "transactions", path: "pages/management/transactions.html", title: "Transactions", navLabel: "Transactions", group: "management", shell: "app", activeNav: "transactions", render: "transactions", description: "Revenue movements across subscriptions, refunds and payouts." },
  { id: "invoices", path: "pages/management/invoices.html", title: "Invoices", navLabel: "Invoices", group: "management", shell: "app", activeNav: "invoices", render: "invoices", description: "Invoice list with issue dates, due dates and payment status." },
  { id: "invoice-detail", path: "pages/management/invoice-detail.html", title: "Invoice Detail", navLabel: "Invoice Detail", group: "management", shell: "app", activeNav: "invoices", parent: "invoices", render: "invoiceDetail", description: "Detailed invoice record for finance and collections workflows." },
  { id: "subscription-plans", path: "pages/business/subscription-plans.html", title: "Subscription Plans", navLabel: "Subscription Plans", group: "business", shell: "app", activeNav: "subscription-plans", render: "subscriptionPlans", description: "Plan packaging, feature sets and plan distribution summary." },
  { id: "subscribers-list", path: "pages/business/subscribers-list.html", title: "Subscribers List", navLabel: "Subscribers List", group: "business", shell: "app", activeNav: "subscribers-list", render: "subscribersList", description: "Subscriber roster with renewal cadence and ARPA detail." },
  { id: "billing-overview", path: "pages/business/billing-overview.html", title: "Billing Overview", navLabel: "Billing Overview", group: "business", shell: "app", activeNav: "billing-overview", render: "billingOverview", description: "Cash collections, recovery rate and payment method health." },
  { id: "revenue-reports", path: "pages/business/revenue-reports.html", title: "Revenue Reports", navLabel: "Revenue Reports", group: "business", shell: "app", activeNav: "revenue-reports", render: "revenueReports", description: "Segmented revenue reporting for leadership and finance." },
  { id: "support-tickets", path: "pages/business/support-tickets.html", title: "Support Tickets", navLabel: "Support Tickets", group: "business", shell: "app", activeNav: "support-tickets", render: "supportTickets", description: "Support workload, SLAs and priority mix by channel." },
  { id: "ticket-detail", path: "pages/business/ticket-detail.html", title: "Ticket Detail", navLabel: "Ticket Detail", group: "business", shell: "app", activeNav: "support-tickets", parent: "support-tickets", render: "ticketDetail", description: "Single support thread with notes, SLA and recommended macros." },
  { id: "calendar", path: "pages/productivity/calendar.html", title: "Calendar", navLabel: "Calendar", group: "productivity", shell: "app", activeNav: "calendar", render: "calendar", description: "Operational calendar with meetings, deadlines and launches." },
  { id: "kanban", path: "pages/productivity/kanban-board.html", title: "Kanban Board", navLabel: "Kanban Board", group: "productivity", shell: "app", activeNav: "kanban", render: "kanban", description: "Delivery board for operations, product and support workstreams." },
  { id: "messages", path: "pages/productivity/messages-inbox.html", title: "Messages / Inbox", navLabel: "Messages / Inbox", group: "productivity", shell: "app", activeNav: "messages", render: "messages", description: "Threaded inbox for customer and internal communication." },
  { id: "chat", path: "pages/productivity/chat-page.html", title: "Chat Page", navLabel: "Chat Page", group: "productivity", shell: "app", activeNav: "chat", render: "chat", description: "Live team chat with context cards and quick actions." },
  { id: "file-manager", path: "pages/productivity/file-manager.html", title: "File Manager", navLabel: "File Manager", group: "productivity", shell: "app", activeNav: "file-manager", render: "fileManager", description: "Structured file browser for assets, reports and exports." },
  { id: "team-members", path: "pages/team/team-members.html", title: "Team Members", navLabel: "Team Members", group: "team", shell: "app", activeNav: "team-members", render: "teamMembers", description: "People directory with status, ownership and permission depth." },
  { id: "roles-permissions", path: "pages/team/roles-permissions.html", title: "Roles & Permissions", navLabel: "Roles & Permissions", group: "team", shell: "app", activeNav: "roles-permissions", render: "rolesPermissions", description: "Role catalogue and permission matrix for governance." },
  { id: "user-profile", path: "pages/team/user-profile.html", title: "User Profile", navLabel: "User Profile", group: "team", shell: "app", activeNav: "user-profile", render: "userProfile", description: "Personal profile with ownership, activity and linked workstreams." },
  { id: "account-settings", path: "pages/team/account-settings.html", title: "Account Settings", navLabel: "Account Settings", group: "team", shell: "app", activeNav: "account-settings", render: "accountSettings", description: "Company profile, billing contacts and workspace metadata." },
  { id: "security-settings", path: "pages/team/security-settings.html", title: "Security Settings", navLabel: "Security Settings", group: "team", shell: "app", activeNav: "security-settings", render: "securitySettings", description: "Security posture, active sessions and access controls." },
  { id: "notification-settings", path: "pages/team/notification-settings.html", title: "Notification Settings", navLabel: "Notification Settings", group: "team", shell: "app", activeNav: "notification-settings", render: "notificationSettings", description: "Notification routing across email, mobile and in-app channels." },
  { id: "login", path: "pages/auth/login.html", title: "Login", navLabel: "Login", group: "auth", shell: "auth", render: "login", description: "Sign in screen for operators and team members." },
  { id: "register", path: "pages/auth/register.html", title: "Register", navLabel: "Register", group: "auth", shell: "auth", render: "register", description: "Create a new workspace operator account." },
  { id: "forgot-password", path: "pages/auth/forgot-password.html", title: "Forgot Password", navLabel: "Forgot Password", group: "auth", shell: "auth", render: "forgotPassword", description: "Recover access with a password reset email flow." },
  { id: "reset-password", path: "pages/auth/reset-password.html", title: "Reset Password", navLabel: "Reset Password", group: "auth", shell: "auth", render: "resetPassword", description: "Define a new password and confirm access." },
  { id: "two-factor", path: "pages/auth/two-factor-verification.html", title: "Two-Factor Verification", navLabel: "Two-Factor Verification", group: "auth", shell: "auth", render: "twoFactor", description: "Enter a one-time code to finalize login." },
  { id: "pricing", path: "pages/utility/pricing.html", title: "Pricing", navLabel: "Pricing", group: "utility", shell: "app", activeNav: "pricing", render: "pricing", description: "Pricing comparison page for plans and enterprise options." },
  { id: "faq", path: "pages/utility/faq.html", title: "FAQ", navLabel: "FAQ", group: "utility", shell: "app", activeNav: "faq", render: "faq", description: "Answers to product, billing and implementation questions." },
  { id: "blank", path: "pages/utility/blank-page.html", title: "Blank Page", navLabel: "Blank Page", group: "utility", shell: "app", activeNav: "blank", render: "blank", description: "Starter canvas with reusable layout regions and guidance." },
  { id: "404", path: "pages/utility/404-error-page.html", title: "404 Error Page", navLabel: "404 Error Page", group: "utility", shell: "special", render: "error404", description: "Not found state for invalid routes or expired links." },
  { id: "500", path: "pages/utility/500-error-page.html", title: "500 Error Page", navLabel: "500 Error Page", group: "utility", shell: "special", render: "error500", description: "Server issue state for processing failures." },
  { id: "maintenance", path: "pages/utility/maintenance-page.html", title: "Maintenance Page", navLabel: "Maintenance Page", group: "utility", shell: "special", render: "maintenance", description: "Planned maintenance placeholder with status summary." },
];

const pageMap = new Map(pages.map((page) => [page.id, page]));

function writeFile(relativePath, content) {
  const fullPath = path.join(root, relativePath);
  mkdirSync(path.dirname(fullPath), { recursive: true });
  writeFileSync(fullPath, content, "utf8");
}

function depthFor(filePath) {
  const parts = filePath.split("/");
  return parts.length - 1;
}

function rootPath(depth, target) {
  return `${"../".repeat(depth)}${target}`;
}

function pageHref(pageId, depth) {
  const page = pageMap.get(pageId);
  return rootPath(depth, page.path);
}

function escapeHtml(value) {
  return String(value)
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;");
}

function stripHtml(value) {
  return String(value).replace(/<[^>]+>/g, "");
}

function initials(name) {
  return name.split(" ").slice(0, 2).map((part) => part[0]).join("").toUpperCase();
}

function currency(value) {
  const amount = Number(value);
  const sign = amount < 0 ? "-" : "";
  return `${sign}$${Math.abs(amount).toLocaleString("en-US")}`;
}

function number(value) {
  return Number(value).toLocaleString("en-US");
}

function tonePair(tone = "primary") {
  return tones[tone] || tones.primary;
}

function badge(text, tone = "primary", kind = "metric") {
  const pair = tonePair(tone);
  const className = kind === "status" ? "status-badge" : "metric-badge";
  return `<span class="${className}" style="background:${pair.soft};color:${pair.main};border-color:${pair.soft};">${escapeHtml(text)}</span>`;
}

function icon(name, classes = "h-5 w-5") {
  const icons = {
    logo: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M5 19V5l7-2 7 2v14l-7 2-7-2Zm7-16v16m7-14-7 2-7-2m14 8-7 2-7-2"/>',
    dashboard: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M4 12h7V4H4v8Zm9 8h7v-5h-7v5Zm0-9h7V4h-7v7ZM4 20h7v-5H4v5Z"/>',
    analytics: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M4 19h16M7 15V9m5 6V5m5 10v-3"/>',
    users: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M15 20v-1a4 4 0 0 0-4-4H7a4 4 0 0 0-4 4v1m18 0v-1a4 4 0 0 0-3-3.87M14 4.13a4 4 0 0 1 0 7.75M13 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0Z"/>',
    shopping: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M3 3h2l.4 2M7 13h10l4-8H6.4m.6 8L5.2 5M7 13l-1.1 5H19M9 20a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm8 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"/>',
    receipt: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M7 3h10v18l-3-2-2 2-2-2-3 2V3Zm3 4h4m-6 4h8m-8 4h5"/>',
    credit: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M3 7h18v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Zm0 0V6a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v1M3 11h18"/>',
    ticket: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M4 7a2 2 0 0 0 2-2h12a2 2 0 0 0 2 2v3a2 2 0 0 0 0 4v3a2 2 0 0 0-2 2H6a2 2 0 0 0-2-2v-3a2 2 0 0 0 0-4V7Zm8-2v14"/>',
    calendar: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M8 3v4m8-4v4M4 9h16M5 5h14a1 1 0 0 1 1 1v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a1 1 0 0 1 1-1Z"/>',
    kanban: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M4 5h5v14H4V5Zm6 0h5v9h-5V5Zm6 0h4v6h-4V5Zm0 7h4v7h-4v-7Zm-6 3h5v4h-5v-4Z"/>',
    inbox: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M4 6h16v12H4V6Zm0 7h4l2 3h4l2-3h4"/>',
    chat: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M7 17.5 4 20V6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H7Z"/>',
    folder: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z"/>',
    team: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2m16 0v-2a4 4 0 0 0-3-3.87m-8-8a4 4 0 1 0 8 0 4 4 0 0 0-8 0Zm9 0a4 4 0 1 1 3.99 4A4 4 0 0 1 15 7Z"/>',
    shield: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="m12 3 7 3v5c0 4.97-3.06 8.7-7 10-3.94-1.3-7-5.03-7-10V6l7-3Zm-2.5 9.5 1.8 1.8 3.7-4.3"/>',
    user: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2m8-10a4 4 0 1 0 0-8 4 4 0 0 0 0 8Z"/>',
    settings: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M12 8.5A3.5 3.5 0 1 0 12 15.5 3.5 3.5 0 0 0 12 8.5Zm8 3.5-.9-.6a1 1 0 0 1-.45-1.03l.19-1.07-1.8-1.04-.76.77a1 1 0 0 1-1.04.23l-1.04-.42-.35-1.06H10.2L9.85 8.8a1 1 0 0 1-1.04.23l-1.04.42-.76-.77-1.8 1.04.2 1.07a1 1 0 0 1-.46 1.03L4 12l.9.6a1 1 0 0 1 .45 1.03l-.19 1.07 1.8 1.04.76-.77a1 1 0 0 1 1.04-.23l1.04.42.35 1.06h2.6l.35-1.06 1.04-.42a1 1 0 0 1 1.04.23l.76.77 1.8-1.04-.2-1.07a1 1 0 0 1 .46-1.03l.9-.6Z"/>',
    bell: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M6 8a6 6 0 1 1 12 0c0 7 3 8 3 8H3s3-1 3-8m4 12a2 2 0 1 0 4 0"/>',
    search: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="m21 21-4.35-4.35M10.5 18a7.5 7.5 0 1 1 0-15 7.5 7.5 0 0 1 0 15Z"/>',
    menu: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M4 7h16M4 12h16M4 17h16"/>',
    chevronRight: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="m9 18 6-6-6-6"/>',
    chevronDown: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="m6 9 6 6 6-6"/>',
    dots: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M12 5.5h.01M12 12h.01M12 18.5h.01"/>',
    plus: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M12 5v14M5 12h14"/>',
    filter: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M4 6h16M7 12h10m-7 6h4"/>',
    download: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M12 3v12m0 0 4-4m-4 4-4-4m-4 8h16"/>',
    upload: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="m12 21V9m0 0 4 4m-4-4-4 4M4 3h16"/>',
    activity: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M3 12h4l2-5 4 10 2-5h6"/>',
    trendUp: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M3 17 9 11l4 4 8-8M15 7h6v6"/>',
    trendDown: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="m3 7 6 6 4-4 8 8M15 17h6v-6"/>',
    clock: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M12 8v4l3 2m7-2a10 10 0 1 1-20 0 10 10 0 0 1 20 0Z"/>',
    check: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="m5 13 4 4L19 7"/>',
    warning: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M12 9v4m0 4h.01M10.3 4.5 2.8 18a2 2 0 0 0 1.74 3h14.92A2 2 0 0 0 21.2 18L13.7 4.5a2 2 0 0 0-3.4 0Z"/>',
    server: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M4 6h16v4H4V6Zm0 8h16v4H4v-4Zm3-6h.01M7 16h.01"/>',
    lock: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M7 11V8a5 5 0 1 1 10 0v3m-9 0h8a2 2 0 0 1 2 2v6H6v-6a2 2 0 0 1 2-2Z"/>',
    sparkles: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="m12 3 1.5 4.5L18 9l-4.5 1.5L12 15l-1.5-4.5L6 9l4.5-1.5L12 3Zm7 10 1 3 3 1-3 1-1 3-1-3-3-1 3-1 1-3ZM4 14l.8 2.2L7 17l-2.2.8L4 20l-.8-2.2L1 17l2.2-.8L4 14Z"/>',
  };

  return `<svg class="${classes}" viewBox="0 0 24 24" fill="none" stroke="currentColor">${icons[name] || icons.dashboard}</svg>`;
}

function iconBox(name, tone = "primary") {
  const pair = tonePair(tone);
  return `<div class="flex h-12 w-12 items-center justify-center rounded-2xl" style="background:${pair.soft};color:${pair.main};">${icon(name, "h-5 w-5")}</div>`;
}

function avatar(name, tone = "primary", size = "") {
  const extra = size ? ` avatar-${size}` : "";
  return `<span class="avatar ${tone}${extra}">${escapeHtml(initials(name))}</span>`;
}

function statCard({ label, value, delta, tone = "primary", iconName = "analytics", hint }) {
  return `
    <article class="panel stat-card reveal p-5">
      <div class="flex items-start justify-between gap-4">
        <div>
          <p class="text-sm font-semibold text-[color:var(--text-soft)]">${escapeHtml(label)}</p>
          <p class="mt-3 font-display text-3xl font-semibold tracking-tight text-[color:var(--text)]">${escapeHtml(value)}</p>
          <div class="mt-4 flex flex-wrap items-center gap-3">
            ${delta ? badge(delta, tone) : ""}
            ${hint ? `<span class="text-sm text-[color:var(--text-faint)]">${escapeHtml(hint)}</span>` : ""}
          </div>
        </div>
        ${iconBox(iconName, tone)}
      </div>
    </article>
  `;
}

function progressRow(label, value, tone = "primary") {
  const pair = tonePair(tone);
  return `
    <div class="space-y-2">
      <div class="flex items-center justify-between gap-3 text-sm">
        <span class="font-semibold text-[color:var(--text)]">${escapeHtml(label)}</span>
        <span class="text-[color:var(--text-soft)]">${value}%</span>
      </div>
      <div class="h-2 rounded-full bg-[color:var(--bg-muted)]"><div class="h-full rounded-full" style="width:${value}%;background:${pair.main};"></div></div>
    </div>
  `;
}

function panel(title, description, body, action = "") {
  return `
    <section class="panel reveal p-6">
      <div class="mb-5 flex flex-wrap items-start justify-between gap-4">
        <div>
          <h3 class="font-display text-xl font-semibold tracking-tight text-[color:var(--text)]">${escapeHtml(title)}</h3>
          ${description ? `<p class="mt-1 text-sm text-[color:var(--text-soft)]">${escapeHtml(description)}</p>` : ""}
        </div>
        ${action}
      </div>
      ${body}
    </section>
  `;
}

function heroBlock(page, metrics, actions = "") {
  return `
    <section class="panel reveal overflow-hidden p-6 lg:p-8">
      <div class="grid gap-8 xl:grid-cols-[1.25fr_.75fr]">
        <div class="relative">
          <div class="mb-4 inline-flex items-center gap-2 rounded-full border border-slate-200/70 bg-white/70 px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.2em] text-slate-500 shadow-sm dark:border-slate-800 dark:bg-slate-900/60 dark:text-slate-400">${icon("sparkles", "h-4 w-4")}KA Nexus Admin</div>
          <h1 class="max-w-3xl font-display text-3xl font-semibold tracking-tight text-[color:var(--text)] lg:text-4xl">${escapeHtml(page.title)}</h1>
          <p class="mt-4 max-w-2xl text-base leading-7 text-[color:var(--text-soft)]">${escapeHtml(page.description)}</p>
          <div class="mt-6 flex flex-wrap items-center gap-3">${actions}</div>
        </div>
        <div class="grid gap-4 sm:grid-cols-2">
          ${metrics.map((metric) => `<div class="panel-muted p-4"><p class="text-xs font-semibold uppercase tracking-[0.18em] text-[color:var(--text-faint)]">${escapeHtml(metric.label)}</p><p class="mt-3 text-2xl font-semibold tracking-tight text-[color:var(--text)]">${escapeHtml(metric.value)}</p><div class="mt-3">${badge(metric.delta, metric.tone)}</div></div>`).join("")}
        </div>
      </div>
    </section>
  `;
}

function timeline(items) {
  return `<div class="timeline space-y-6">${items.map((item) => `<article class="timeline-item"><div class="flex flex-wrap items-center gap-3">${badge(item.time, item.tone || "primary")}</div><h4 class="mt-3 text-base font-semibold text-[color:var(--text)]">${escapeHtml(item.title)}</h4><p class="mt-1 text-sm leading-6 text-[color:var(--text-soft)]">${escapeHtml(item.detail)}</p></article>`).join("")}</div>`;
}

function simpleTable(columns, rows) {
  return `<div class="overflow-x-auto"><table class="w-full text-sm"><thead><tr class="border-b border-[color:var(--border)] text-left text-[color:var(--text-faint)]">${columns.map((column) => `<th class="pb-3 pr-4 font-semibold">${escapeHtml(column)}</th>`).join("")}</tr></thead><tbody>${rows.map((row) => `<tr class="border-b border-[color:var(--border)] align-top">${row.map((cell) => `<td class="py-4 pr-4 text-[color:var(--text-soft)]">${cell}</td>`).join("")}</tr>`).join("")}</tbody></table></div>`;
}

function activityList(items) {
  return `<div class="space-y-4">${items.map((item) => `<article class="flex items-start gap-4 rounded-3xl border border-[color:var(--border)] bg-[color:var(--bg-muted)]/50 p-4">${iconBox("activity", item.tone)}<div class="min-w-0"><h4 class="text-sm font-semibold text-[color:var(--text)]">${escapeHtml(item.title)}</h4><p class="mt-1 text-sm leading-6 text-[color:var(--text-soft)]">${escapeHtml(item.detail)}</p><p class="mt-2 text-xs font-semibold uppercase tracking-[0.18em] text-[color:var(--text-faint)]">${escapeHtml(item.time)}</p></div></article>`).join("")}</div>`;
}

function keyValueList(items) {
  return `<dl class="grid gap-4 sm:grid-cols-2">${items.map((item) => `<div class="rounded-3xl border border-[color:var(--border)] bg-[color:var(--bg-muted)]/50 p-4"><dt class="text-xs font-semibold uppercase tracking-[0.18em] text-[color:var(--text-faint)]">${escapeHtml(item.label)}</dt><dd class="mt-2 text-base font-semibold text-[color:var(--text)]">${item.value}</dd></div>`).join("")}</dl>`;
}

function actionMenu() {
  return `<div x-data="{open:false}" class="relative"><button @click="open=!open" type="button" class="inline-flex h-10 w-10 items-center justify-center rounded-2xl border border-[color:var(--border)] bg-white/70 text-[color:var(--text-soft)] transition hover:text-[color:var(--text)] dark:bg-slate-900/60">${icon("dots", "h-4 w-4")}</button><div x-cloak x-show="open" @click.outside="open=false" class="table-action-menu absolute right-0 top-12 z-20 p-2"><button type="button" class="flex w-full items-center gap-3 rounded-2xl px-3 py-2 text-left text-sm text-[color:var(--text-soft)] transition hover:bg-[color:var(--bg-muted)] hover:text-[color:var(--text)]" data-toast="View opened">${icon("search", "h-4 w-4")} View</button><button type="button" class="flex w-full items-center gap-3 rounded-2xl px-3 py-2 text-left text-sm text-[color:var(--text-soft)] transition hover:bg-[color:var(--bg-muted)] hover:text-[color:var(--text)]" data-toast="Edit workspace launched">${icon("settings", "h-4 w-4")} Edit</button><button type="button" class="flex w-full items-center gap-3 rounded-2xl px-3 py-2 text-left text-sm text-[color:var(--danger)] transition hover:bg-[color:var(--danger-soft)]">${icon("warning", "h-4 w-4")} Archive</button></div></div>`;
}

function renderDataTable({ title, description, columns, rows, filters = [], searchPlaceholder = "Search records", pageSize = 6, sortKey = "" }) {
  return `
    <section class="panel reveal overflow-hidden">
      <div class="flex flex-col gap-5 border-b border-[color:var(--border)] p-6">
        <div class="flex flex-wrap items-start justify-between gap-4">
          <div><h3 class="font-display text-xl font-semibold tracking-tight text-[color:var(--text)]">${escapeHtml(title)}</h3><p class="mt-1 text-sm text-[color:var(--text-soft)]">${escapeHtml(description)}</p></div>
          <div class="flex flex-wrap gap-3">
            <button type="button" class="inline-flex items-center gap-2 rounded-2xl border border-[color:var(--border)] px-4 py-2 text-sm font-semibold text-[color:var(--text-soft)] transition hover:text-[color:var(--text)]" data-drawer-open="filters">${icon("filter", "h-4 w-4")} Filters</button>
            <button type="button" class="inline-flex items-center gap-2 rounded-2xl bg-blue-600 px-4 py-2 text-sm font-semibold text-white shadow-lg shadow-blue-600/20 transition hover:bg-blue-700" data-modal-open="quick-actions">${icon("plus", "h-4 w-4")} New entry</button>
          </div>
        </div>
        <div class="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
          <label class="top-search flex min-w-0 items-center gap-3 px-4 py-3 lg:min-w-[320px]">${icon("search", "h-4 w-4 text-slate-400")}<input type="search" class="w-full border-0 bg-transparent p-0 text-sm text-[color:var(--text)] focus:ring-0" placeholder="${escapeHtml(searchPlaceholder)}" data-table-search /></label>
          <div class="flex flex-wrap gap-3">${filters.map((filter) => `<label class="min-w-[160px]"><select class="select-field" data-table-filter="${escapeHtml(filter.key)}"><option value="">${escapeHtml(filter.label)}</option>${filter.options.map((option) => `<option value="${escapeHtml(option)}">${escapeHtml(option)}</option>`).join("")}</select></label>`).join("")}</div>
        </div>
      </div>
      <div data-table-root data-page-size="${pageSize}" data-sort-key="${escapeHtml(sortKey)}">
        <div data-bulk-bar class="hidden items-center justify-between gap-4 border-b border-[color:var(--border)] bg-[color:var(--bg-muted)]/60 px-6 py-4 lg:flex"><div class="flex items-center gap-3 text-sm text-[color:var(--text-soft)]">${badge("Selected", "primary")}<span><strong data-bulk-count>0</strong> rows selected</span></div><div class="flex flex-wrap gap-3"><button type="button" class="rounded-2xl border border-[color:var(--border)] px-4 py-2 text-sm font-semibold text-[color:var(--text-soft)]" data-bulk-action="Bulk export ready">Export</button><button type="button" class="rounded-2xl border border-[color:var(--border)] px-4 py-2 text-sm font-semibold text-[color:var(--text-soft)]" data-bulk-action="Bulk assignment updated">Assign owner</button><button type="button" class="rounded-2xl border border-transparent px-4 py-2 text-sm font-semibold text-[color:var(--danger)]" data-bulk-action="Archive workflow queued">Archive</button></div></div>
        <div class="data-table-shell overflow-x-auto"><table><thead><tr><th class="w-12"><input type="checkbox" class="rounded border-slate-300 text-blue-600 focus:ring-blue-500" data-table-select-all /></th>${columns.map((column) => column.sortable ? `<th><button type="button" class="inline-flex items-center gap-2 font-semibold" data-sort-key="${escapeHtml(column.key)}" data-sort-type="${escapeHtml(column.type || "string")}">${escapeHtml(column.label)} <span data-sort-indicator>|</span></button></th>` : `<th class="font-semibold">${escapeHtml(column.label)}</th>`).join("")}<th class="text-right font-semibold">Actions</th></tr></thead><tbody>${rows.map((row) => { const dataAttributes = Object.entries(row.filters || {}).map(([key, value]) => `data-${escapeHtml(key)}="${escapeHtml(value)}"`).join(" "); const sortAttributes = columns.filter((column) => column.sortable).map((column) => `data-sort-${escapeHtml(column.key)}="${escapeHtml(row.sort?.[column.key] ?? stripHtml(row.cells[column.key] ?? ""))}"`).join(" "); return `<tr data-row data-search="${escapeHtml(row.search)}" ${dataAttributes} ${sortAttributes}><td><input type="checkbox" class="rounded border-slate-300 text-blue-600 focus:ring-blue-500" data-row-select /></td>${columns.map((column) => `<td>${row.cells[column.key]}</td>`).join("")}<td class="text-right">${actionMenu()}</td></tr>`; }).join("")}</tbody></table></div>
        <div class="flex flex-col gap-4 border-t border-[color:var(--border)] px-6 py-5 lg:flex-row lg:items-center lg:justify-between"><p class="text-sm text-[color:var(--text-soft)]" data-table-count>${rows.length} records</p><div class="flex flex-wrap gap-2" data-pagination></div></div>
      </div>
    </section>
  `;
}

function navIconFor(pageId) {
  if (pageId.includes("dashboard") || pageId === "home") return "dashboard";
  if (pageId.includes("analytics")) return "analytics";
  if (pageId.includes("crm")) return "users";
  if (pageId.includes("ecommerce") || pageId.includes("orders") || pageId.includes("products") || pageId.includes("categories")) return "shopping";
  if (pageId.includes("invoice")) return "receipt";
  if (pageId.includes("transactions") || pageId.includes("billing") || pageId.includes("pricing")) return "credit";
  if (pageId.includes("ticket") || pageId.includes("faq")) return "ticket";
  if (pageId.includes("calendar")) return "calendar";
  if (pageId.includes("kanban")) return "kanban";
  if (pageId.includes("messages")) return "inbox";
  if (pageId.includes("chat")) return "chat";
  if (pageId.includes("file")) return "folder";
  if (pageId.includes("team") || pageId.includes("roles")) return "team";
  if (pageId.includes("security")) return "shield";
  if (pageId.includes("user") || pageId.includes("account")) return "user";
  if (pageId.includes("notification")) return "bell";
  if (pageId.includes("password") || pageId.includes("login") || pageId.includes("register") || pageId.includes("two-factor")) return "lock";
  if (pageId.includes("maintenance")) return "server";
  return "dashboard";
}

function sidebar(page, depth) {
  return `
    <aside class="sidebar-shell fixed inset-y-0 left-0 z-40 flex flex-col overflow-hidden">
      <div class="flex items-center justify-between gap-3 border-b border-[color:var(--border)] px-5 py-5">
        <a href="${pageHref("dashboard-overview", depth)}" class="flex min-w-0 items-center gap-3"><span class="flex h-12 w-12 items-center justify-center rounded-2xl bg-slate-950 text-white shadow-xl shadow-slate-900/15 dark:bg-white dark:text-slate-950">${icon("logo", "h-6 w-6")}</span><span class="sidebar-brand-copy min-w-0"><span class="block truncate font-display text-lg font-semibold tracking-tight text-[color:var(--text)]">KA Nexus</span><span class="block truncate text-sm text-[color:var(--text-soft)]">Admin Template</span></span></a>
        <div class="flex items-center gap-2">
          <button type="button" class="inline-flex rounded-2xl border border-[color:var(--border)] p-2 text-[color:var(--text-soft)] lg:hidden" data-mobile-sidebar-close>${icon("chevronRight", "h-4 w-4 rotate-45")}</button>
          <button type="button" class="hidden rounded-2xl border border-[color:var(--border)] p-2 text-[color:var(--text-soft)] lg:inline-flex" data-sidebar-toggle>${icon("chevronRight", "h-4 w-4")}</button>
        </div>
      </div>
      <div class="flex-1 space-y-5 overflow-y-auto px-4 py-5">
        ${pageGroups.map((group) => { const groupPages = pages.filter((candidate) => candidate.group === group.id); const isOpen = page.group === group.id ? "true" : "false"; return `<section class="sidebar-group" x-data="{open:${isOpen}}"><button type="button" class="sidebar-group-toggle flex w-full items-center justify-between gap-3 px-2 text-left text-xs font-semibold uppercase tracking-[0.22em] text-[color:var(--text-faint)]" @click="open=!open"><span class="sidebar-section-title">${escapeHtml(group.label)}</span><span class="sidebar-chevron">${icon("chevronDown", "h-4 w-4")}</span></button><div x-cloak x-show="open || document.body.classList.contains('sidebar-collapsed')" class="sidebar-group-body mt-3 space-y-1">${groupPages.map((candidate) => { const active = candidate.id === (page.activeNav || page.id); return `<a href="${rootPath(depth, candidate.path)}" class="sidebar-link ${active ? "active" : ""}">${icon(navIconFor(candidate.id), "h-5 w-5 shrink-0")}<span class="sidebar-label text-sm font-semibold">${escapeHtml(candidate.navLabel)}</span></a>`; }).join("")}</div></section>`; }).join("")}
      </div>
      <div class="border-t border-[color:var(--border)] px-4 py-4"><div class="panel-muted flex items-center gap-3 p-3">${avatar("Mina Aksoy", "primary", "sm")}<div class="sidebar-footer-copy min-w-0"><p class="truncate text-sm font-semibold text-[color:var(--text)]">Mina Aksoy</p><p class="truncate text-xs text-[color:var(--text-soft)]">Support Operations</p></div></div></div>
    </aside>
  `;
}

function breadcrumb(page, depth) {
  const parts = [];
  const group = pageGroups.find((item) => item.id === page.group);
  if (group) parts.push(`<span class="text-[color:var(--text-faint)]">${escapeHtml(group.label)}</span>`);
  if (page.parent) {
    const parent = pageMap.get(page.parent);
    parts.push(`<a href="${rootPath(depth, parent.path)}" class="text-[color:var(--text-soft)] transition hover:text-[color:var(--text)]">${escapeHtml(parent.title)}</a>`);
  }
  parts.push(`<span class="font-semibold text-[color:var(--text)]">${escapeHtml(page.title)}</span>`);
  return parts.map((part, index) => index === 0 ? part : `<span class="flex items-center gap-2">${icon("chevronRight", "h-3.5 w-3.5 text-slate-400")}${part}</span>`).join("");
}

function header(page, depth) {
  return `
    <header class="header-shell">
      <div class="mx-auto flex w-full max-w-[1680px] flex-col gap-4 px-4 py-4 lg:px-6 xl:flex-row xl:items-center xl:justify-between">
        <div class="header-context flex min-w-0 items-start gap-3">
          <button type="button" class="inline-flex h-11 w-11 items-center justify-center rounded-2xl border border-[color:var(--border)] bg-white/80 text-[color:var(--text-soft)] transition hover:text-[color:var(--text)] lg:hidden dark:bg-slate-900/60" data-mobile-sidebar-open>${icon("menu", "h-5 w-5")}</button>
          <div class="min-w-0 flex-1"><div class="flex flex-wrap items-center gap-2 text-sm">${breadcrumb(page, depth)}</div><p class="mt-1 hidden text-sm text-[color:var(--text-soft)] md:block">${escapeHtml(page.description)}</p></div>
        </div>
        <div class="header-controls flex items-center gap-3">
          <label class="top-search hidden items-center gap-3 px-4 py-3 xl:flex xl:min-w-[320px]">${icon("search", "h-4 w-4 text-slate-400")}<input type="search" class="w-full border-0 bg-transparent p-0 text-sm text-[color:var(--text)] focus:ring-0" placeholder="Search customers, orders or reports" /></label>
          <button type="button" class="inline-flex h-11 items-center gap-2 rounded-2xl border border-[color:var(--border)] px-4 text-sm font-semibold text-[color:var(--text-soft)] transition hover:text-[color:var(--text)]" data-drawer-open="filters">${icon("filter", "h-4 w-4")} Filters</button>
          <button type="button" class="inline-flex h-11 items-center gap-2 rounded-2xl bg-slate-950 px-4 text-sm font-semibold text-white shadow-lg shadow-slate-900/15 transition hover:bg-slate-800 dark:bg-white dark:text-slate-950" data-modal-open="quick-actions">${icon("plus", "h-4 w-4")} Quick action</button>
          <button type="button" class="inline-flex h-11 items-center gap-2 rounded-2xl border border-[color:var(--border)] px-4 text-sm font-semibold text-[color:var(--text-soft)] transition hover:text-[color:var(--text)]" data-theme-toggle><span data-theme-label>Dark Mode</span></button>
          <div x-data="{open:false}" class="relative"><button type="button" class="inline-flex h-11 w-11 items-center justify-center rounded-2xl border border-[color:var(--border)] bg-white/80 text-[color:var(--text-soft)] transition hover:text-[color:var(--text)] dark:bg-slate-900/60" @click="open=!open">${icon("bell", "h-5 w-5")}</button><div x-cloak x-show="open" @click.outside="open=false" class="table-action-menu absolute right-0 top-14 z-30 w-[340px] p-3"><div class="mb-3 flex items-center justify-between"><h3 class="font-semibold text-[color:var(--text)]">Notifications</h3>${badge("4 new", "primary")}</div><div class="space-y-3">${activities.slice(0, 4).map((item) => `<article class="rounded-2xl border border-[color:var(--border)] p-3"><p class="text-sm font-semibold text-[color:var(--text)]">${escapeHtml(item.title)}</p><p class="mt-1 text-sm text-[color:var(--text-soft)]">${escapeHtml(item.detail)}</p></article>`).join("")}</div></div></div>
          <div x-data="{open:false}" class="relative"><button type="button" class="inline-flex items-center gap-3 rounded-2xl border border-[color:var(--border)] bg-white/80 px-3 py-2 text-left dark:bg-slate-900/60" @click="open=!open">${avatar("Mina Aksoy", "primary", "sm")}<span class="hidden sm:block"><span class="block text-sm font-semibold text-[color:var(--text)]">Mina Aksoy</span><span class="block text-xs text-[color:var(--text-soft)]">Support Ops</span></span></button><div x-cloak x-show="open" @click.outside="open=false" class="table-action-menu absolute right-0 top-14 z-30 w-56 p-2"><a href="${pageHref("user-profile", depth)}" class="flex items-center gap-3 rounded-2xl px-3 py-2 text-sm text-[color:var(--text-soft)] transition hover:bg-[color:var(--bg-muted)] hover:text-[color:var(--text)]">${icon("user", "h-4 w-4")} Profile</a><a href="${pageHref("account-settings", depth)}" class="flex items-center gap-3 rounded-2xl px-3 py-2 text-sm text-[color:var(--text-soft)] transition hover:bg-[color:var(--bg-muted)] hover:text-[color:var(--text)]">${icon("settings", "h-4 w-4")} Settings</a><a href="${pageHref("login", depth)}" class="flex items-center gap-3 rounded-2xl px-3 py-2 text-sm text-[color:var(--danger)] transition hover:bg-[color:var(--danger-soft)]">${icon("lock", "h-4 w-4")} Sign out</a></div></div>
        </div>
      </div>
    </header>
  `;
}

function overlays() {
  return `
    <div class="hidden" data-modal="quick-actions"><div class="modal-backdrop flex items-center justify-center p-4"><div class="modal-shell w-full max-w-2xl p-6"><div class="flex items-start justify-between gap-4"><div><h3 class="font-display text-2xl font-semibold tracking-tight text-[color:var(--text)]">Create a quick action</h3><p class="mt-1 text-sm text-[color:var(--text-soft)]">Launch a reusable workflow for your admin team.</p></div><button type="button" class="inline-flex h-10 w-10 items-center justify-center rounded-2xl border border-[color:var(--border)]" data-modal-close>${icon("chevronRight", "h-4 w-4 rotate-45")}</button></div><div class="mt-6 grid gap-4 md:grid-cols-2"><button type="button" class="rounded-3xl border border-[color:var(--border)] p-5 text-left transition hover:-translate-y-0.5 hover:shadow-xl" data-toast="Customer onboarding playbook created">${iconBox("users", "primary")}<h4 class="mt-4 text-lg font-semibold text-[color:var(--text)]">New customer playbook</h4><p class="mt-2 text-sm leading-6 text-[color:var(--text-soft)]">Generate onboarding tasks, owners and welcome sequences.</p></button><button type="button" class="rounded-3xl border border-[color:var(--border)] p-5 text-left transition hover:-translate-y-0.5 hover:shadow-xl" data-toast="Revenue snapshot exported">${iconBox("analytics", "success")}<h4 class="mt-4 text-lg font-semibold text-[color:var(--text)]">Revenue snapshot</h4><p class="mt-2 text-sm leading-6 text-[color:var(--text-soft)]">Build a shareable board-ready revenue digest in one click.</p></button><button type="button" class="rounded-3xl border border-[color:var(--border)] p-5 text-left transition hover:-translate-y-0.5 hover:shadow-xl" data-toast="Billing recovery flow launched">${iconBox("credit", "warning")}<h4 class="mt-4 text-lg font-semibold text-[color:var(--text)]">Billing recovery</h4><p class="mt-2 text-sm leading-6 text-[color:var(--text-soft)]">Kick off dunning, finance notes and account risk checks.</p></button><button type="button" class="rounded-3xl border border-[color:var(--border)] p-5 text-left transition hover:-translate-y-0.5 hover:shadow-xl" data-toast="Incident channel created">${iconBox("shield", "danger")}<h4 class="mt-4 text-lg font-semibold text-[color:var(--text)]">Security incident room</h4><p class="mt-2 text-sm leading-6 text-[color:var(--text-soft)]">Open an incident workspace with roles, timeline and owners.</p></button></div></div></div></div>
    <div class="hidden" data-drawer="filters"><div class="drawer-backdrop flex justify-end"><div class="drawer-shell flex h-full flex-col p-6"><div class="flex items-start justify-between gap-4"><div><h3 class="font-display text-2xl font-semibold tracking-tight text-[color:var(--text)]">Filters & presets</h3><p class="mt-1 text-sm text-[color:var(--text-soft)]">Save reusable views for revenue, support and operations.</p></div><button type="button" class="inline-flex h-10 w-10 items-center justify-center rounded-2xl border border-[color:var(--border)]" data-drawer-close>${icon("chevronRight", "h-4 w-4 rotate-45")}</button></div><div class="mt-6 space-y-6 overflow-y-auto"><div><label class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Revenue owner</label><select class="select-field"><option>All owners</option><option>Deniz Kaya</option><option>Selin Akca</option><option>Lara Soylu</option></select></div><div><label class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Customer segment</label><select class="select-field"><option>All segments</option><option>Enterprise</option><option>Scale</option><option>Growth</option></select></div><div><label class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Saved preset</label><div class="space-y-3"><button type="button" class="w-full rounded-3xl border border-[color:var(--border)] p-4 text-left" data-toast="Revenue leadership preset applied"><p class="text-sm font-semibold text-[color:var(--text)]">Leadership revenue view</p><p class="mt-1 text-sm text-[color:var(--text-soft)]">Shows MRR, expansion and churn risks only.</p></button><button type="button" class="w-full rounded-3xl border border-[color:var(--border)] p-4 text-left" data-toast="Support SLA preset applied"><p class="text-sm font-semibold text-[color:var(--text)]">Support SLA watch</p><p class="mt-1 text-sm text-[color:var(--text-soft)]">Highlights open high-priority tickets due in the next 4 hours.</p></button></div></div><div class="space-y-4"><label class="flex items-center justify-between gap-4 rounded-3xl border border-[color:var(--border)] p-4"><div><p class="text-sm font-semibold text-[color:var(--text)]">Only at-risk accounts</p><p class="mt-1 text-sm text-[color:var(--text-soft)]">Surface customers with falling adoption signals.</p></div><span><input type="checkbox" class="toggle-input sr-only" checked /><span class="toggle-switch"></span></span></label><label class="flex items-center justify-between gap-4 rounded-3xl border border-[color:var(--border)] p-4"><div><p class="text-sm font-semibold text-[color:var(--text)]">Include archived reports</p><p class="mt-1 text-sm text-[color:var(--text-soft)]">Add exported and historical views to search.</p></div><span><input type="checkbox" class="toggle-input sr-only" /><span class="toggle-switch"></span></span></label></div></div><div class="mt-6 flex gap-3"><button type="button" class="flex-1 rounded-2xl bg-blue-600 px-4 py-3 text-sm font-semibold text-white shadow-lg shadow-blue-600/20" data-toast="Filter preset saved">Save preset</button><button type="button" class="flex-1 rounded-2xl border border-[color:var(--border)] px-4 py-3 text-sm font-semibold text-[color:var(--text-soft)]" data-drawer-close>Close</button></div></div></div></div>
  `;
}

function baseHead(page, depth) {
  return `
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>${escapeHtml(page.title)} - KA Nexus Admin</title>
    <meta name="description" content="${escapeHtml(page.description)}" />
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&family=Outfit:wght@500;600;700&display=swap" rel="stylesheet" />
    <script>try { var savedTheme = localStorage.getItem("ka-nexus-theme"); var prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches; if (savedTheme === "dark" || (!savedTheme && prefersDark)) { document.documentElement.classList.add("dark"); } } catch (error) {}</script>
    <script>window.tailwind = window.tailwind || {}; window.tailwind.config = { darkMode: "class", theme: { extend: { fontFamily: { sans: ["Manrope", "sans-serif"], display: ["Outfit", "sans-serif"] }, boxShadow: { soft: "0 18px 45px rgba(15, 23, 42, 0.08)", card: "0 10px 30px rgba(15, 23, 42, 0.05)" } } } };</script>
    <script src="https://cdn.tailwindcss.com?plugins=forms,typography,aspect-ratio"></script>
    <link rel="stylesheet" href="${rootPath(depth, "assets/css/app.css")}" />
  `;
}

function appShell(page, content, chartConfigs = []) {
  const depth = depthFor(page.path);
  return `<!DOCTYPE html><html lang="en"><head>${baseHead(page, depth)}</head><body class="text-[color:var(--text)]"><div class="fixed inset-0 z-30 hidden bg-slate-950/40 lg:hidden" data-mobile-overlay></div>${sidebar(page, depth)}<div class="shell-main min-h-screen">${header(page, depth)}<main class="px-4 py-6 lg:px-6"><div class="mx-auto flex w-full max-w-[1680px] min-w-0 flex-col gap-6">${content}</div></main><footer class="px-4 pb-8 pt-2 text-sm text-[color:var(--text-faint)] lg:px-6"><div class="mx-auto w-full max-w-[1680px]"><div class="flex flex-col gap-2 rounded-3xl border border-[color:var(--border)] bg-white/60 px-5 py-4 backdrop-blur dark:bg-slate-900/40 md:flex-row md:items-center md:justify-between"><p>KA Nexus Admin template. Built with HTML, TailwindCSS, Alpine.js, Chart.js and vanilla JavaScript.</p><p><span data-current-year></span> KA Nexus. All demo data is fictional.</p></div></div></footer></div>${overlays()}<script>window.kaCharts = ${JSON.stringify(chartConfigs)};</script><script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script><script src="https://cdn.jsdelivr.net/npm/chart.js"></script><script src="${rootPath(depth, "assets/js/app.js")}"></script></body></html>`;
}

function authShell(page, content) {
  const depth = depthFor(page.path);
  return `<!DOCTYPE html><html lang="en"><head>${baseHead(page, depth)}</head><body><main class="auth-shell"><section class="auth-visual flex flex-col justify-between p-10 text-white"><a href="${pageHref("dashboard-overview", depth)}" class="inline-flex items-center gap-3"><span class="flex h-12 w-12 items-center justify-center rounded-2xl bg-white/10 text-white">${icon("logo", "h-6 w-6")}</span><span><span class="block font-display text-lg font-semibold">KA Nexus</span><span class="block text-sm text-slate-300">Enterprise admin template</span></span></a><div class="max-w-xl"><div class="inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/5 px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.2em] text-slate-300">${icon("sparkles", "h-4 w-4")}Premium control layer</div><h1 class="mt-6 font-display text-4xl font-semibold tracking-tight">Real-product admin UI for SaaS, CRM, analytics and commerce operations.</h1><p class="mt-5 max-w-lg text-base leading-7 text-slate-300">KA Nexus Admin ships with modular dashboards, management views, auth flows, system states and reusable enterprise UI patterns.</p></div><div class="grid gap-4 sm:grid-cols-2"><div class="auth-grid-card p-5"><p class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-300">Revenue visibility</p><p class="mt-3 text-3xl font-semibold">$142.8k</p><p class="mt-2 text-sm text-slate-300">MRR with churn, expansion and ticket health in one place.</p></div><div class="auth-grid-card p-5"><p class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-300">Ops quality</p><p class="mt-3 text-3xl font-semibold">98.4%</p><p class="mt-2 text-sm text-slate-300">Workspace uptime, billing success and SLA compliance overview.</p></div></div></section><section class="flex items-center justify-center px-6 py-10 lg:px-12"><div class="w-full max-w-xl">${content}</div></section></main><script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script><script src="${rootPath(depth, "assets/js/app.js")}"></script></body></html>`;
}

function specialShell(page, content) {
  const depth = depthFor(page.path);
  return `<!DOCTYPE html><html lang="en"><head>${baseHead(page, depth)}</head><body>${content}<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script><script src="${rootPath(depth, "assets/js/app.js")}"></script></body></html>`;
}

function chartLine(id, labels, datasets, options = {}) { return { id, type: "line", data: { labels, datasets }, options }; }
function chartBar(id, labels, datasets, options = {}) { return { id, type: "bar", data: { labels, datasets }, options }; }
function chartDoughnut(id, labels, datasets, options = {}) { return { id, type: "doughnut", data: { labels, datasets }, options }; }
function chartRadar(id, labels, datasets, options = {}) { return { id, type: "radar", data: { labels, datasets }, options }; }
function chartCard(id, title, description, height = "320px", action = "") { return panel(title, description, `<div class="relative" style="height:${height}"><canvas id="${id}"></canvas></div>`, action); }

function renderDashboardOverview(page) {
  const revenueRows = transactions.slice(0, 5).map((item) => [
    `<div class="flex items-center gap-3">${iconBox("credit", item.amount >= 0 ? "success" : "danger")}<div><p class="font-semibold text-[color:var(--text)]">${escapeHtml(item.reference)}</p><p class="mt-1 text-xs uppercase tracking-[0.18em] text-[color:var(--text-faint)]">${escapeHtml(item.type)}</p></div></div>`,
    item.amount >= 0 ? badge(item.status, "success", "status") : badge(item.status, "danger", "status"),
    `<span class="font-semibold text-[color:var(--text)]">${currency(item.amount)}</span>`,
  ]);

  const content = `
    ${heroBlock(page, [
      { label: "Net Revenue", value: "$142.8k", delta: "+12.6%", tone: "success" },
      { label: "Active Accounts", value: "4,892", delta: "+7.4%", tone: "primary" },
      { label: "Expansion MRR", value: "$21.4k", delta: "+4.1%", tone: "info" },
      { label: "Open Tickets", value: "38", delta: "-8.2%", tone: "warning" },
    ], `<button type="button" class="inline-flex items-center gap-2 rounded-2xl bg-blue-600 px-4 py-3 text-sm font-semibold text-white shadow-lg shadow-blue-600/20" data-modal-open="quick-actions">${icon("plus", "h-4 w-4")} Create report</button><button type="button" class="inline-flex items-center gap-2 rounded-2xl border border-[color:var(--border)] px-4 py-3 text-sm font-semibold text-[color:var(--text-soft)]" data-toast="Board export ready">${icon("download", "h-4 w-4")} Export board</button>`)}
    <div class="grid gap-4 md:grid-cols-2 xl:grid-cols-4">${[
      { label: "Total Revenue", value: "$1.82M", delta: "+18.4%", tone: "success", iconName: "analytics", hint: "vs last quarter" },
      { label: "Monthly Recurring Revenue", value: "$142.8k", delta: "+12.6%", tone: "primary", iconName: "credit", hint: "current run rate" },
      { label: "Active Users", value: "24,918", delta: "+8.7%", tone: "info", iconName: "users", hint: "weekly active seats" },
      { label: "Conversion Rate", value: "5.42%", delta: "+0.8 pts", tone: "success", iconName: "trendUp", hint: "paid trial to active" },
      { label: "New Customers", value: "186", delta: "+14.3%", tone: "primary", iconName: "plus", hint: "last 30 days" },
      { label: "Churn Rate", value: "1.8%", delta: "-0.3 pts", tone: "warning", iconName: "trendDown", hint: "gross logo churn" },
      { label: "Traffic Overview", value: "482k", delta: "+22.1%", tone: "info", iconName: "activity", hint: "sessions this month" },
      { label: "Subscription Growth", value: "+312", delta: "+17.8%", tone: "success", iconName: "dashboard", hint: "net new subscribers" },
    ].map(statCard).join("")}</div>
    <div class="grid gap-6 xl:grid-cols-[1.35fr_.65fr]">${chartCard("overviewRevenueChart", "Revenue performance", "Recurring revenue, expansion and forecasts by month.", "340px", badge("Live", "success"))}${panel("Subscription distribution", "Plan mix across your current subscriber base.", `<div class="relative mb-6" style="height:280px"><canvas id="overviewSubscriptionChart"></canvas></div><div class="space-y-4">${progressRow("Enterprise", 32, "warning")}${progressRow("Scale", 41, "primary")}${progressRow("Growth", 19, "success")}${progressRow("Starter", 8, "info")}</div>`, badge("4 plans", "info"))}</div>
    <div class="grid gap-6 xl:grid-cols-[1.1fr_.9fr]">${chartCard("overviewUsersChart", "User growth", "Monthly active seats and newly activated workspaces.", "320px", badge("Updated 10m ago", "primary"))}${panel("Recent activity", "Live operating log across revenue, support and security workflows.", timeline(activities), `<a href="${pageHref("support-tickets", depthFor(page.path))}" class="text-sm font-semibold text-blue-600">View all</a>`)}</div>
    <div class="grid gap-6 xl:grid-cols-[1.1fr_.9fr]">${panel("Recent transactions", "Latest money movement across subscriptions and payouts.", simpleTable(["Reference", "Status", "Amount"], revenueRows), `<a href="${pageHref("transactions", depthFor(page.path))}" class="text-sm font-semibold text-blue-600">Open ledger</a>`)}${panel("Support ticket summary", "Ticket load and response momentum across the customer support queue.", `<div class="space-y-5"><div class="grid gap-4 sm:grid-cols-2"><div class="rounded-3xl border border-[color:var(--border)] p-4"><p class="text-xs font-semibold uppercase tracking-[0.18em] text-[color:var(--text-faint)]">Open</p><p class="mt-2 text-3xl font-semibold text-[color:var(--text)]">18</p><p class="mt-2 text-sm text-[color:var(--text-soft)]">3 high-priority tickets are nearing SLA.</p></div><div class="rounded-3xl border border-[color:var(--border)] p-4"><p class="text-xs font-semibold uppercase tracking-[0.18em] text-[color:var(--text-faint)]">Resolved today</p><p class="mt-2 text-3xl font-semibold text-[color:var(--text)]">27</p><p class="mt-2 text-sm text-[color:var(--text-soft)]">Median first reply in 22 minutes.</p></div></div>${progressRow("SLA met", 94, "success")}${progressRow("Escalation backlog", 21, "warning")}${progressRow("Self-serve deflection", 56, "info")}</div>`, `<a href="${pageHref("ticket-detail", depthFor(page.path))}" class="text-sm font-semibold text-blue-600">Open latest ticket</a>`)}</div>
  `;

  const charts = [
    chartLine("overviewRevenueChart", ["Sep", "Oct", "Nov", "Dec", "Jan", "Feb", "Mar"], [
      { label: "MRR", data: [92000, 101000, 109000, 117000, 125000, 136000, 142800], borderColor: "theme:primary", backgroundColor: "theme:primarySoft", fill: true, tension: 0.42, borderWidth: 3, pointRadius: 0 },
      { label: "Expansion", data: [8000, 9200, 9700, 11100, 12600, 18900, 21400], borderColor: "theme:success", backgroundColor: "theme:successSoft", fill: false, tension: 0.42, borderWidth: 2, pointRadius: 0 },
    ]),
    chartDoughnut("overviewSubscriptionChart", ["Enterprise", "Scale", "Growth", "Starter"], [{ data: [32, 41, 19, 8], backgroundColor: ["theme:warning", "theme:primary", "theme:success", "theme:info"], borderWidth: 0, hoverOffset: 8 }], { cutout: "72%" }),
    chartBar("overviewUsersChart", ["Oct", "Nov", "Dec", "Jan", "Feb", "Mar"], [
      { label: "Activated seats", data: [1240, 1310, 1490, 1720, 1880, 2140], backgroundColor: "theme:primary", borderRadius: 12 },
      { label: "New workspaces", data: [42, 48, 60, 71, 88, 103], backgroundColor: "theme:info", borderRadius: 12 },
    ]),
  ];

  return { content, charts };
}

function renderAnalyticsDashboard(page) {
  const content = `
    ${heroBlock(page, [
      { label: "Sessions", value: "482k", delta: "+22.1%", tone: "primary" },
      { label: "Qualified Leads", value: "18,240", delta: "+14.2%", tone: "success" },
      { label: "Engaged Accounts", value: "3,204", delta: "+9.8%", tone: "info" },
      { label: "Bounce Rate", value: "28.4%", delta: "-3.1%", tone: "warning" },
    ], `<button type="button" class="inline-flex items-center gap-2 rounded-2xl bg-blue-600 px-4 py-3 text-sm font-semibold text-white" data-toast="Attribution report scheduled">${icon("plus", "h-4 w-4")} Schedule report</button><button type="button" class="inline-flex items-center gap-2 rounded-2xl border border-[color:var(--border)] px-4 py-3 text-sm font-semibold text-[color:var(--text-soft)]" data-toast="Analytics notes shared">${icon("download", "h-4 w-4")} Share snapshot</button>`)}
    <div class="grid gap-6 xl:grid-cols-[1.3fr_.7fr]">${chartCard("analyticsTrafficChart", "Traffic overview", "Unique visitors versus qualified sessions.", "340px")}${chartCard("analyticsAcquisitionChart", "Acquisition mix", "Channel contribution to pipeline-ready visits.", "340px", badge("Weighted", "info"))}</div>
    <div class="grid gap-6 xl:grid-cols-[0.9fr_1.1fr]">${panel("Session quality", "Behavioral strength by acquisition channel.", `<div class="relative" style="height:320px"><canvas id="analyticsRadarChart"></canvas></div>`)}${panel("Cohort performance", "Seven-day cohort conversion based on signup month.", simpleTable(["Cohort", "Activation", "Upgrade", "30d retention"], [["Jan 2026", `<span class="font-semibold text-[color:var(--text)]">58%</span>`, `<span class="font-semibold text-[color:var(--text)]">22%</span>`, `<span class="font-semibold text-[color:var(--text)]">81%</span>`], ["Feb 2026", `<span class="font-semibold text-[color:var(--text)]">61%</span>`, `<span class="font-semibold text-[color:var(--text)]">25%</span>`, `<span class="font-semibold text-[color:var(--text)]">84%</span>`], ["Mar 2026", `<span class="font-semibold text-[color:var(--text)]">64%</span>`, `<span class="font-semibold text-[color:var(--text)]">28%</span>`, `<span class="font-semibold text-[color:var(--text)]">--</span>`]]))}</div>
    <div class="grid gap-6 xl:grid-cols-3">${panel("Top insights", "Auto-generated highlights from the last 30 days.", activityList([{ title: "Organic traffic produced the strongest qualified conversion this month.", detail: "Organic sessions are up 18 percent while bounce fell below 24 percent.", time: "Insight", tone: "success" }, { title: "Partner referrals over-index on enterprise deal creation.", detail: "41 percent of enterprise opportunities in March originated from partner-driven visits.", time: "Insight", tone: "primary" }, { title: "Paid social volume improved, but follow-through is still soft.", detail: "High reach, low activation. Campaign landing pages need stronger segment fit.", time: "Insight", tone: "warning" }]))}${panel("Funnel health", "Performance across key lifecycle stages.", `<div class="space-y-5">${progressRow("Visitor to signup", 18, "primary")}${progressRow("Signup to trial", 57, "info")}${progressRow("Trial to paid", 34, "success")}${progressRow("Paid to expansion", 12, "warning")}</div>`)}${panel("Segment split", "Share of qualified pipeline by company size.", `<div class="grid gap-4">${[["SMB", "36%", "primary"], ["Mid-market", "42%", "success"], ["Enterprise", "22%", "warning"]].map(([label, value, tone]) => `<div class="rounded-3xl border border-[color:var(--border)] p-4"><div class="flex items-center justify-between gap-3"><p class="text-sm font-semibold text-[color:var(--text)]">${label}</p>${badge(value, tone)}</div><p class="mt-2 text-sm text-[color:var(--text-soft)]">Qualified pipeline contribution</p></div>`).join("")}</div>`)}</div>
  `;

  const charts = [
    chartLine("analyticsTrafficChart", ["Week 1", "Week 2", "Week 3", "Week 4", "Week 5", "Week 6"], [
      { label: "Unique visitors", data: [62000, 68000, 70500, 74100, 79600, 84100], borderColor: "theme:primary", backgroundColor: "theme:primarySoft", fill: true, tension: 0.42, borderWidth: 3, pointRadius: 0 },
      { label: "Qualified sessions", data: [14200, 15100, 15880, 16220, 17040, 18240], borderColor: "theme:success", backgroundColor: "theme:successSoft", fill: false, tension: 0.42, borderWidth: 2, pointRadius: 0 },
    ]),
    chartBar("analyticsAcquisitionChart", ["Organic", "Direct", "Paid Search", "Paid Social", "Partner", "Email"], [{ label: "Qualified visits", data: [4200, 3400, 2900, 2100, 3600, 2040], backgroundColor: ["theme:success", "theme:primary", "theme:warning", "theme:info", "theme:primary", "theme:success"], borderRadius: 12 }], { plugins: { legend: { display: false } } }),
    chartRadar("analyticsRadarChart", ["Engagement", "Conversion", "Retention", "Depth", "Latency", "Return visits"], [
      { label: "Organic", data: [84, 76, 71, 80, 68, 82], borderColor: "theme:primary", backgroundColor: "theme:primarySoft", fill: true },
      { label: "Partner", data: [72, 83, 78, 69, 71, 75], borderColor: "theme:warning", backgroundColor: "theme:warningSoft", fill: true },
    ]),
  ];

  return { content, charts };
}

function renderCrmDashboard(page) {
  const content = `
    ${heroBlock(page, [
      { label: "Open pipeline", value: "$3.84M", delta: "+9.2%", tone: "primary" },
      { label: "Renewals due", value: "$412k", delta: "17 accounts", tone: "warning" },
      { label: "Win rate", value: "31.4%", delta: "+2.3 pts", tone: "success" },
      { label: "Health score", value: "86.2", delta: "+4.7%", tone: "info" },
    ], `<button type="button" class="inline-flex items-center gap-2 rounded-2xl bg-blue-600 px-4 py-3 text-sm font-semibold text-white" data-toast="Forecast snapshot created">${icon("plus", "h-4 w-4")} Forecast update</button><button type="button" class="inline-flex items-center gap-2 rounded-2xl border border-[color:var(--border)] px-4 py-3 text-sm font-semibold text-[color:var(--text-soft)]" data-toast="Renewal board shared">${icon("download", "h-4 w-4")} Share renewal board</button>`)}
    <div class="grid gap-6 xl:grid-cols-[1.15fr_.85fr]">${chartCard("crmPipelineChart", "Pipeline by stage", "Weighted value across the current quarter.", "340px")}${panel("Account health", "Priority customer accounts with the largest revenue exposure.", activityList(customers.slice(0, 4).map((customer) => ({ title: `${customer.company} health is ${customer.health}/100`, detail: `${customer.owner} owns the relationship. Renewal on ${customer.renewal}.`, time: customer.status, tone: customer.status === "Risk" ? "warning" : customer.status === "Renewal" ? "danger" : "success" }))))}</div>
    <div class="grid gap-6 xl:grid-cols-[0.9fr_1.1fr]">${chartCard("crmForecastChart", "Forecast confidence", "Commit, best case and pipeline coverage over time.", "320px")}${panel("Upcoming renewals", "High-priority accounts renewing in the next 30 days.", simpleTable(["Customer", "Plan", "Owner", "Renewal"], customers.slice(0, 5).map((customer) => [`<div class="flex items-center gap-3">${avatar(customer.name, "primary", "sm")}<div><p class="font-semibold text-[color:var(--text)]">${escapeHtml(customer.company)}</p><p class="text-xs uppercase tracking-[0.18em] text-[color:var(--text-faint)]">${escapeHtml(customer.status)}</p></div></div>`, escapeHtml(customer.plan), escapeHtml(customer.owner), escapeHtml(customer.renewal)])))}</div>
  `;

  const charts = [
    chartBar("crmPipelineChart", ["Prospect", "Qualified", "Proposal", "Negotiation", "Commit"], [{ label: "Weighted value", data: [420000, 610000, 820000, 950000, 1040000], backgroundColor: ["theme:info", "theme:primary", "theme:success", "theme:warning", "theme:danger"], borderRadius: 12 }], { plugins: { legend: { display: false } } }),
    chartLine("crmForecastChart", ["Jan", "Feb", "Mar", "Apr", "May", "Jun"], [
      { label: "Commit", data: [280000, 320000, 348000, 371000, 390000, 408000], borderColor: "theme:success", backgroundColor: "theme:successSoft", fill: true, tension: 0.4, pointRadius: 0, borderWidth: 3 },
      { label: "Best case", data: [360000, 402000, 438000, 482000, 524000, 560000], borderColor: "theme:primary", backgroundColor: "theme:primarySoft", fill: false, tension: 0.4, pointRadius: 0, borderWidth: 2 },
    ]),
  ];

  return { content, charts };
}

function renderEcommerceDashboard(page) {
  const topProducts = products.slice(0, 5).map((product) => [
    `<div><p class="font-semibold text-[color:var(--text)]">${escapeHtml(product.name)}</p><p class="mt-1 text-xs uppercase tracking-[0.18em] text-[color:var(--text-faint)]">${escapeHtml(product.category)}</p></div>`,
    `<span class="font-semibold text-[color:var(--text)]">${currency(product.revenue)}</span>`,
    badge(product.status, product.status === "Draft" ? "warning" : product.status === "Beta" ? "info" : "success", "status"),
  ]);

  const content = `
    ${heroBlock(page, [
      { label: "Gross sales", value: "$286.4k", delta: "+18.3%", tone: "success" },
      { label: "Orders", value: "1,942", delta: "+11.6%", tone: "primary" },
      { label: "Avg order value", value: "$147", delta: "+4.2%", tone: "info" },
      { label: "Return rate", value: "2.1%", delta: "-0.6 pts", tone: "warning" },
    ])}
    <div class="grid gap-6 xl:grid-cols-[1.2fr_.8fr]">${chartCard("commerceSalesChart", "Sales trend", "GMV and order volume over the last six months.", "340px")}${chartCard("commerceCategoryChart", "Category share", "Revenue contribution by product family.", "340px")}</div>
    <div class="grid gap-6 xl:grid-cols-[1.1fr_.9fr]">${panel("Top products", "Products generating the most recurring monthly revenue.", simpleTable(["Product", "Revenue", "Status"], topProducts), `<a href="${pageHref("products-list", depthFor(page.path))}" class="text-sm font-semibold text-blue-600">Open catalog</a>`)}${panel("Fulfillment summary", "Operational throughput for your delivery pipeline.", `<div class="space-y-5">${progressRow("Delivered", 74, "success")}${progressRow("Shipped", 16, "primary")}${progressRow("Pending", 7, "warning")}${progressRow("Returned", 3, "danger")}</div><div class="mt-6 grid gap-4 sm:grid-cols-2"><div class="rounded-3xl border border-[color:var(--border)] p-4"><p class="text-xs font-semibold uppercase tracking-[0.18em] text-[color:var(--text-faint)]">Warehouse latency</p><p class="mt-2 text-3xl font-semibold text-[color:var(--text)]">1.8h</p><p class="mt-2 text-sm text-[color:var(--text-soft)]">Median dispatch lead time this week.</p></div><div class="rounded-3xl border border-[color:var(--border)] p-4"><p class="text-xs font-semibold uppercase tracking-[0.18em] text-[color:var(--text-faint)]">CSAT</p><p class="mt-2 text-3xl font-semibold text-[color:var(--text)]">4.7/5</p><p class="mt-2 text-sm text-[color:var(--text-soft)]">Post-delivery feedback across fulfilled orders.</p></div></div>`)} </div>
  `;

  const charts = [
    chartLine("commerceSalesChart", ["Oct", "Nov", "Dec", "Jan", "Feb", "Mar"], [
      { label: "GMV", data: [164000, 182000, 205000, 221000, 247000, 286400], borderColor: "theme:primary", backgroundColor: "theme:primarySoft", fill: true, tension: 0.42, borderWidth: 3, pointRadius: 0 },
      { label: "Orders", data: [1120, 1260, 1390, 1510, 1690, 1942], borderColor: "theme:success", backgroundColor: "theme:successSoft", fill: false, tension: 0.42, borderWidth: 2, pointRadius: 0, yAxisID: "y1" },
    ], { scales: { y1: { position: "right", border: { display: false }, grid: { display: false }, ticks: { color: "theme:textFaint" } } } }),
    chartDoughnut("commerceCategoryChart", ["Analytics", "CRM", "Commerce", "Finance", "Security"], [{ data: [28, 24, 21, 14, 13], backgroundColor: ["theme:primary", "theme:success", "theme:info", "theme:warning", "theme:danger"], borderWidth: 0, hoverOffset: 8 }], { cutout: "70%" }),
  ];

  return { content, charts };
}

function customerRows() {
  return customers.map((customer) => ({
    search: `${customer.id} ${customer.name} ${customer.company} ${customer.email} ${customer.plan} ${customer.status}`.toLowerCase(),
    filters: { status: customer.status, plan: customer.plan },
    sort: { customer: customer.name, company: customer.company, plan: customer.plan, mrr: customer.mrr, health: customer.health },
    cells: {
      customer: `<div class="flex items-center gap-3">${avatar(customer.name, "primary", "sm")}<div><p class="font-semibold text-[color:var(--text)]">${escapeHtml(customer.name)}</p><p class="mt-1 text-xs uppercase tracking-[0.18em] text-[color:var(--text-faint)]">${escapeHtml(customer.id)}</p></div></div>`,
      company: `<div><p class="font-semibold text-[color:var(--text)]">${escapeHtml(customer.company)}</p><p class="mt-1 text-sm text-[color:var(--text-soft)]">${escapeHtml(customer.email)}</p></div>`,
      plan: badge(customer.plan, customer.plan === "Enterprise" ? "warning" : customer.plan === "Scale" ? "primary" : customer.plan === "Growth" ? "success" : "info"),
      mrr: `<span class="font-semibold text-[color:var(--text)]">${currency(customer.mrr)}</span>`,
      status: badge(customer.status, customer.status === "Active" ? "success" : customer.status === "Trial" ? "info" : customer.status === "Risk" ? "warning" : customer.status === "Renewal" ? "danger" : "primary", "status"),
      health: `<span class="font-semibold text-[color:var(--text)]">${customer.health}</span>`,
    },
  }));
}

function renderCustomersList(page) {
  const content = `
    ${heroBlock(page, [
      { label: "Customers", value: "1,248", delta: "+8.2%", tone: "primary" },
      { label: "Healthy accounts", value: "82%", delta: "+3.4%", tone: "success" },
      { label: "At-risk MRR", value: "$18.4k", delta: "-6.1%", tone: "warning" },
      { label: "Renewals due", value: "24", delta: "next 30 days", tone: "info" },
    ])}
    ${renderDataTable({
      title: "Customer accounts",
      description: "Search, filter and action every customer record from a single table.",
      columns: [
        { key: "customer", label: "Customer", sortable: true },
        { key: "company", label: "Company", sortable: true },
        { key: "plan", label: "Plan", sortable: true },
        { key: "mrr", label: "MRR", sortable: true, type: "number" },
        { key: "status", label: "Status", sortable: true },
        { key: "health", label: "Health", sortable: true, type: "number" },
      ],
      rows: customerRows(),
      filters: [
        { key: "status", label: "All statuses", options: ["Active", "Trial", "Risk", "Paused", "Onboarding", "Renewal"] },
        { key: "plan", label: "All plans", options: ["Starter", "Growth", "Scale", "Enterprise"] },
      ],
      searchPlaceholder: "Search customer, company or plan",
      sortKey: "mrr",
    })}
  `;
  return { content, charts: [] };
}

function renderCustomerDetail(page) {
  const customer = customers[0];
  const content = `
    ${heroBlock(page, [
      { label: "MRR", value: currency(customer.mrr), delta: "+9.4%", tone: "success" },
      { label: "Health score", value: String(customer.health), delta: "Excellent", tone: "primary" },
      { label: "Seats", value: String(customer.seats), delta: "+6 last month", tone: "info" },
      { label: "Renewal", value: customer.renewal, delta: "In 6 days", tone: "warning" },
    ], `<a href="${pageHref("customers-list", depthFor(page.path))}" class="inline-flex items-center gap-2 rounded-2xl border border-[color:var(--border)] px-4 py-3 text-sm font-semibold text-[color:var(--text-soft)]">${icon("chevronRight", "h-4 w-4 rotate-180")} Back to customers</a><button type="button" class="inline-flex items-center gap-2 rounded-2xl bg-blue-600 px-4 py-3 text-sm font-semibold text-white" data-toast="Customer success note saved">${icon("plus", "h-4 w-4")} Add note</button>`)}
    <div class="grid gap-6 xl:grid-cols-[1.1fr_.9fr]">${panel("Account snapshot", "Operating context for the selected customer.", `<div class="flex items-start gap-4 rounded-3xl border border-[color:var(--border)] bg-[color:var(--bg-muted)]/50 p-5">${avatar(customer.name, "primary", "lg")}<div><h3 class="font-display text-2xl font-semibold tracking-tight text-[color:var(--text)]">${escapeHtml(customer.company)}</h3><p class="mt-1 text-sm text-[color:var(--text-soft)]">${escapeHtml(customer.email)} • Owner: ${escapeHtml(customer.owner)}</p><div class="mt-4 flex flex-wrap gap-2">${badge(customer.plan, "primary")}${badge(customer.status, "success", "status")}${badge(customer.location, "info")}</div></div></div><div class="mt-6" x-data="{tab:'overview'}"><div class="flex flex-wrap gap-2"><button type="button" class="rounded-2xl border border-[color:var(--border)] px-4 py-2 text-sm font-semibold" @click="tab='overview'">Overview</button><button type="button" class="rounded-2xl border border-[color:var(--border)] px-4 py-2 text-sm font-semibold" @click="tab='billing'">Billing</button><button type="button" class="rounded-2xl border border-[color:var(--border)] px-4 py-2 text-sm font-semibold" @click="tab='activity'">Activity</button></div><div class="mt-5" x-show="tab==='overview'">${keyValueList([{ label: "Workspace owner", value: escapeHtml(customer.owner) }, { label: "Lifecycle stage", value: escapeHtml(customer.status) }, { label: "Plan", value: escapeHtml(customer.plan) }, { label: "Next renewal", value: escapeHtml(customer.renewal) }])}</div><div class="mt-5" x-show="tab==='billing'">${keyValueList([{ label: "Payment method", value: "Visa ending 4021" }, { label: "Billing frequency", value: "Annual prepaid" }, { label: "Last invoice", value: "INV-2109" }, { label: "Collections health", value: "No issues" }])}</div><div class="mt-5" x-show="tab==='activity'">${timeline(activities.slice(0, 3))}</div></div>`)}${panel("Customer timeline", "Recent lifecycle and support activity for the account.", timeline([{ title: "Renewal prep started", detail: "Revenue owner opened the annual commit checklist.", time: "Today", tone: "primary" }, { title: "Feature usage increased", detail: "Workspace templates usage rose by 16 percent week over week.", time: "Yesterday", tone: "success" }, { title: "Invoice INV-2109 settled", detail: "Annual invoice was paid on time via Visa.", time: "3 days ago", tone: "info" }]))}</div>
    ${panel("Recent invoices", "Finance history for the customer account.", simpleTable(["Invoice", "Status", "Amount", "Due"], invoices.slice(0, 4).map((invoice) => [`<a class="font-semibold text-[color:var(--text)]" href="${pageHref("invoice-detail", depthFor(page.path))}">${escapeHtml(invoice.id)}</a>`, badge(invoice.status, invoice.status === "Paid" ? "success" : invoice.status === "Overdue" ? "danger" : "warning", "status"), `<span class="font-semibold text-[color:var(--text)]">${currency(invoice.amount)}</span>`, escapeHtml(invoice.dueDate)])))}
  `;
  return { content, charts: [] };
}

function orderRows() {
  return orders.map((order) => ({
    search: `${order.id} ${order.customer} ${order.company} ${order.payment} ${order.fulfillment}`.toLowerCase(),
    filters: { payment: order.payment, fulfillment: order.fulfillment },
    sort: { order: order.id, customer: order.customer, items: order.items, amount: order.amount, payment: order.payment, fulfillment: order.fulfillment },
    cells: {
      order: `<a href="${pageHref("order-detail", 2)}" class="font-semibold text-[color:var(--text)]">${escapeHtml(order.id)}</a>`,
      customer: `<div><p class="font-semibold text-[color:var(--text)]">${escapeHtml(order.customer)}</p><p class="mt-1 text-sm text-[color:var(--text-soft)]">${escapeHtml(order.company)}</p></div>`,
      items: `<span class="font-semibold text-[color:var(--text)]">${order.items}</span>`,
      amount: `<span class="font-semibold text-[color:var(--text)]">${currency(order.amount)}</span>`,
      payment: badge(order.payment, order.payment === "Paid" ? "success" : order.payment === "Pending" ? "warning" : order.payment === "Refunded" ? "info" : "danger", "status"),
      fulfillment: badge(order.fulfillment, order.fulfillment === "Delivered" ? "success" : order.fulfillment === "Shipped" || order.fulfillment === "Processing" ? "primary" : order.fulfillment === "Pending" ? "warning" : "danger", "status"),
    },
  }));
}

function renderOrdersList(page) {
  const content = `
    ${heroBlock(page, [
      { label: "Orders today", value: "184", delta: "+13.2%", tone: "primary" },
      { label: "AOV", value: "$147", delta: "+4.2%", tone: "success" },
      { label: "Pending fulfillment", value: "28", delta: "within SLA", tone: "info" },
      { label: "Refund rate", value: "1.2%", delta: "-0.4 pts", tone: "warning" },
    ])}
    ${renderDataTable({
      title: "Order operations",
      description: "Track payment, fulfillment and channel performance in one list.",
      columns: [
        { key: "order", label: "Order", sortable: true },
        { key: "customer", label: "Customer", sortable: true },
        { key: "items", label: "Items", sortable: true, type: "number" },
        { key: "amount", label: "Amount", sortable: true, type: "number" },
        { key: "payment", label: "Payment", sortable: true },
        { key: "fulfillment", label: "Fulfillment", sortable: true },
      ],
      rows: orderRows(),
      filters: [
        { key: "payment", label: "All payments", options: ["Paid", "Pending", "Refunded", "Failed"] },
        { key: "fulfillment", label: "All fulfillment", options: ["Delivered", "Processing", "Pending", "Shipped", "Returned", "Blocked"] },
      ],
      searchPlaceholder: "Search order, customer or payment",
      sortKey: "amount",
    })}
  `;
  return { content, charts: [] };
}

function renderOrderDetail(page) {
  const order = orders[1];
  const content = `
    ${heroBlock(page, [
      { label: "Order value", value: currency(order.amount), delta: "Paid", tone: "success" },
      { label: "Items", value: String(order.items), delta: "3 bundles + 5 seats", tone: "info" },
      { label: "Channel", value: order.channel, delta: "Sales-assisted", tone: "primary" },
      { label: "Fulfillment", value: order.fulfillment, delta: "In progress", tone: "warning" },
    ])}
    <div class="grid gap-6 xl:grid-cols-[1.1fr_.9fr]">${panel("Order summary", "Commercial and customer context for this order.", keyValueList([{ label: "Customer", value: escapeHtml(order.customer) }, { label: "Company", value: escapeHtml(order.company) }, { label: "Placed on", value: escapeHtml(order.date) }, { label: "Payment status", value: badge(order.payment, "success", "status") }, { label: "Fulfillment status", value: badge(order.fulfillment, "primary", "status") }, { label: "Channel", value: escapeHtml(order.channel) }]))}${panel("Shipment timeline", "Line-by-line visibility into processing steps.", timeline([{ title: "Order confirmed", detail: "Sales order synced from CRM to commerce ops.", time: "09:12", tone: "primary" }, { title: "Payment captured", detail: "ACH payment confirmed and risk checks cleared.", time: "09:18", tone: "success" }, { title: "Provisioning in progress", detail: "Workspace seats and automations are being provisioned.", time: "09:37", tone: "warning" }]))}</div>
    ${panel("Line items", "Products and services included in the order.", simpleTable(["Item", "Qty", "Unit price", "Total"], [["CRM Workspace", "<span class='font-semibold text-[color:var(--text)]'>3</span>", "<span class='font-semibold text-[color:var(--text)]'>$189</span>", "<span class='font-semibold text-[color:var(--text)]'>$567</span>"], ["Insight Pro Seat", "<span class='font-semibold text-[color:var(--text)]'>5</span>", "<span class='font-semibold text-[color:var(--text)]'>$129</span>", "<span class='font-semibold text-[color:var(--text)]'>$645</span>"], ["Migration support", "<span class='font-semibold text-[color:var(--text)]'>1</span>", "<span class='font-semibold text-[color:var(--text)]'>$3,168</span>", "<span class='font-semibold text-[color:var(--text)]'>$3,168</span>"]]))}
  `;
  return { content, charts: [] };
}

function productRows() {
  return products.map((product) => ({
    search: `${product.sku} ${product.name} ${product.category} ${product.status}`.toLowerCase(),
    filters: { status: product.status, category: product.category },
    sort: { product: product.name, category: product.category, price: product.price, stock: product.stock, status: product.status, revenue: product.revenue },
    cells: {
      product: `<div><a href="${pageHref("product-detail", 2)}" class="font-semibold text-[color:var(--text)]">${escapeHtml(product.name)}</a><p class="mt-1 text-xs uppercase tracking-[0.18em] text-[color:var(--text-faint)]">${escapeHtml(product.sku)}</p></div>`,
      category: `<span class="font-semibold text-[color:var(--text)]">${escapeHtml(product.category)}</span>`,
      price: `<span class="font-semibold text-[color:var(--text)]">${currency(product.price)}</span>`,
      stock: `<span class="font-semibold text-[color:var(--text)]">${number(product.stock)}</span>`,
      status: badge(product.status, product.status === "Published" ? "success" : product.status === "Beta" ? "info" : "warning", "status"),
      revenue: `<span class="font-semibold text-[color:var(--text)]">${currency(product.revenue)}</span>`,
    },
  }));
}

function renderProductsList(page) {
  const content = `
    ${heroBlock(page, [
      { label: "Catalog items", value: "128", delta: "+12 new", tone: "primary" },
      { label: "Published", value: "94", delta: "73%", tone: "success" },
      { label: "In beta", value: "18", delta: "14%", tone: "info" },
      { label: "Drafts", value: "16", delta: "needs review", tone: "warning" },
    ])}
    ${renderDataTable({
      title: "Product catalog",
      description: "Manage pricing, publish status and revenue output across every product.",
      columns: [
        { key: "product", label: "Product", sortable: true },
        { key: "category", label: "Category", sortable: true },
        { key: "price", label: "Price", sortable: true, type: "number" },
        { key: "stock", label: "Stock", sortable: true, type: "number" },
        { key: "status", label: "Status", sortable: true },
        { key: "revenue", label: "Revenue", sortable: true, type: "number" },
      ],
      rows: productRows(),
      filters: [
        { key: "status", label: "All statuses", options: ["Published", "Beta", "Draft"] },
        { key: "category", label: "All categories", options: ["Analytics", "CRM", "Commerce", "Finance", "Security", "Support", "Workspace", "Planning"] },
      ],
      searchPlaceholder: "Search product, SKU or category",
      sortKey: "revenue",
    })}
  `;
  return { content, charts: [] };
}

function renderProductDetail(page) {
  const product = products[1];
  const content = `
    ${heroBlock(page, [
      { label: "Monthly revenue", value: currency(product.revenue), delta: "+18.2%", tone: "success" },
      { label: "ARPA", value: "$189", delta: "flat pricing", tone: "primary" },
      { label: "Rating", value: String(product.rating), delta: "G2 internal sample", tone: "info" },
      { label: "Owner", value: product.owner, delta: "Revenue Team", tone: "warning" },
    ])}
    <div class="grid gap-6 xl:grid-cols-[1fr_.95fr]">${panel("Product profile", "Commercial metadata and packaging information.", keyValueList([{ label: "SKU", value: escapeHtml(product.sku) }, { label: "Category", value: escapeHtml(product.category) }, { label: "Status", value: badge(product.status, "success", "status") }, { label: "List price", value: currency(product.price) }, { label: "Owner", value: escapeHtml(product.owner) }, { label: "Seats included", value: "Per workspace" }]))}${chartCard("productPerformanceChart", "Performance trend", "Revenue and adoption momentum over the last six months.", "320px")}</div>
    ${panel("Recent linked orders", "Latest orders containing this product bundle.", simpleTable(["Order", "Customer", "Amount", "Status"], orders.slice(0, 4).map((order) => [`<a href="${pageHref("order-detail", depthFor(page.path))}" class="font-semibold text-[color:var(--text)]">${escapeHtml(order.id)}</a>`, escapeHtml(order.company), `<span class="font-semibold text-[color:var(--text)]">${currency(order.amount)}</span>`, badge(order.fulfillment, order.fulfillment === "Delivered" ? "success" : order.fulfillment === "Pending" ? "warning" : "primary", "status")])))}
  `;
  const charts = [chartLine("productPerformanceChart", ["Oct", "Nov", "Dec", "Jan", "Feb", "Mar"], [{ label: "Revenue", data: [34400, 38200, 41600, 46800, 53100, 61200], borderColor: "theme:primary", backgroundColor: "theme:primarySoft", fill: true, tension: 0.4, pointRadius: 0, borderWidth: 3 }, { label: "Activated workspaces", data: [112, 128, 146, 170, 192, 214], borderColor: "theme:success", backgroundColor: "theme:successSoft", fill: false, tension: 0.4, pointRadius: 0, borderWidth: 2 }])];
  return { content, charts };
}

function renderAddNewProduct(page) {
  const content = `
    ${heroBlock(page, [
      { label: "Draft slots", value: "16", delta: "4 pending review", tone: "warning" },
      { label: "Published this month", value: "12", delta: "+3 vs Feb", tone: "success" },
      { label: "Avg review cycle", value: "2.4d", delta: "fast", tone: "primary" },
      { label: "Launch readiness", value: "82%", delta: "needs assets", tone: "info" },
    ])}
    <div class="grid gap-6 xl:grid-cols-[1.1fr_.9fr]">${panel("Product information", "Create a new catalog item using the shared product system.", `<form class="space-y-5"><div class="grid gap-5 md:grid-cols-2"><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Product name</span><input class="field" placeholder="Forecast Command Center" /></label><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">SKU</span><input class="field" placeholder="PRD-309" /></label><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Category</span><select class="select-field"><option>Planning</option><option>Analytics</option><option>CRM</option><option>Finance</option></select></label><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Owner team</span><select class="select-field"><option>Strategy Team</option><option>Growth Team</option><option>Finance Team</option></select></label></div><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Description</span><textarea class="textarea-field" placeholder="Describe the product positioning, packaging and ideal buyer profile."></textarea></label><div class="upload-dropzone p-6 text-center"><div class="mx-auto flex h-14 w-14 items-center justify-center rounded-3xl bg-white/80 text-blue-600 shadow-lg">${icon("upload", "h-6 w-6")}</div><p class="mt-4 text-base font-semibold text-[color:var(--text)]">Drop hero images, docs or launch assets</p><p class="mt-2 text-sm text-[color:var(--text-soft)]">PNG, SVG, PDF or DOCX up to 25 MB</p></div></form>`)}${panel("Pricing & controls", "Configure billing and launch switches.", `<div class="space-y-5"><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Base price</span><input class="field" value="$149" /></label><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Billing cadence</span><select class="select-field"><option>Monthly</option><option>Annual</option></select></label><label class="flex items-center justify-between gap-4 rounded-3xl border border-[color:var(--border)] p-4"><div><p class="text-sm font-semibold text-[color:var(--text)]">Publish on save</p><p class="mt-1 text-sm text-[color:var(--text-soft)]">Push the product live right after review.</p></div><span><input type="checkbox" class="toggle-input sr-only" /><span class="toggle-switch"></span></span></label><label class="flex items-center justify-between gap-4 rounded-3xl border border-[color:var(--border)] p-4"><div><p class="text-sm font-semibold text-[color:var(--text)]">Enable add-on upsell</p><p class="mt-1 text-sm text-[color:var(--text-soft)]">Allow post-purchase expansions in checkout flows.</p></div><span><input type="checkbox" class="toggle-input sr-only" checked /><span class="toggle-switch"></span></span></label><div class="flex gap-3"><button type="button" class="flex-1 rounded-2xl bg-blue-600 px-4 py-3 text-sm font-semibold text-white" data-toast="Draft saved">Save draft</button><button type="button" class="flex-1 rounded-2xl border border-[color:var(--border)] px-4 py-3 text-sm font-semibold text-[color:var(--text-soft)]" data-toast="Review started">Request review</button></div></div>`)} </div>
  `;
  return { content, charts: [] };
}

function renderCategories(page) {
  const categoryCards = products.reduce((accumulator, product) => { accumulator[product.category] = accumulator[product.category] || { count: 0, revenue: 0 }; accumulator[product.category].count += 1; accumulator[product.category].revenue += product.revenue; return accumulator; }, {});
  const content = `
    ${heroBlock(page, [
      { label: "Categories", value: String(Object.keys(categoryCards).length), delta: "active groups", tone: "primary" },
      { label: "Top category", value: "CRM", delta: "$61.2k", tone: "success" },
      { label: "Needs review", value: "2", delta: "draft-heavy", tone: "warning" },
      { label: "Share of revenue", value: "28%", delta: "Analytics", tone: "info" },
    ])}
    <div class="grid gap-6 md:grid-cols-2 xl:grid-cols-4">${Object.entries(categoryCards).map(([name, item], index) => statCard({ label: name, value: currency(item.revenue), delta: `${item.count} products`, tone: ["primary", "success", "warning", "info"][index % 4], iconName: "shopping", hint: "monthly output" })).join("")}</div>
    ${panel("Category management", "Revenue ownership and publish posture by category.", simpleTable(["Category", "Products", "Revenue", "Lead"], Object.entries(categoryCards).map(([name, item], index) => [`<span class="font-semibold text-[color:var(--text)]">${escapeHtml(name)}</span>`, `<span class="font-semibold text-[color:var(--text)]">${item.count}</span>`, `<span class="font-semibold text-[color:var(--text)]">${currency(item.revenue)}</span>`, escapeHtml(teamMembers[index].name)])))}
  `;
  return { content, charts: [] };
}

function transactionRows() {
  return transactions.map((transaction) => ({
    search: `${transaction.id} ${transaction.type} ${transaction.reference} ${transaction.method} ${transaction.status}`.toLowerCase(),
    filters: { status: transaction.status, type: transaction.type },
    sort: { transaction: transaction.id, type: transaction.type, reference: transaction.reference, amount: transaction.amount, method: transaction.method, status: transaction.status },
    cells: {
      transaction: `<span class="font-semibold text-[color:var(--text)]">${escapeHtml(transaction.id)}</span>`,
      type: badge(transaction.type, transaction.amount >= 0 ? "success" : "warning"),
      reference: `<div><p class="font-semibold text-[color:var(--text)]">${escapeHtml(transaction.reference)}</p><p class="mt-1 text-sm text-[color:var(--text-soft)]">${escapeHtml(transaction.date)}</p></div>`,
      amount: `<span class="font-semibold ${transaction.amount >= 0 ? "text-emerald-600 dark:text-emerald-400" : "text-rose-600 dark:text-rose-400"}">${currency(transaction.amount)}</span>`,
      method: `<span class="font-semibold text-[color:var(--text)]">${escapeHtml(transaction.method)}</span>`,
      status: badge(transaction.status, transaction.status === "Settled" ? "success" : transaction.status === "Pending" || transaction.status === "Scheduled" ? "warning" : transaction.status === "Review" ? "info" : "danger", "status"),
    },
  }));
}

function renderTransactions(page) {
  const content = `
    ${heroBlock(page, [
      { label: "Settled volume", value: "$118.4k", delta: "+11.2%", tone: "success" },
      { label: "Pending", value: "$3.8k", delta: "4 records", tone: "warning" },
      { label: "Refunds", value: "$3.1k", delta: "stable", tone: "info" },
      { label: "Chargebacks", value: "1", delta: "under review", tone: "danger" },
    ])}
    ${renderDataTable({
      title: "Transaction ledger",
      description: "Monitor money movement across subscriptions, invoices, usage and payouts.",
      columns: [
        { key: "transaction", label: "Transaction", sortable: true },
        { key: "type", label: "Type", sortable: true },
        { key: "reference", label: "Reference", sortable: true },
        { key: "amount", label: "Amount", sortable: true, type: "number" },
        { key: "method", label: "Method", sortable: true },
        { key: "status", label: "Status", sortable: true },
      ],
      rows: transactionRows(),
      filters: [
        { key: "status", label: "All statuses", options: ["Settled", "Pending", "Scheduled", "Review", "Investigating"] },
        { key: "type", label: "All types", options: ["Subscription", "Upgrade", "Refund", "Invoice", "Chargeback", "Usage", "Payout"] },
      ],
      searchPlaceholder: "Search transaction, reference or method",
      sortKey: "amount",
    })}
  `;
  return { content, charts: [] };
}

function invoiceRows() {
  return invoices.map((invoice) => ({
    search: `${invoice.id} ${invoice.customer} ${invoice.status} ${invoice.paymentMethod}`.toLowerCase(),
    filters: { status: invoice.status },
    sort: { invoice: invoice.id, customer: invoice.customer, amount: invoice.amount, status: invoice.status, issueDate: invoice.issueDate, dueDate: invoice.dueDate },
    cells: {
      invoice: `<a href="${pageHref("invoice-detail", 2)}" class="font-semibold text-[color:var(--text)]">${escapeHtml(invoice.id)}</a>`,
      customer: `<span class="font-semibold text-[color:var(--text)]">${escapeHtml(invoice.customer)}</span>`,
      amount: `<span class="font-semibold text-[color:var(--text)]">${currency(invoice.amount)}</span>`,
      status: badge(invoice.status, invoice.status === "Paid" ? "success" : invoice.status === "Overdue" ? "danger" : invoice.status === "Draft" ? "warning" : "info", "status"),
      issueDate: escapeHtml(invoice.issueDate),
      dueDate: escapeHtml(invoice.dueDate),
    },
  }));
}

function renderInvoices(page) {
  const content = `
    ${heroBlock(page, [
      { label: "Invoices issued", value: "128", delta: "+18 this month", tone: "primary" },
      { label: "Collected", value: "$112.6k", delta: "+10.4%", tone: "success" },
      { label: "Overdue", value: "$8.4k", delta: "4 records", tone: "warning" },
      { label: "Drafts", value: "6", delta: "awaiting review", tone: "info" },
    ])}
    ${renderDataTable({
      title: "Invoices",
      description: "Invoice operations and collections status across the full billing cycle.",
      columns: [
        { key: "invoice", label: "Invoice", sortable: true },
        { key: "customer", label: "Customer", sortable: true },
        { key: "amount", label: "Amount", sortable: true, type: "number" },
        { key: "status", label: "Status", sortable: true },
        { key: "issueDate", label: "Issued", sortable: true, type: "date" },
        { key: "dueDate", label: "Due", sortable: true, type: "date" },
      ],
      rows: invoiceRows(),
      filters: [{ key: "status", label: "All statuses", options: ["Paid", "Sent", "Draft", "Overdue"] }],
      searchPlaceholder: "Search invoice, customer or payment method",
      sortKey: "dueDate",
    })}
  `;
  return { content, charts: [] };
}

function renderInvoiceDetail(page) {
  const invoice = invoices[0];
  const content = `
    ${heroBlock(page, [
      { label: "Invoice", value: invoice.id, delta: invoice.status, tone: "success" },
      { label: "Amount", value: currency(invoice.amount), delta: "Settled", tone: "primary" },
      { label: "Issued", value: invoice.issueDate, delta: "Net 7", tone: "info" },
      { label: "Method", value: "Visa", delta: "ending 4021", tone: "warning" },
    ])}
    <div class="grid gap-6 xl:grid-cols-[1.1fr_.9fr]">${panel("Invoice summary", "Bill-to and accounting context.", keyValueList([{ label: "Customer", value: escapeHtml(invoice.customer) }, { label: "Issue date", value: escapeHtml(invoice.issueDate) }, { label: "Due date", value: escapeHtml(invoice.dueDate) }, { label: "Status", value: badge(invoice.status, "success", "status") }, { label: "Payment method", value: escapeHtml(invoice.paymentMethod) }, { label: "PO reference", value: "PO-90214" }]))}${panel("Payment activity", "Finance-side movement on this invoice.", timeline([{ title: "Invoice issued", detail: "Billing cycle triggered from annual contract schedule.", time: "01 Mar", tone: "primary" }, { title: "Customer viewed invoice", detail: "Opened from billing portal by admin owner.", time: "03 Mar", tone: "info" }, { title: "Payment settled", detail: "Payment succeeded and was reconciled automatically.", time: "07 Mar", tone: "success" }]))}</div>
    ${panel("Line items", "Detailed billing line items for the invoice.", simpleTable(["Description", "Qty", "Rate", "Total"], [["Scale plan annual base", "<span class='font-semibold text-[color:var(--text)]'>1</span>", "<span class='font-semibold text-[color:var(--text)]'>$4,200</span>", "<span class='font-semibold text-[color:var(--text)]'>$4,200</span>"], ["Additional seats", "<span class='font-semibold text-[color:var(--text)]'>6</span>", "<span class='font-semibold text-[color:var(--text)]'>$100</span>", "<span class='font-semibold text-[color:var(--text)]'>$600</span>"]]), `<button type="button" class="text-sm font-semibold text-blue-600" data-toast="Invoice PDF generated">Download PDF</button>`)}
  `;
  return { content, charts: [] };
}

function renderSubscriptionPlans(page) {
  const content = `
    ${heroBlock(page, [
      { label: "Active plans", value: "4", delta: "commercial tiers", tone: "primary" },
      { label: "Most adopted", value: "Scale", delta: "41%", tone: "success" },
      { label: "Enterprise mix", value: "32%", delta: "+4 pts", tone: "warning" },
      { label: "Avg expansion", value: "$1.2k", delta: "per account", tone: "info" },
    ])}
    <div class="grid gap-6 xl:grid-cols-4">${plans.map((plan) => `<article class="panel reveal p-6"><div class="flex items-center justify-between gap-3"><h3 class="font-display text-2xl font-semibold tracking-tight text-[color:var(--text)]">${escapeHtml(plan.name)}</h3>${badge(plan.name === "Growth" ? "Popular" : "Plan", plan.tone)}</div><p class="mt-4 text-4xl font-semibold tracking-tight text-[color:var(--text)]">${escapeHtml(plan.price)}</p><p class="mt-3 text-sm leading-6 text-[color:var(--text-soft)]">${escapeHtml(plan.description)}</p><ul class="mt-6 space-y-3 text-sm text-[color:var(--text-soft)]">${plan.features.map((feature) => `<li class="flex items-start gap-3">${icon("check", "mt-0.5 h-4 w-4 text-emerald-500")}<span>${escapeHtml(feature)}</span></li>`).join("")}</ul></article>`).join("")}</div>
    ${panel("Plan mix", "Revenue and account distribution by plan.", simpleTable(["Plan", "Accounts", "Share", "Avg contract"], [["Starter", "<span class='font-semibold text-[color:var(--text)]'>102</span>", badge("8%", "info"), "<span class='font-semibold text-[color:var(--text)]'>$588</span>"], ["Growth", "<span class='font-semibold text-[color:var(--text)]'>242</span>", badge("19%", "success"), "<span class='font-semibold text-[color:var(--text)]'>$1,548</span>"], ["Scale", "<span class='font-semibold text-[color:var(--text)]'>518</span>", badge("41%", "primary"), "<span class='font-semibold text-[color:var(--text)]'>$2,988</span>"], ["Enterprise", "<span class='font-semibold text-[color:var(--text)]'>386</span>", badge("32%", "warning"), "<span class='font-semibold text-[color:var(--text)]'>$10,420</span>"]]))}
  `;
  return { content, charts: [] };
}

function subscriberRows() {
  return subscribers.map((subscriber) => ({
    search: `${subscriber.id} ${subscriber.customer} ${subscriber.owner} ${subscriber.plan} ${subscriber.status}`.toLowerCase(),
    filters: { plan: subscriber.plan, status: subscriber.status },
    sort: { subscriber: subscriber.customer, owner: subscriber.owner, plan: subscriber.plan, seats: subscriber.seats, renewal: subscriber.renewal, arpa: subscriber.arpa },
    cells: {
      subscriber: `<div><p class="font-semibold text-[color:var(--text)]">${escapeHtml(subscriber.customer)}</p><p class="mt-1 text-xs uppercase tracking-[0.18em] text-[color:var(--text-faint)]">${escapeHtml(subscriber.id)}</p></div>`,
      owner: `<div class="flex items-center gap-3">${avatar(subscriber.owner, "primary", "sm")}<span class="font-semibold text-[color:var(--text)]">${escapeHtml(subscriber.owner)}</span></div>`,
      plan: badge(subscriber.plan, subscriber.plan === "Enterprise" ? "warning" : subscriber.plan === "Scale" ? "primary" : subscriber.plan === "Growth" ? "success" : "info"),
      seats: `<span class="font-semibold text-[color:var(--text)]">${subscriber.seats}</span>`,
      renewal: `<span class="font-semibold text-[color:var(--text)]">${escapeHtml(subscriber.renewal)}</span>`,
      arpa: `<span class="font-semibold text-[color:var(--text)]">${currency(subscriber.arpa)}</span>`,
    },
  }));
}

function renderSubscribersList(page) {
  const content = `
    ${heroBlock(page, [
      { label: "Subscribers", value: "1,248", delta: "+31 net", tone: "primary" },
      { label: "ARPA", value: "$92", delta: "+5.2%", tone: "success" },
      { label: "Renewals this month", value: "64", delta: "12 enterprise", tone: "warning" },
      { label: "Expansion accounts", value: "118", delta: "+14", tone: "info" },
    ])}
    ${renderDataTable({ title: "Subscriber roster", description: "Monitor plan, seats, renewal dates and average revenue per account.", columns: [{ key: "subscriber", label: "Subscriber", sortable: true }, { key: "owner", label: "Owner", sortable: true }, { key: "plan", label: "Plan", sortable: true }, { key: "seats", label: "Seats", sortable: true, type: "number" }, { key: "renewal", label: "Renewal", sortable: true, type: "date" }, { key: "arpa", label: "ARPA", sortable: true, type: "number" }], rows: subscriberRows(), filters: [{ key: "plan", label: "All plans", options: ["Starter", "Growth", "Scale", "Enterprise"] }, { key: "status", label: "All statuses", options: ["Active", "Trial", "Risk", "Paused", "Onboarding", "Renewal"] }], searchPlaceholder: "Search subscriber, owner or plan", sortKey: "renewal" })}
  `;
  return { content, charts: [] };
}

function renderBillingOverview(page) {
  const content = `
    ${heroBlock(page, [{ label: "MRR", value: "$142.8k", delta: "+12.6%", tone: "primary" }, { label: "ARR", value: "$1.71M", delta: "+16.4%", tone: "success" }, { label: "Failed charges", value: "14", delta: "-3 vs last week", tone: "warning" }, { label: "Recovery rate", value: "68%", delta: "+8 pts", tone: "info" }])}
    <div class="grid gap-6 xl:grid-cols-[1.2fr_.8fr]">${chartCard("billingCashChart", "Collections and recovery", "Cash collections against recovered failed payments.", "340px")}${chartCard("billingDunningChart", "Dunning effectiveness", "Attempts and successful recoveries per cycle.", "340px")}</div>
    <div class="grid gap-6 xl:grid-cols-[1fr_1fr]">${panel("Payment method health", "Portfolio-level payment method mix and risk posture.", `<div class="space-y-5">${progressRow("Cards", 58, "primary")}${progressRow("ACH", 21, "success")}${progressRow("Wire", 14, "info")}${progressRow("SEPA", 7, "warning")}</div>`)}${panel("Billing controls", "Automation readiness for collections and notifications.", `<div class="space-y-4"><label class="flex items-center justify-between gap-4 rounded-3xl border border-[color:var(--border)] p-4"><div><p class="text-sm font-semibold text-[color:var(--text)]">Auto-retry failed cards</p><p class="mt-1 text-sm text-[color:var(--text-soft)]">Retry cards using the configured cadence.</p></div><span><input type="checkbox" class="toggle-input sr-only" checked /><span class="toggle-switch"></span></span></label><label class="flex items-center justify-between gap-4 rounded-3xl border border-[color:var(--border)] p-4"><div><p class="text-sm font-semibold text-[color:var(--text)]">Finance escalation at attempt 3</p><p class="mt-1 text-sm text-[color:var(--text-soft)]">Notify finance owners before accounts become overdue.</p></div><span><input type="checkbox" class="toggle-input sr-only" checked /><span class="toggle-switch"></span></span></label></div>`)} </div>
  `;
  const charts = [
    chartLine("billingCashChart", ["Oct", "Nov", "Dec", "Jan", "Feb", "Mar"], [{ label: "Collections", data: [96000, 102000, 118000, 124000, 136000, 148000], borderColor: "theme:primary", backgroundColor: "theme:primarySoft", fill: true, tension: 0.4, pointRadius: 0, borderWidth: 3 }, { label: "Recovered", data: [4200, 5100, 5500, 6100, 7300, 8200], borderColor: "theme:success", backgroundColor: "theme:successSoft", fill: false, tension: 0.4, pointRadius: 0, borderWidth: 2 }]),
    chartBar("billingDunningChart", ["Attempt 1", "Attempt 2", "Attempt 3", "Attempt 4"], [{ label: "Sent", data: [82, 51, 24, 9], backgroundColor: "theme:warning", borderRadius: 12 }, { label: "Recovered", data: [34, 19, 9, 3], backgroundColor: "theme:success", borderRadius: 12 }]),
  ];
  return { content, charts };
}

function renderRevenueReports(page) {
  const content = `${heroBlock(page, [{ label: "Revenue by region", value: "$1.82M", delta: "YTD", tone: "primary" }, { label: "Expansion share", value: "18.6%", delta: "+2.1 pts", tone: "success" }, { label: "Contraction", value: "$12.8k", delta: "-11%", tone: "warning" }, { label: "Net retention", value: "114%", delta: "+5 pts", tone: "info" }])}<div class="grid gap-6 xl:grid-cols-[1fr_1fr]">${chartCard("revenueRegionChart", "Regional performance", "ARR contribution across major regions.", "340px")}${chartCard("revenueBridgeChart", "Revenue bridge", "New, expansion, contraction and churn components.", "340px")}</div>${panel("Regional table", "Leadership-ready breakdown of revenue output.", simpleTable(["Region", "ARR", "Growth", "Top segment"], [["North America", "<span class='font-semibold text-[color:var(--text)]'>$812k</span>", badge("+18%", "success"), "Enterprise"], ["Europe", "<span class='font-semibold text-[color:var(--text)]'>$544k</span>", badge("+12%", "primary"), "Scale"], ["MENA", "<span class='font-semibold text-[color:var(--text)]'>$264k</span>", badge("+21%", "success"), "Enterprise"], ["APAC", "<span class='font-semibold text-[color:var(--text)]'>$198k</span>", badge("+9%", "info"), "Growth"]]))}`;
  const charts = [chartBar("revenueRegionChart", ["North America", "Europe", "MENA", "APAC"], [{ label: "ARR", data: [812000, 544000, 264000, 198000], backgroundColor: ["theme:primary", "theme:success", "theme:warning", "theme:info"], borderRadius: 12 }], { plugins: { legend: { display: false } } }), chartBar("revenueBridgeChart", ["New", "Expansion", "Usage", "Contraction", "Churn"], [{ label: "Revenue impact", data: [184000, 102000, 24000, -31000, -18800], backgroundColor: ["theme:success", "theme:primary", "theme:info", "theme:warning", "theme:danger"], borderRadius: 12 }], { plugins: { legend: { display: false } } })];
  return { content, charts };
}

function ticketRows() {
  return tickets.map((ticket) => ({
    search: `${ticket.id} ${ticket.subject} ${ticket.customer} ${ticket.priority} ${ticket.status} ${ticket.agent}`.toLowerCase(),
    filters: { status: ticket.status, priority: ticket.priority },
    sort: { ticket: ticket.id, subject: ticket.subject, customer: ticket.customer, priority: ticket.priority, status: ticket.status, agent: ticket.agent, updatedAt: ticket.updatedAt },
    cells: {
      ticket: `<a href="${pageHref("ticket-detail", 2)}" class="font-semibold text-[color:var(--text)]">${escapeHtml(ticket.id)}</a>`,
      subject: `<div><p class="font-semibold text-[color:var(--text)]">${escapeHtml(ticket.subject)}</p><p class="mt-1 text-sm text-[color:var(--text-soft)]">${escapeHtml(ticket.customer)}</p></div>`,
      priority: badge(ticket.priority, ticket.priority === "High" ? "danger" : ticket.priority === "Medium" ? "warning" : "info"),
      status: badge(ticket.status, ticket.status === "Open" ? "warning" : ticket.status === "Pending" ? "info" : ticket.status === "Solved" ? "success" : "danger", "status"),
      agent: `<span class="font-semibold text-[color:var(--text)]">${escapeHtml(ticket.agent)}</span>`,
      updatedAt: `<span class="font-semibold text-[color:var(--text)]">${escapeHtml(ticket.updatedAt)}</span>`,
    },
  }));
}

function renderSupportTickets(page) {
  const content = `${heroBlock(page, [{ label: "Open tickets", value: "38", delta: "-8.2%", tone: "warning" }, { label: "Median first reply", value: "22m", delta: "-6m", tone: "success" }, { label: "Escalations", value: "3", delta: "under control", tone: "danger" }, { label: "CSAT", value: "4.8/5", delta: "+0.2", tone: "info" }])}${renderDataTable({ title: "Support queue", description: "Sort by SLA, priority or agent to keep the queue healthy.", columns: [{ key: "ticket", label: "Ticket", sortable: true }, { key: "subject", label: "Subject", sortable: true }, { key: "priority", label: "Priority", sortable: true }, { key: "status", label: "Status", sortable: true }, { key: "agent", label: "Agent", sortable: true }, { key: "updatedAt", label: "Updated", sortable: true }], rows: ticketRows(), filters: [{ key: "status", label: "All statuses", options: ["Open", "Pending", "Solved", "Escalated"] }, { key: "priority", label: "All priorities", options: ["High", "Medium", "Low"] }], searchPlaceholder: "Search ticket, subject or customer", sortKey: "updatedAt" })}`;
  return { content, charts: [] };
}

function renderTicketDetail(page) {
  const ticket = tickets[0];
  const conversation = [
    { author: "Customer", body: "Invited users are stuck after the first SSO redirect. Existing users sign in without issues.", direction: "incoming", time: "08:54" },
    { author: "Mina", body: "Thanks, we reproduced the issue in staging and are checking attribute mappings for newly invited users.", direction: "outgoing", time: "09:02" },
    { author: "Customer", body: "Please let us know if a temporary workaround exists. We have a rollout this afternoon.", direction: "incoming", time: "09:06" },
  ];
  const content = `${heroBlock(page, [{ label: "Ticket", value: ticket.id, delta: ticket.priority, tone: "danger" }, { label: "Status", value: ticket.status, delta: ticket.sla, tone: "warning" }, { label: "Channel", value: ticket.channel, delta: "active thread", tone: "info" }, { label: "Agent", value: ticket.agent, delta: "owner", tone: "primary" }])}<div class="grid gap-6 xl:grid-cols-[1.15fr_.85fr]">${panel("Conversation", "Ticket thread with timestamps and quick context.", `<div class="space-y-4">${conversation.map((item) => `<div class="flex ${item.direction === "outgoing" ? "justify-end" : "justify-start"}"><div class="message-bubble ${item.direction}"><div class="flex items-center justify-between gap-3"><p class="text-xs font-semibold uppercase tracking-[0.18em] ${item.direction === "outgoing" ? "text-white/80" : "text-[color:var(--text-faint)]"}">${escapeHtml(item.author)}</p><p class="text-xs ${item.direction === "outgoing" ? "text-white/80" : "text-[color:var(--text-faint)]"}">${escapeHtml(item.time)}</p></div><p class="mt-2 text-sm leading-6 ${item.direction === "outgoing" ? "text-white" : "text-[color:var(--text-soft)]"}">${escapeHtml(item.body)}</p></div></div>`).join("")}<div class="mt-6 flex gap-3"><input class="field" placeholder="Type an internal or customer-facing reply" /><button type="button" class="rounded-2xl bg-blue-600 px-4 py-3 text-sm font-semibold text-white" data-toast="Reply queued">Send</button></div></div>`)}${panel("Ticket details", "Metadata, SLA and response helpers.", `${keyValueList([{ label: "Customer", value: escapeHtml(ticket.customer) }, { label: "Priority", value: badge(ticket.priority, "danger") }, { label: "Status", value: badge(ticket.status, "warning", "status") }, { label: "SLA", value: escapeHtml(ticket.sla) }])}<div class="mt-6 space-y-4" x-data="{one:true,two:false}"><div class="rounded-3xl border border-[color:var(--border)] p-4"><button type="button" class="flex w-full items-center justify-between gap-4 text-left" @click="one=!one"><span class="font-semibold text-[color:var(--text)]">Suggested macro</span>${icon("chevronDown", "h-4 w-4")}</button><div class="pt-4 text-sm leading-6 text-[color:var(--text-soft)]" x-show="one">Share the temporary workaround for invited-user login and request the customer's IdP attribute sample.</div></div><div class="rounded-3xl border border-[color:var(--border)] p-4"><button type="button" class="flex w-full items-center justify-between gap-4 text-left" @click="two=!two"><span class="font-semibold text-[color:var(--text)]">Internal notes</span>${icon("chevronDown", "h-4 w-4")}</button><div class="pt-4 text-sm leading-6 text-[color:var(--text-soft)]" x-show="two">Potential regression introduced after the latest SAML mapping update. Security already reviewing.</div></div></div>`)} </div>`;
  return { content, charts: [] };
}

function renderCalendar(page) {
  const days = Array.from({ length: 31 }, (_, index) => index + 1);
  const content = `${heroBlock(page, [{ label: "Events this month", value: "28", delta: "12 internal", tone: "primary" }, { label: "Customer meetings", value: "9", delta: "4 enterprise", tone: "success" }, { label: "Launch milestones", value: "6", delta: "next 3 weeks", tone: "warning" }, { label: "Conflicts", value: "2", delta: "resolve today", tone: "danger" }])}<div class="grid gap-6 xl:grid-cols-[1.3fr_.7fr]">${panel("March 2026", "Operational calendar with milestones, QBRs and launches.", `<div class="grid grid-cols-7 gap-3 text-xs font-semibold uppercase tracking-[0.18em] text-[color:var(--text-faint)]"><span>Mon</span><span>Tue</span><span>Wed</span><span>Thu</span><span>Fri</span><span>Sat</span><span>Sun</span></div><div class="calendar-grid mt-4">${days.map((day) => `<div class="calendar-cell"><div class="flex items-center justify-between gap-3"><span class="text-sm font-semibold text-[color:var(--text)]">${day}</span>${calendarEvents[day] ? badge(String(calendarEvents[day].length), calendarEvents[day][0].tone) : ""}</div><div class="mt-4 space-y-2">${(calendarEvents[day] || []).map((event) => `<div class="rounded-2xl px-3 py-2 text-xs font-semibold" style="background:${tonePair(event.tone).soft};color:${tonePair(event.tone).main};"><div>${escapeHtml(event.time)}</div><div class="mt-1">${escapeHtml(event.title)}</div></div>`).join("")}</div></div>`).join("")}</div>`)}${panel("Agenda", "Prioritized events and deadlines for the current week.", activityList([{ title: "Pipeline review", detail: "Revenue leadership sync with region owners.", time: "Today, 10:00", tone: "primary" }, { title: "Northstar renewal", detail: "Final commercial review before annual commit closes.", time: "Fri, 15:00", tone: "success" }, { title: "Security review", detail: "Procurement and compliance walkthrough for SigmaPay.", time: "Mon, 16:00", tone: "danger" }]))}</div>`;
  return { content, charts: [] };
}

function renderKanban(page) {
  const content = `${heroBlock(page, [{ label: "Open tasks", value: "21", delta: "-5 today", tone: "primary" }, { label: "Work in review", value: "7", delta: "needs approvals", tone: "warning" }, { label: "Completed", value: "42", delta: "this sprint", tone: "success" }, { label: "Blocked", value: "2", delta: "finance review", tone: "danger" }])}<section class="grid gap-6 xl:grid-cols-4">${kanbanColumns.map((column) => `<div class="kanban-column reveal p-4"><div class="flex items-center justify-between gap-3"><h3 class="font-display text-lg font-semibold tracking-tight text-[color:var(--text)]">${escapeHtml(column.title)}</h3>${badge(String(column.count), "primary")}</div><div class="mt-5 space-y-4">${column.cards.map((card) => `<article class="rounded-3xl border border-[color:var(--border)] bg-white/70 p-4 shadow-sm dark:bg-slate-900/40"><div class="flex items-start justify-between gap-3">${badge(card.tone === "primary" ? "Ops" : card.tone === "success" ? "Live" : card.tone === "warning" ? "Review" : "Priority", card.tone)}${actionMenu()}</div><h4 class="mt-4 text-base font-semibold text-[color:var(--text)]">${escapeHtml(card.title)}</h4><p class="mt-2 text-sm text-[color:var(--text-soft)]">${escapeHtml(card.meta)}</p></article>`).join("")}</div></div>`).join("")}</section>`;
  return { content, charts: [] };
}

function renderMessages(page) {
  const content = `${heroBlock(page, [{ label: "Open threads", value: "42", delta: "5 unread", tone: "primary" }, { label: "Avg response time", value: "18m", delta: "-4m", tone: "success" }, { label: "VIP contacts", value: "12", delta: "active today", tone: "warning" }, { label: "Draft replies", value: "7", delta: "awaiting review", tone: "info" }])}<div class="grid gap-6 xl:grid-cols-[0.72fr_1.28fr]">${panel("Inbox", "Customer and internal threads with ownership context.", `<div class="space-y-3">${inboxThreads.map((thread) => `<article class="rounded-3xl border border-[color:var(--border)] p-4"><div class="flex items-start justify-between gap-4"><div><h4 class="text-sm font-semibold text-[color:var(--text)]">${escapeHtml(thread.name)}</h4><p class="mt-1 text-sm text-[color:var(--text-soft)]">${escapeHtml(thread.topic)}</p></div>${thread.unread ? badge(`${thread.unread} unread`, "primary") : badge("Read", "info")}</div><p class="mt-3 text-sm leading-6 text-[color:var(--text-soft)]">${escapeHtml(thread.preview)}</p><p class="mt-3 text-xs font-semibold uppercase tracking-[0.18em] text-[color:var(--text-faint)]">${escapeHtml(thread.time)}</p></article>`).join("")}</div>`)}${panel("Preview", "Selected thread content and shared notes.", `<div class="space-y-4"><div class="rounded-3xl border border-[color:var(--border)] p-5"><div class="flex items-center justify-between gap-4"><div><h3 class="text-lg font-semibold text-[color:var(--text)]">Northstar Labs</h3><p class="mt-1 text-sm text-[color:var(--text-soft)]">Pricing alignment for annual commit</p></div>${badge("VIP", "warning")}</div><div class="mt-5 space-y-4"><p class="text-sm leading-6 text-[color:var(--text-soft)]">Can you share the updated tier sheet before tomorrow's procurement review? We also need clarification on dedicated support hours.</p><div class="rounded-3xl border border-[color:var(--border)] bg-[color:var(--bg-muted)]/60 p-4"><p class="text-xs font-semibold uppercase tracking-[0.18em] text-[color:var(--text-faint)]">Suggested response</p><p class="mt-2 text-sm leading-6 text-[color:var(--text-soft)]">We can share the updated tier sheet, security appendix and support scope as a single package. Dedicated support hours start at the Enterprise plan.</p></div></div></div><div class="flex gap-3"><textarea class="textarea-field" placeholder="Draft a reply"></textarea><div class="flex flex-col gap-3"><button type="button" class="rounded-2xl bg-blue-600 px-4 py-3 text-sm font-semibold text-white" data-toast="Reply drafted">Save draft</button><button type="button" class="rounded-2xl border border-[color:var(--border)] px-4 py-3 text-sm font-semibold text-[color:var(--text-soft)]" data-toast="Reply sent">Send</button></div></div></div>`)} </div>`;
  return { content, charts: [] };
}

function renderChat(page) {
  const content = `${heroBlock(page, [{ label: "Participants", value: "8", delta: "ops war room", tone: "primary" }, { label: "Messages today", value: "126", delta: "+18", tone: "success" }, { label: "Pinned items", value: "4", delta: "latest plan", tone: "info" }, { label: "Urgent mentions", value: "2", delta: "action needed", tone: "warning" }])}<div class="grid gap-6 xl:grid-cols-[1fr_.72fr]">${panel("Team chat", "Real-time conversation for cross-functional coordination.", `<div class="space-y-4">${chatMessages.map((message) => `<div class="flex ${message.direction === "outgoing" ? "justify-end" : "justify-start"}"><div class="message-bubble ${message.direction}"><div class="flex items-center justify-between gap-3"><p class="text-xs font-semibold uppercase tracking-[0.18em] ${message.direction === "outgoing" ? "text-white/80" : "text-[color:var(--text-faint)]"}">${escapeHtml(message.author)}</p><p class="text-xs ${message.direction === "outgoing" ? "text-white/80" : "text-[color:var(--text-faint)]"}">${escapeHtml(message.time)}</p></div><p class="mt-2 text-sm leading-6 ${message.direction === "outgoing" ? "text-white" : "text-[color:var(--text-soft)]"}">${escapeHtml(message.body)}</p></div></div>`).join("")}<div class="mt-6 flex gap-3"><input class="field" placeholder="Write a team message" /><button type="button" class="rounded-2xl bg-blue-600 px-4 py-3 text-sm font-semibold text-white" data-toast="Message sent">Send</button></div></div>`)}${panel("Context cards", "Pinned links, owners and action items for the current room.", `<div class="space-y-4"><div class="rounded-3xl border border-[color:var(--border)] p-4"><p class="text-sm font-semibold text-[color:var(--text)]">Open issue</p><p class="mt-2 text-sm leading-6 text-[color:var(--text-soft)]">SSO invited-user regression. Security validation in progress.</p></div><div class="rounded-3xl border border-[color:var(--border)] p-4"><p class="text-sm font-semibold text-[color:var(--text)]">Primary owner</p><div class="mt-3 flex items-center gap-3">${avatar("Ali Gok", "info", "sm")}<span class="font-semibold text-[color:var(--text)]">Ali Gok</span></div></div><div class="rounded-3xl border border-[color:var(--border)] p-4"><p class="text-sm font-semibold text-[color:var(--text)]">Next checkpoint</p><p class="mt-2 text-sm leading-6 text-[color:var(--text-soft)]">11:30 with security, support and revenue stakeholders.</p></div></div>`)} </div>`;
  return { content, charts: [] };
}

function renderFileManager(page) {
  const content = `${heroBlock(page, [{ label: "Stored files", value: "1,284", delta: "+18 this week", tone: "primary" }, { label: "Used storage", value: "248 GB", delta: "61% of plan", tone: "warning" }, { label: "Shared folders", value: "28", delta: "team-wide", tone: "info" }, { label: "Recent uploads", value: "14", delta: "today", tone: "success" }])}<div class="grid gap-6 xl:grid-cols-[0.85fr_1.15fr]">${panel("Storage overview", "Capacity, folder usage and upload actions.", `<div class="upload-dropzone p-6 text-center"><div class="mx-auto flex h-14 w-14 items-center justify-center rounded-3xl bg-white/80 text-blue-600 shadow-lg">${icon("upload", "h-6 w-6")}</div><p class="mt-4 text-base font-semibold text-[color:var(--text)]">Drop files to upload</p><p class="mt-2 text-sm text-[color:var(--text-soft)]">Create reports, decks, exports or knowledge base assets.</p></div><div class="mt-6 space-y-5">${progressRow("Finance", 72, "warning")}${progressRow("Operations", 56, "primary")}${progressRow("Support", 34, "info")}${progressRow("Security", 18, "success")}</div>`)}${panel("Files", "Latest files across all shared spaces.", simpleTable(["Name", "Type", "Owner", "Updated"], files.slice(0, 6).map((file) => [`<span class="font-semibold text-[color:var(--text)]">${escapeHtml(file.name)}</span>`, escapeHtml(file.type), escapeHtml(file.owner), escapeHtml(file.updated)])))} </div>`;
  return { content, charts: [] };
}

function teamRows() {
  return teamMembers.map((member) => ({
    search: `${member.name} ${member.role} ${member.team} ${member.status} ${member.email}`.toLowerCase(),
    filters: { team: member.team, status: member.status },
    sort: { member: member.name, role: member.role, team: member.team, status: member.status, permissions: member.permissions, location: member.location },
    cells: {
      member: `<div class="flex items-center gap-3">${avatar(member.name, "primary", "sm")}<div><p class="font-semibold text-[color:var(--text)]">${escapeHtml(member.name)}</p><p class="mt-1 text-sm text-[color:var(--text-soft)]">${escapeHtml(member.email)}</p></div></div>`,
      role: `<span class="font-semibold text-[color:var(--text)]">${escapeHtml(member.role)}</span>`,
      team: badge(member.team, "info"),
      status: badge(member.status, member.status === "Online" ? "success" : member.status === "Busy" ? "warning" : member.status === "Away" ? "info" : "primary", "status"),
      permissions: `<span class="font-semibold text-[color:var(--text)]">${member.permissions}</span>`,
      location: `<span class="font-semibold text-[color:var(--text)]">${escapeHtml(member.location)}</span>`,
    },
  }));
}

function renderTeamMembers(page) {
  const content = `${heroBlock(page, [{ label: "Members", value: "86", delta: "+4 this month", tone: "primary" }, { label: "Online", value: "61", delta: "right now", tone: "success" }, { label: "Managers", value: "14", delta: "active owners", tone: "info" }, { label: "Pending invites", value: "3", delta: "review needed", tone: "warning" }])}${renderDataTable({ title: "Team members", description: "Directory of operators, owners and support teammates.", columns: [{ key: "member", label: "Member", sortable: true }, { key: "role", label: "Role", sortable: true }, { key: "team", label: "Team", sortable: true }, { key: "status", label: "Status", sortable: true }, { key: "permissions", label: "Permissions", sortable: true, type: "number" }, { key: "location", label: "Location", sortable: true }], rows: teamRows(), filters: [{ key: "team", label: "All teams", options: ["Executive", "Customer Success", "Growth", "Operations", "Support", "Security", "Finance"] }, { key: "status", label: "All statuses", options: ["Online", "Busy", "Away", "Focus"] }], searchPlaceholder: "Search member, role or team", sortKey: "member" })}`;
  return { content, charts: [] };
}

function renderRolesPermissions(page) {
  const content = `${heroBlock(page, [{ label: "Roles", value: "4", delta: "standardized", tone: "primary" }, { label: "Custom overrides", value: "12", delta: "audit monthly", tone: "warning" }, { label: "MFA coverage", value: "96%", delta: "+5 pts", tone: "success" }, { label: "Last audit", value: "07 Mar", delta: "clean", tone: "info" }])}<div class="grid gap-6 xl:grid-cols-[0.8fr_1.2fr]">${panel("Role catalog", "Current workspace roles and their focus area.", `<div class="space-y-4">${[["Admin", "Full platform access, security and billing controls.", "danger"], ["Manager", "Operational dashboards, revenue, team and reporting.", "primary"], ["Analyst", "Reporting, exports and read-only management access.", "info"], ["Support", "Tickets, customer context and limited billing visibility.", "success"]].map(([role, copy, tone]) => `<article class="rounded-3xl border border-[color:var(--border)] p-4"><div class="flex items-center justify-between gap-3"><h3 class="text-base font-semibold text-[color:var(--text)]">${role}</h3>${badge("Role", tone)}</div><p class="mt-2 text-sm leading-6 text-[color:var(--text-soft)]">${copy}</p></article>`).join("")}</div>`)}${panel("Permission matrix", "Shared access model across roles.", `<div class="overflow-x-auto"><table class="w-full text-sm"><thead><tr class="border-b border-[color:var(--border)] text-left text-[color:var(--text-faint)]"><th class="pb-3 pr-4 font-semibold">Area</th><th class="pb-3 pr-4 font-semibold">Admin</th><th class="pb-3 pr-4 font-semibold">Manager</th><th class="pb-3 pr-4 font-semibold">Analyst</th><th class="pb-3 pr-4 font-semibold">Support</th></tr></thead><tbody>${permissionRows.map((row) => `<tr class="border-b border-[color:var(--border)]"><td class="py-4 pr-4 font-semibold text-[color:var(--text)]">${escapeHtml(row.area)}</td><td class="py-4 pr-4">${row.admin ? badge("Allow", "success") : badge("Block", "danger")}</td><td class="py-4 pr-4">${row.manager ? badge("Allow", "success") : badge("Block", "danger")}</td><td class="py-4 pr-4">${row.analyst ? badge("Allow", "success") : badge("Block", "danger")}</td><td class="py-4 pr-4">${row.support ? badge("Allow", "success") : badge("Block", "danger")}</td></tr>`).join("")}</tbody></table></div>`)} </div>`;
  return { content, charts: [] };
}

function renderUserProfile(page) {
  const member = teamMembers[0];
  const content = `${heroBlock(page, [{ label: "Owned ARR", value: "$1.24M", delta: "+14%", tone: "success" }, { label: "Accounts", value: "28", delta: "active", tone: "primary" }, { label: "Tasks", value: "12", delta: "4 due this week", tone: "warning" }, { label: "Reports", value: "18", delta: "shared last month", tone: "info" }])}<div class="grid gap-6 xl:grid-cols-[1fr_.92fr]">${panel("Profile", "Personal ownership and contact details.", `<div class="flex items-start gap-4 rounded-3xl border border-[color:var(--border)] bg-[color:var(--bg-muted)]/50 p-5">${avatar(member.name, "primary", "lg")}<div><h3 class="font-display text-2xl font-semibold tracking-tight text-[color:var(--text)]">${escapeHtml(member.name)}</h3><p class="mt-1 text-sm text-[color:var(--text-soft)]">${escapeHtml(member.role)} • ${escapeHtml(member.team)}</p><div class="mt-4 flex flex-wrap gap-2">${badge(member.status, "success", "status")}${badge(member.location, "info")}${badge(`${member.permissions} permissions`, "primary")}</div></div></div><div class="mt-6" x-data="{tab:'summary'}"><div class="flex flex-wrap gap-2"><button type="button" class="rounded-2xl border border-[color:var(--border)] px-4 py-2 text-sm font-semibold" @click="tab='summary'">Summary</button><button type="button" class="rounded-2xl border border-[color:var(--border)] px-4 py-2 text-sm font-semibold" @click="tab='projects'">Projects</button><button type="button" class="rounded-2xl border border-[color:var(--border)] px-4 py-2 text-sm font-semibold" @click="tab='activity'">Activity</button></div><div class="mt-5" x-show="tab==='summary'">${keyValueList([{ label: "Email", value: escapeHtml(member.email) }, { label: "Region", value: escapeHtml(member.location) }, { label: "Team", value: escapeHtml(member.team) }, { label: "Focus", value: "Revenue and renewals" }])}</div><div class="mt-5" x-show="tab==='projects'">${simpleTable(["Project", "Status", "Owner"], [["Q2 growth pack", badge("Live", "success"), "Deniz Kaya"], ["Renewal risk watch", badge("Review", "warning"), "Selin Akca"], ["Board reporting", badge("Planning", "info"), "Ece Uysal"]])}</div><div class="mt-5" x-show="tab==='activity'">${timeline(activities.slice(0, 3))}</div></div>`)}${panel("Recent activity", "Latest ownership moments across reports and customer work.", timeline([{ title: "Reviewed Northstar renewal notes", detail: "Shared pricing guidance with procurement stakeholders.", time: "Today", tone: "primary" }, { title: "Approved Q2 dashboard pack", detail: "Moved board materials to final review.", time: "Yesterday", tone: "success" }, { title: "Escalated overdue invoice", detail: "Triggered collections workflow for Atlas HR.", time: "2 days ago", tone: "warning" }]))} </div>`;
  return { content, charts: [] };
}

function renderAccountSettings(page) {
  const content = `${heroBlock(page, [{ label: "Workspace", value: "KA Nexus", delta: "production", tone: "primary" }, { label: "Billing contact", value: "2", delta: "active", tone: "info" }, { label: "Domains", value: "3", delta: "verified", tone: "success" }, { label: "Seats", value: "86", delta: "14 available", tone: "warning" }])}<div class="grid gap-6 xl:grid-cols-[1.1fr_.9fr]">${panel("Organization profile", "Workspace-level details used across billing, reporting and exports.", `<form class="space-y-5"><div class="grid gap-5 md:grid-cols-2"><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Organization name</span><input class="field" value="KA Nexus" /></label><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Primary domain</span><input class="field" value="kanexus.io" /></label><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Billing email</span><input class="field" value="finance@kanexus.io" /></label><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Headquarters</span><input class="field" value="Istanbul" /></label></div><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Address</span><textarea class="textarea-field">Maslak district, innovation campus, building 4, Istanbul</textarea></label><button type="button" class="rounded-2xl bg-blue-600 px-5 py-3 text-sm font-semibold text-white" data-toast="Account settings saved">Save changes</button></form>`)}${panel("Workspace controls", "Common metadata and workspace defaults.", `<div class="space-y-4"><label class="flex items-center justify-between gap-4 rounded-3xl border border-[color:var(--border)] p-4"><div><p class="text-sm font-semibold text-[color:var(--text)]">Enable public status page</p><p class="mt-1 text-sm text-[color:var(--text-soft)]">Display incidents and planned maintenance externally.</p></div><span><input type="checkbox" class="toggle-input sr-only" checked /><span class="toggle-switch"></span></span></label><label class="flex items-center justify-between gap-4 rounded-3xl border border-[color:var(--border)] p-4"><div><p class="text-sm font-semibold text-[color:var(--text)]">Auto-create monthly board pack</p><p class="mt-1 text-sm text-[color:var(--text-soft)]">Generate leadership snapshots on the first business day.</p></div><span><input type="checkbox" class="toggle-input sr-only" checked /><span class="toggle-switch"></span></span></label></div>`)} </div>`;
  return { content, charts: [] };
}

function renderSecuritySettings(page) {
  const content = `${heroBlock(page, [{ label: "MFA coverage", value: "96%", delta: "+5 pts", tone: "success" }, { label: "Active sessions", value: "38", delta: "12 devices", tone: "primary" }, { label: "Security alerts", value: "2", delta: "review today", tone: "warning" }, { label: "Audit exports", value: "14", delta: "last 30 days", tone: "info" }])}<div class="grid gap-6 xl:grid-cols-[1fr_1fr]">${panel("Security controls", "Workspace-wide protections and login guardrails.", `<div class="space-y-4">${[["Force MFA for admins", "All admin accounts must verify via second factor.", true], ["New device review", "Flag sign-ins from new devices before full access.", true], ["Session timeout", "Expire inactive sessions after 12 hours.", false]].map(([title, copy, active]) => `<label class="flex items-center justify-between gap-4 rounded-3xl border border-[color:var(--border)] p-4"><div><p class="text-sm font-semibold text-[color:var(--text)]">${title}</p><p class="mt-1 text-sm text-[color:var(--text-soft)]">${copy}</p></div><span><input type="checkbox" class="toggle-input sr-only" ${active ? "checked" : ""} /><span class="toggle-switch"></span></span></label>`).join("")}</div>`)}${panel("Recent sessions", "Recently active sessions and security observations.", simpleTable(["User", "Location", "Device", "Status"], [["Deniz Kaya", "Istanbul", "MacBook Pro", badge("Active", "success", "status")], ["Selin Akca", "Berlin", "Chrome / Windows", badge("Active", "success", "status")], ["Mina Aksoy", "Ankara", "Safari / iPhone", badge("Review", "warning", "status")], ["Ali Gok", "Amsterdam", "Firefox / Linux", badge("Trusted", "info", "status")]]))} </div>`;
  return { content, charts: [] };
}

function renderNotificationSettings(page) {
  const content = `${heroBlock(page, [{ label: "Notification rules", value: "24", delta: "active", tone: "primary" }, { label: "Critical alerts", value: "6", delta: "always-on", tone: "danger" }, { label: "Muted digests", value: "3", delta: "focus mode", tone: "warning" }, { label: "Team channels", value: "8", delta: "connected", tone: "info" }])}${panel("Notification matrix", "Choose how each event reaches your team.", `<div class="overflow-x-auto"><table class="w-full text-sm"><thead><tr class="border-b border-[color:var(--border)] text-left text-[color:var(--text-faint)]"><th class="pb-3 pr-4 font-semibold">Event</th><th class="pb-3 pr-4 font-semibold">Email</th><th class="pb-3 pr-4 font-semibold">In-app</th><th class="pb-3 pr-4 font-semibold">SMS</th><th class="pb-3 pr-4 font-semibold">Owner</th></tr></thead><tbody>${[["Failed payment", true, true, true, "Finance"], ["High-priority ticket", true, true, false, "Support"], ["Renewal risk alert", true, true, false, "Revenue"], ["New team invite", false, true, false, "People Ops"]].map((row) => `<tr class="border-b border-[color:var(--border)]"><td class="py-4 pr-4 font-semibold text-[color:var(--text)]">${row[0]}</td><td class="py-4 pr-4">${row[1] ? badge("On", "success") : badge("Off", "danger")}</td><td class="py-4 pr-4">${row[2] ? badge("On", "success") : badge("Off", "danger")}</td><td class="py-4 pr-4">${row[3] ? badge("On", "warning") : badge("Off", "info")}</td><td class="py-4 pr-4 text-[color:var(--text-soft)]">${row[4]}</td></tr>`).join("")}</tbody></table></div>`)} `;
  return { content, charts: [] };
}

function authCard(title, description, inner) {
  return `<section class="panel p-8"><div class="mb-8"><div class="inline-flex items-center gap-2 rounded-full border border-[color:var(--border)] bg-[color:var(--bg-muted)]/60 px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.2em] text-[color:var(--text-faint)]">${icon("lock", "h-4 w-4")}Secure access</div><h2 class="mt-4 font-display text-3xl font-semibold tracking-tight text-[color:var(--text)]">${escapeHtml(title)}</h2><p class="mt-2 text-sm leading-6 text-[color:var(--text-soft)]">${escapeHtml(description)}</p></div>${inner}</section>`;
}

function renderLogin() { return { content: authCard("Sign in", "Access dashboards, billing tools and team operations.", `<form class="space-y-5"><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Email</span><input class="field" type="email" placeholder="name@company.com" value="mina@kanexus.io" /></label><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Password</span><input class="field" type="password" value="********" /></label><div class="flex items-center justify-between gap-4 text-sm"><label class="flex items-center gap-2 text-[color:var(--text-soft)]"><input type="checkbox" class="rounded border-slate-300 text-blue-600 focus:ring-blue-500" checked />Remember this device</label><a href="../auth/forgot-password.html" class="font-semibold text-blue-600">Forgot password?</a></div><a href="../../index.html" class="inline-flex w-full items-center justify-center rounded-2xl bg-blue-600 px-5 py-3 text-sm font-semibold text-white shadow-lg shadow-blue-600/20">Continue to dashboard</a></form>`), charts: [] }; }
function renderRegister() { return { content: authCard("Create account", "Start a new workspace for your operations team.", `<form class="space-y-5"><div class="grid gap-5 md:grid-cols-2"><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">First name</span><input class="field" placeholder="Mina" /></label><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Last name</span><input class="field" placeholder="Aksoy" /></label></div><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Company email</span><input class="field" type="email" placeholder="name@company.com" /></label><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Workspace name</span><input class="field" placeholder="KA Nexus" /></label><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Password</span><input class="field" type="password" placeholder="Create a secure password" /></label><button type="button" class="inline-flex w-full items-center justify-center rounded-2xl bg-blue-600 px-5 py-3 text-sm font-semibold text-white shadow-lg shadow-blue-600/20" data-toast="Workspace created">Create workspace</button></form>`), charts: [] }; }
function renderForgotPassword() { return { content: authCard("Forgot password", "Enter your email and we will send a secure reset link.", `<form class="space-y-5"><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Email</span><input class="field" type="email" placeholder="name@company.com" /></label><button type="button" class="inline-flex w-full items-center justify-center rounded-2xl bg-blue-600 px-5 py-3 text-sm font-semibold text-white" data-toast="Reset email sent">Send reset email</button></form>`), charts: [] }; }
function renderResetPassword() { return { content: authCard("Reset password", "Choose a new password for your workspace account.", `<form class="space-y-5"><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">New password</span><input class="field" type="password" placeholder="Create a new password" /></label><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Confirm password</span><input class="field" type="password" placeholder="Confirm the new password" /></label><button type="button" class="inline-flex w-full items-center justify-center rounded-2xl bg-blue-600 px-5 py-3 text-sm font-semibold text-white" data-toast="Password reset complete">Update password</button></form>`), charts: [] }; }
function renderTwoFactor() { return { content: authCard("Two-factor verification", "Confirm your sign-in with the code from your authenticator app.", `<div class="space-y-6"><div class="grid grid-cols-6 gap-3">${Array.from({ length: 6 }, () => `<input class="field text-center text-lg font-semibold" maxlength="1" value="0" />`).join("")}</div><button type="button" class="inline-flex w-full items-center justify-center rounded-2xl bg-blue-600 px-5 py-3 text-sm font-semibold text-white" data-toast="Verification successful">Verify and continue</button></div>`), charts: [] }; }
function renderPricing(page) { return renderSubscriptionPlans(page); }
function renderFaq(page) { const faqItems = [["Can I use this template for SaaS, CRM and commerce products?", "Yes. The page system is built to handle dashboards, management views, productivity tools and system states with the same visual language."], ["Does the template support dark mode?", "Yes. Theme preference is saved in local storage and applied consistently across charts, cards, forms and navigation."], ["Are the data tables interactive?", "Yes. Sorting, filtering, search, pagination, row selection, bulk actions and row menus are all wired with vanilla JavaScript."], ["Can I adapt the layout to my own backend?", "Yes. Every page is HTML-based, modular and framework-free, so it can be integrated into static or server-rendered stacks."]]; const content = `${heroBlock(page, [{ label: "Questions", value: "18", delta: "curated", tone: "primary" }, { label: "Docs coverage", value: "92%", delta: "core flows", tone: "success" }, { label: "Setup time", value: "< 10m", delta: "no build step", tone: "info" }, { label: "Support scope", value: "HTML template", delta: "framework-free", tone: "warning" }])}${panel("Frequently asked questions", "Common questions about structure, theme support and extensibility.", `<div class="space-y-4" x-data="{open:0}">${faqItems.map(([question, answer], index) => `<div class="rounded-3xl border border-[color:var(--border)] p-5"><button type="button" class="flex w-full items-center justify-between gap-4 text-left" @click="open = open === ${index} ? -1 : ${index}"><span class="text-base font-semibold text-[color:var(--text)]">${escapeHtml(question)}</span>${icon("chevronDown", "h-4 w-4")}</button><div class="pt-4 text-sm leading-6 text-[color:var(--text-soft)]" x-show="open === ${index}">${escapeHtml(answer)}</div></div>`).join("")}</div>`)}`; return { content, charts: [] }; }
function renderBlank(page) { const content = `${heroBlock(page, [{ label: "Starter modules", value: "6", delta: "ready to clone", tone: "primary" }, { label: "Reusable cards", value: "20+", delta: "stat + chart + form", tone: "success" }, { label: "Grid regions", value: "3", delta: "hero, body, sidebar", tone: "info" }, { label: "Notes", value: "Build here", delta: "starter canvas", tone: "warning" }])}<div class="grid gap-6 xl:grid-cols-[1.2fr_.8fr]">${panel("Starter canvas", "Use this page as a clean extension point for a new module.", `<div class="rounded-[2rem] border border-dashed border-[color:var(--border-strong)] bg-[color:var(--bg-muted)]/40 p-10 text-center"><div class="mx-auto flex h-16 w-16 items-center justify-center rounded-3xl bg-white/80 text-blue-600 shadow-lg">${icon("sparkles", "h-7 w-7")}</div><h3 class="mt-5 font-display text-2xl font-semibold tracking-tight text-[color:var(--text)]">Blank page starter</h3><p class="mt-3 max-w-2xl text-sm leading-7 text-[color:var(--text-soft)] mx-auto">Keep the shared shell, header, sidebar, overlays and theme system while composing a new module. This block intentionally leaves room for your own charts, tables or forms.</p></div>`)}${panel("Starter checklist", "What to wire when you turn this into a new page.", `<div class="space-y-4">${["Define page title and group", "Add reusable cards or chart panels", "Reuse data-table shell if you need records", "Connect modals, drawers or toasts", "Document the page in README"].map((item) => `<div class="flex items-start gap-3 rounded-3xl border border-[color:var(--border)] p-4">${icon("check", "mt-0.5 h-4 w-4 text-emerald-500")}<span class="text-sm text-[color:var(--text-soft)]">${escapeHtml(item)}</span></div>`).join("")}</div>`)} </div>`; return { content, charts: [] }; }
function renderError404(page) { const depth = depthFor(page.path); return { content: `<main class="error-shell"><section class="panel max-w-3xl p-10 text-center"><div class="mx-auto flex h-20 w-20 items-center justify-center rounded-[2rem] bg-[color:var(--primary-soft)] text-[color:var(--primary)]">${icon("warning", "h-8 w-8")}</div><p class="mt-6 text-sm font-semibold uppercase tracking-[0.22em] text-[color:var(--text-faint)]">404 error</p><h1 class="mt-3 font-display text-5xl font-semibold tracking-tight text-[color:var(--text)]">The page you were looking for is not available.</h1><p class="mx-auto mt-4 max-w-2xl text-base leading-7 text-[color:var(--text-soft)]">The route may have expired, been moved, or requires a different workspace context. Use the links below to jump back into the admin template.</p><div class="mt-8 flex flex-wrap justify-center gap-3"><a href="${rootPath(depth, "index.html")}" class="rounded-2xl bg-blue-600 px-5 py-3 text-sm font-semibold text-white">Go to dashboard</a><a href="${rootPath(depth, "pages/utility/faq.html")}" class="rounded-2xl border border-[color:var(--border)] px-5 py-3 text-sm font-semibold text-[color:var(--text-soft)]">Open FAQ</a></div></section></main>`, charts: [] }; }
function renderError500(page) { const depth = depthFor(page.path); return { content: `<main class="error-shell"><section class="panel max-w-3xl p-10 text-center"><div class="mx-auto flex h-20 w-20 items-center justify-center rounded-[2rem] bg-[color:var(--danger-soft)] text-[color:var(--danger)]">${icon("server", "h-8 w-8")}</div><p class="mt-6 text-sm font-semibold uppercase tracking-[0.22em] text-[color:var(--text-faint)]">500 error</p><h1 class="mt-3 font-display text-5xl font-semibold tracking-tight text-[color:var(--text)]">A server-side issue interrupted the workflow.</h1><p class="mx-auto mt-4 max-w-2xl text-base leading-7 text-[color:var(--text-soft)]">Use this page for incident states, failed report generation or backend processing failures.</p><div class="mt-8 flex flex-wrap justify-center gap-3"><a href="${rootPath(depth, "index.html")}" class="rounded-2xl bg-blue-600 px-5 py-3 text-sm font-semibold text-white">Return to dashboard</a><a href="${rootPath(depth, "pages/utility/maintenance-page.html")}" class="rounded-2xl border border-[color:var(--border)] px-5 py-3 text-sm font-semibold text-[color:var(--text-soft)]">View maintenance page</a></div></section></main>`, charts: [] }; }
function renderMaintenance(page) { const depth = depthFor(page.path); return { content: `<main class="maintenance-shell"><section class="panel max-w-4xl p-10 text-center"><div class="mx-auto flex h-20 w-20 items-center justify-center rounded-[2rem] bg-[color:var(--warning-soft)] text-[color:var(--warning)]">${icon("settings", "h-8 w-8")}</div><p class="mt-6 text-sm font-semibold uppercase tracking-[0.22em] text-[color:var(--text-faint)]">Planned maintenance</p><h1 class="mt-3 font-display text-5xl font-semibold tracking-tight text-[color:var(--text)]">We are polishing the platform and will be back shortly.</h1><p class="mx-auto mt-4 max-w-2xl text-base leading-7 text-[color:var(--text-soft)]">Use this state for scheduled maintenance windows, data migrations or temporary release holds.</p><div class="mx-auto mt-10 grid max-w-3xl gap-4 md:grid-cols-3">${[["Start", "12 Mar 2026, 22:00 UTC", "primary"], ["Expected duration", "45 minutes", "warning"], ["Status", "Database optimization", "info"]].map(([label, value, tone]) => `<div class="rounded-3xl border border-[color:var(--border)] p-5"><p class="text-xs font-semibold uppercase tracking-[0.18em] text-[color:var(--text-faint)]">${label}</p><p class="mt-3 text-lg font-semibold text-[color:var(--text)]">${value}</p><div class="mt-3">${badge("Scheduled", tone)}</div></div>`).join("")}</div><div class="mt-8 flex flex-wrap justify-center gap-3"><a href="${rootPath(depth, "index.html")}" class="rounded-2xl bg-blue-600 px-5 py-3 text-sm font-semibold text-white">Back to dashboard</a><button type="button" class="rounded-2xl border border-[color:var(--border)] px-5 py-3 text-sm font-semibold text-[color:var(--text-soft)]" data-toast="Status alert subscribed">Notify me</button></div></section></main>`, charts: [] }; }

const renderers = { dashboardOverview: renderDashboardOverview, analyticsDashboard: renderAnalyticsDashboard, crmDashboard: renderCrmDashboard, ecommerceDashboard: renderEcommerceDashboard, customersList: renderCustomersList, customerDetail: renderCustomerDetail, ordersList: renderOrdersList, orderDetail: renderOrderDetail, productsList: renderProductsList, productDetail: renderProductDetail, addNewProduct: renderAddNewProduct, categories: renderCategories, transactions: renderTransactions, invoices: renderInvoices, invoiceDetail: renderInvoiceDetail, subscriptionPlans: renderSubscriptionPlans, subscribersList: renderSubscribersList, billingOverview: renderBillingOverview, revenueReports: renderRevenueReports, supportTickets: renderSupportTickets, ticketDetail: renderTicketDetail, calendar: renderCalendar, kanban: renderKanban, messages: renderMessages, chat: renderChat, fileManager: renderFileManager, teamMembers: renderTeamMembers, rolesPermissions: renderRolesPermissions, userProfile: renderUserProfile, accountSettings: renderAccountSettings, securitySettings: renderSecuritySettings, notificationSettings: renderNotificationSettings, login: renderLogin, register: renderRegister, forgotPassword: renderForgotPassword, resetPassword: renderResetPassword, twoFactor: renderTwoFactor, pricing: renderPricing, faq: renderFaq, blank: renderBlank, error404: renderError404, error500: renderError500, maintenance: renderMaintenance };

function buildPage(page) {
  const renderer = renderers[page.render];
  const rendered = renderer(page);
  if (page.shell === "app") return appShell(page, rendered.content, rendered.charts || []);
  if (page.shell === "auth") return authShell(page, rendered.content);
  return specialShell(page, rendered.content);
}

function componentSnippets() {
  return {
    "components/layout/app-shell.html": `<div class="shell-main min-h-screen"><header class="header-shell"><div class="mx-auto w-full max-w-[1680px] px-4 py-4 lg:px-6">...</div></header><main class="px-4 py-6 lg:px-6"><div class="mx-auto flex w-full max-w-[1680px] flex-col gap-6">...</div></main></div>`,
    "components/cards/stat-card.html": `<article class="panel stat-card p-5"><p class="text-sm font-semibold text-[color:var(--text-soft)]">Total Revenue</p><p class="mt-3 font-display text-3xl font-semibold tracking-tight text-[color:var(--text)]">$142.8k</p><div class="mt-4 inline-flex">${badge("+12.6%", "success")}</div></article>`,
    "components/tables/data-table.html": `<section class="panel overflow-hidden"><div class="border-b border-[color:var(--border)] p-6">Table header and controls</div><div class="data-table-shell overflow-x-auto">Interactive table rows</div></section>`,
    "components/forms/settings-form.html": `<form class="space-y-5"><label class="block"><span class="mb-2 block text-sm font-semibold text-[color:var(--text)]">Field label</span><input class="field" placeholder="Example value" /></label></form>`,
    "components/charts/chart-card.html": `<section class="panel p-6"><div class="mb-5"><h3 class="font-display text-xl font-semibold tracking-tight text-[color:var(--text)]">Chart title</h3><p class="mt-1 text-sm text-[color:var(--text-soft)]">Supporting description</p></div><div style="height:320px"><canvas id="chart-id"></canvas></div></section>`,
  };
}

function images() {
  const logoSvg = `<?xml version="1.0" encoding="UTF-8"?><svg width="160" height="160" viewBox="0 0 160 160" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="160" height="160" rx="40" fill="#0F172A"/><path d="M40 44L80 32L120 44V116L80 128L40 116V44Z" stroke="white" stroke-width="10" stroke-linejoin="round"/><path d="M80 32V128" stroke="#60A5FA" stroke-width="10" stroke-linecap="round"/><path d="M40 44L80 56L120 44" stroke="#CBD5E1" stroke-width="10" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
  const illustrationSvg = `<?xml version="1.0" encoding="UTF-8"?><svg width="720" height="420" viewBox="0 0 720 420" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="720" height="420" rx="32" fill="#F4F7FB"/><rect x="28" y="28" width="164" height="364" rx="24" fill="white"/><rect x="220" y="28" width="472" height="68" rx="24" fill="white"/><rect x="220" y="120" width="220" height="112" rx="28" fill="white"/><rect x="460" y="120" width="232" height="112" rx="28" fill="white"/><rect x="220" y="256" width="472" height="136" rx="28" fill="white"/><path d="M260 208C288 164 320 152 356 164C392 176 418 154 452 136" stroke="#2563EB" stroke-width="12" stroke-linecap="round"/><circle cx="260" cy="208" r="10" fill="#2563EB"/><circle cx="356" cy="164" r="10" fill="#2563EB"/><circle cx="452" cy="136" r="10" fill="#2563EB"/><rect x="248" y="144" width="76" height="16" rx="8" fill="#E2E8F0"/><rect x="248" y="168" width="112" height="14" rx="7" fill="#CBD5E1"/><rect x="488" y="152" width="132" height="120" rx="20" fill="#EFF6FF"/><rect x="516" y="188" width="24" height="60" rx="12" fill="#2563EB"/><rect x="552" y="168" width="24" height="80" rx="12" fill="#0F766E"/><rect x="588" y="204" width="24" height="44" rx="12" fill="#D97706"/><rect x="248" y="286" width="164" height="14" rx="7" fill="#CBD5E1"/><rect x="248" y="316" width="416" height="10" rx="5" fill="#E2E8F0"/><rect x="248" y="338" width="388" height="10" rx="5" fill="#E2E8F0"/><rect x="248" y="360" width="300" height="10" rx="5" fill="#E2E8F0"/></svg>`;
  const screenshotSvg = `<?xml version="1.0" encoding="UTF-8"?><svg width="1280" height="720" viewBox="0 0 1280 720" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="1280" height="720" rx="40" fill="#F4F7FB"/><rect x="30" y="30" width="260" height="660" rx="32" fill="#FFFFFF"/><rect x="320" y="30" width="930" height="90" rx="30" fill="#FFFFFF"/><rect x="320" y="150" width="930" height="165" rx="34" fill="#FFFFFF"/><rect x="320" y="340" width="600" height="170" rx="34" fill="#FFFFFF"/><rect x="950" y="340" width="300" height="170" rx="34" fill="#FFFFFF"/><rect x="320" y="535" width="930" height="155" rx="34" fill="#FFFFFF"/><rect x="76" y="88" width="120" height="120" rx="28" fill="#0F172A"/><path d="M76 248H238" stroke="#E2E8F0" stroke-width="20" stroke-linecap="round"/><path d="M76 300H220" stroke="#E2E8F0" stroke-width="20" stroke-linecap="round"/><path d="M76 352H230" stroke="#E2E8F0" stroke-width="20" stroke-linecap="round"/><path d="M380 250C450 170 540 146 646 176C760 208 838 178 922 130" stroke="#2563EB" stroke-width="18" stroke-linecap="round"/><circle cx="380" cy="250" r="12" fill="#2563EB"/><circle cx="646" cy="176" r="12" fill="#2563EB"/><circle cx="922" cy="130" r="12" fill="#2563EB"/><rect x="992" y="380" width="56" height="88" rx="18" fill="#2563EB"/><rect x="1070" y="350" width="56" height="118" rx="18" fill="#0F766E"/><rect x="1148" y="398" width="56" height="70" rx="18" fill="#D97706"/><rect x="370" y="575" width="180" height="16" rx="8" fill="#CBD5E1"/><rect x="370" y="615" width="800" height="12" rx="6" fill="#E2E8F0"/><rect x="370" y="643" width="730" height="12" rx="6" fill="#E2E8F0"/></svg>`;
  return { "assets/icons/logo-mark.svg": logoSvg, "assets/images/panel-wave.svg": illustrationSvg, "screenshot/ka-nexus-preview.svg": screenshotSvg };
}

function readme() {
  return `# KA Nexus Admin\n\nKA Nexus Admin is a premium HTML admin dashboard template for SaaS products, CRM systems, analytics workspaces, commerce back offices and internal operations tools.\n\n## Stack\n\n- HTML5\n- TailwindCSS (CDN runtime)\n- Alpine.js\n- Vanilla JavaScript\n- Chart.js\n\n## Highlights\n\n- 40+ HTML pages with consistent layout and dark mode support\n- Responsive collapsible sidebar and sticky header\n- Reusable stat cards, chart cards, tables, forms and timeline widgets\n- Interactive data tables with search, filtering, sorting, pagination and bulk actions\n- Modal, drawer, toast, tabs, accordions and toggle switch patterns\n- Dashboard pages for overview, analytics, CRM and e-commerce\n- Management, business, productivity, team, auth and utility pages\n\n## Structure\n\n\`\`\`\nassets/\n  css/\n  js/\n  images/\n  icons/\ncomponents/\n  layout/\n  cards/\n  tables/\n  forms/\n  charts/\npages/\n  dashboard/\n  management/\n  business/\n  productivity/\n  team/\n  auth/\n  utility/\nscreenshot/\nindex.html\nREADME.md\n\`\`\`\n\n## Usage\n\nOpen \`index.html\` directly in a browser, or serve the project through any static file server.\n\n## Notes\n\n- Demo content is fictional and provided for UI presentation.\n- Theme preference and sidebar state are stored in local storage.\n- Charts automatically adapt to light and dark mode.\n`;
}

for (const page of pages) {
  writeFile(page.path, buildPage(page));
}
for (const [filePath, content] of Object.entries(componentSnippets())) {
  writeFile(filePath, `${content}\n`);
}
for (const [filePath, content] of Object.entries(images())) {
  writeFile(filePath, content);
}
writeFile("README.md", readme());
console.log(`Generated ${pages.length} pages and supporting assets.`);

