const state = {
  token: "",
  user: null,
  view: "dashboard",
  summary: null,
  transactions: [],
  applications: [],
  financeRows: [],
  taxRules: [],
  auditLogs: [],
  notaries: [],
  staffMembers: [],
  settings: null,
  issuedCredentials: null,
  issuedStaffCredentials: null,
  editingStaffId: null,
  mustChangePassword: false,
  auditLogFilters: {
    user: "",
    action: "",
    details: "",
    ip: "",
    date: ""
  },
  message: ""
};

const menus = {
  super_admin: ["dashboard", "applications", "notaries", "finance", "tax_rules", "audit_logs", "settings"],
  ministry_justice: ["dashboard", "applications", "notaries", "audit_logs", "tax_rules", "settings"],
  ministry_finance: ["dashboard", "notaries", "finance", "audit_logs", "tax_rules", "settings"],
  owner: ["dashboard", "create_transaction", "transactions", "staff", "id-cards", "license", "audit_logs", "tax_rules", "settings"],
  teller: ["dashboard", "create_transaction", "transactions"],
  payment: ["dashboard", "payments", "transactions", "settings"],
  executive: ["dashboard", "approvals", "transactions", "settings"]
};

const menuLabels = {
  dashboard: "Dashboard",
  applications: "Applications",
  notaries: "Notaries",
  finance: "Finance Report",
  tax_rules: "Tax Rules",
  audit_logs: "Audit Logs",
  create_transaction: "New Transaction",
  transactions: "Transactions",
  payments: "Payments",
  approvals: "Approvals",
  staff: "Staff",
  "id-cards": "Staff ID Cards",
  license: "Office License",
  settings: "Settings"
};

const badgeLabels = {
  super_admin: "SUPER ADMIN",
  ministry_justice: "JUSTICE",
  ministry_finance: "FINANCE",
  owner: "OWNER",
  teller: "TELLER",
  payment: "PAYMENT",
  executive: "EXECUTIVE"
};

const app = document.getElementById("app");

const serviceOptions = [
  "evidence",
  "power_of_attorney",
  "agreement",
  "gift",
  "sale",
  "will",
  "boat",
  "investment",
  "guarantee"
];

const assetOptions = [
  "general",
  "land",
  "house",
  "vehicle_small",
  "vehicle_large",
  "motorcycle",
  "shares",
  "ownership",
  "sale",
  "asset",
  "other"
];

const demoCredentials = [
  "admin@enotary.gov / admin123",
  "justice@enotary.gov / justice123",
  "finance@enotary.gov / finance123",
  "owner@notary.so / owner123",
  "teller@notary.so / teller123",
  "payment@notary.so / payment123",
  "executive@notary.so / exec123"
];

const formatLabel = (value) =>
  String(value || "")
    .replaceAll("_", " ")
    .replace(/\b\w/g, (letter) => letter.toUpperCase());

const api = async (path, options = {}) => {
  const headers = { ...(options.headers || {}) };
  if (!(options.body instanceof FormData)) {
    headers["Content-Type"] = "application/json";
  }
  if (state.token) {
    headers.Authorization = `Bearer ${state.token}`;
  }

  // Back to a more standard relative path if available, or force current path
  const url = path.startsWith("/api") ? "api" + path.substring(4) : path;
  console.log(`[API Request] ${options.method || 'GET'} ${url}`);
  
  const response = await fetch(url, { ...options, headers });
  const data = await response.json().catch(() => ({}));

  if (!response.ok) {
    console.error(`[API Error] ${url}`, data);
    throw new Error(data.message || "Request failed");
  }
  return data;
};

const money = (value) =>
  new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD"
  }).format(Number(value || 0));

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

const formatDate = (dateString, fallback = "-") => {
  if (!dateString || dateString === fallback || dateString === "Pending" || dateString === "N/A") return dateString || fallback;
  const date = new Date(dateString);
  if (isNaN(date)) return dateString;
  return new Intl.DateTimeFormat('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }).format(date);
};

const notify = (title, message, channel = "SMS") => {
  console.log(`[Notification ${channel}]: ${title} - ${message}`);
  // Only show simulation if notifications are enabled or for testing
  const toast = document.createElement("div");
  toast.className = "notification-toast";
  toast.innerHTML = `
    <div class="toast-icon">${channel === 'SMS' ? '📱' : '📧'}</div>
    <div class="toast-content">
      <strong>${escapeHtml(title)}</strong>
      <p>${escapeHtml(message)}</p>
    </div>
  `;
  document.body.appendChild(toast);
  setTimeout(() => {
    toast.classList.add("show");
    setTimeout(() => {
      toast.classList.remove("show");
      setTimeout(() => toast.remove(), 500);
    }, 4000);
  }, 100);
};
const exportCSV = (data, filename = "report.csv") => {
  if (!data || !data.length) {
    alert("Ma jirto xog la dhoofiyo.");
    return;
  }
  
  const headers = Object.keys(data[0]);
  const csvContent = [
    headers.join(","),
    ...data.map(row => headers.map(h => {
        const val = row[h] === null || row[h] === undefined ? "" : String(row[h]);
        return `"${val.replace(/"/g, '""')}"`;
    }).join(","))
  ].join("\n");

  const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
  const link = document.createElement("a");
  const url = URL.createObjectURL(blob);
  link.setAttribute("href", url);
  link.setAttribute("download", filename);
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const statusChip = (status) =>
  `<span class="status-chip ${escapeHtml(status)}">${escapeHtml(formatLabel(status))}</span>`;

const setMessage = (message) => {
  state.message = message;
};

const clearMessage = () => {
  state.message = "";
  state.issuedCredentials = null;
  state.issuedStaffCredentials = null;
  state.editingStaffId = null;
};

const copyCredentials = (type = "notary") => {
  const data = type === "staff" ? state.issuedStaffCredentials : state.issuedCredentials;
  if (!data) return;
  const text = `Name: ${data.owner_name}\nUsername: ${data.username}\nTemporary Password: ${data.temporary_password}`;
  navigator.clipboard.writeText(text).then(() => {
    alert("Credentials copied to clipboard!");
  });
};

const dashboardSubtitleByRole = {
  owner: "Overview of activity and metrics.",
  teller: "Prepare and submit new legal filings.",
  payment: "Track pending collections and completed receipts.",
  executive: "Review paid files and finalize decisions.",
  ministry_finance: "National financial oversight and tax reporting.",
  ministry_justice: "Review applications and monitor office activity.",
  super_admin: "System-wide overview of usage and compliance."
};

const placeholderCard = (title, copy) => `
  <section class="page-intro">
    <div>
      <h2>${escapeHtml(title)}</h2>
      <p class="muted">${escapeHtml(copy)}</p>
    </div>
  </section>
  <section class="card placeholder-card">
    <h3>${escapeHtml(title)}</h3>
    <p class="muted">${escapeHtml(copy)}</p>
  </section>
`;

const fetchProtectedData = async () => {
  const [summary, transactions] = await Promise.all([
    api("/api/reports/dashboard"),
    api("/api/transactions")
  ]);

  state.summary = summary;
  state.transactions = transactions;

  state.applications = ["super_admin", "ministry_justice"].includes(state.user.role)
    ? await api("/api/applications")
    : [];

  state.financeRows = ["super_admin", "ministry_finance"].includes(state.user.role)
    ? await api("/api/reports/finance")
    : [];

  state.notaries = ["super_admin", "ministry_finance", "ministry_justice"].includes(state.user.role)
    ? await api("/api/notaries")
    : [];

  state.taxRules = ["super_admin", "ministry_finance", "ministry_justice", "owner", "teller"].includes(state.user.role)
    ? await api("/api/tax-rules")
    : [];

  state.auditLogs = ["super_admin", "ministry_finance", "ministry_justice", "owner"].includes(
    state.user.role
  )
    ? await api("/api/audit-logs")
    : [];

  state.staffMembers = state.user.role === "owner" ? await api("/api/staff") : [];
  state.settings =
    ["owner", "super_admin", "ministry_finance", "ministry_justice", "payment", "executive"].includes(
      state.user.role
    )
      ? await api("/api/settings")
      : null;
};

const renderLogin = (error = "") => {
  app.innerHTML = `
    <div class="login-shell">
      <section class="login-hero">
        <img src="logo.jpg" alt="State logo" />
        <h1>North East State of Somalia Justice & Notarial Services</h1>
        <p>Official platform for notary offices to manage legal transactions, tax calculations, and government reporting securely.</p>
      </section>
      <section class="login-panel">
        <div>
          <h2>Welcome back</h2>
          <p class="muted">Sign in to your E-Notary account</p>
        </div>
        <form id="login-form" class="panel-card">
          <label>Email address<input name="email" value="owner@notary.so" required /></label>
          <label>Password<input name="password" type="password" value="owner123" required /></label>
          <button class="solid-button" type="submit">Sign in</button>
          ${error ? `<p class="error">${escapeHtml(error)}</p>` : ""}
        </form>
        <button id="open-application" class="link-button">Apply to register your notary office</button>
        <a href="#notaries-directory" class="link-button" style="text-decoration: none; color: var(--accent);">Search for registered Notary Offices (Public Directory)</a>
        <section class="card creds-card">
          <h3>Demo Credentials</h3>
          ${demoCredentials
            .map((item) => `<p class="muted">${escapeHtml(item)}</p>`)
            .join("")}
        </section>
      </section>
    </div>
  `;

  document.getElementById("login-form").addEventListener("submit", async (event) => {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    try {
      const data = await api("/api/auth/login", {
        method: "POST",
        body: JSON.stringify({
          email: form.get("email"),
          password: form.get("password")
        })
      });
      state.token = data.token;
      state.user = data.user;
      state.mustChangePassword = Boolean(data.user.password_must_change);
      state.view = "dashboard";
      
      localStorage.setItem("nesos_token", data.token);
      localStorage.setItem("nesos_user", JSON.stringify(data.user));

      clearMessage();
      if (state.mustChangePassword) {
        renderForcedPasswordChange();
      } else {
        if (state.user.notary?.issued_date) {
            const issuedDate = new Date(state.user.notary.issued_date);
            const now = new Date();
            const diffHours = (now - issuedDate) / (1000 * 60 * 60);
            if (diffHours < 24 && !localStorage.getItem(`welcomed_${state.user.notary.issued_date}`)) {
              localStorage.setItem(`welcomed_${state.user.notary.issued_date}`, 'true');
              alert(`Welcome back!\nYour notary license has been successfully renewed.\n\nNew Issue Date: ${formatDate(state.user.notary.issued_date)}\nNew Expiry Date: ${formatDate(state.user.notary.expired_date)}`);
            }
        }
        await fetchProtectedData();
        renderApp();
      }
    } catch (error) {
      renderLogin(error.message);
    }
  });

  document.getElementById("open-application").addEventListener("click", () => renderApplicationForm());
};

const renderForcedPasswordChange = (error = "", success = "") => {
  app.innerHTML = `
    <div class="login-shell">
      <section class="login-hero">
        <img src="logo.jpg" alt="State logo" />
        <h1>Change Your Temporary Password</h1>
        <p>Your office has been approved. For security, you must create a new password before entering the system.</p>
      </section>
      <section class="login-panel">
        <div>
          <h2>First Login Security Step</h2>
          <p class="muted">${escapeHtml(state.user?.email || "")}</p>
        </div>
        <form id="force-password-form" class="panel-card">
          <label>New password<input name="new_password" type="password" required /></label>
          <label>Confirm password<input name="confirm_password" type="password" required /></label>
          <button class="solid-button" type="submit">Save new password</button>
          ${error ? `<p class="error">${escapeHtml(error)}</p>` : ""}
          ${success ? `<p class="success-text">${escapeHtml(success)}</p>` : ""}
        </form>
      </section>
    </div>
  `;

  document.getElementById("force-password-form").addEventListener("submit", async (event) => {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    const newPassword = String(form.get("new_password") || "");
    const confirmPassword = String(form.get("confirm_password") || "");
    if (newPassword !== confirmPassword) {
      renderForcedPasswordChange("Passwords do not match.");
      return;
    }
    try {
      await api("/api/auth/change-password", {
        method: "POST",
        body: JSON.stringify({ new_password: newPassword })
      });
      
      // Update local state and storage IMMEDIATELY
      state.mustChangePassword = false;
      if (state.user) {
        state.user.password_must_change = 0;
        localStorage.setItem("nesos_user", JSON.stringify(state.user));
      }
      
      setMessage("Password-kaaga si guul leh ayaa loo beddelay. Hadda waad isticmaali kartaa nidaamka.");
      await fetchProtectedData();
      renderApp();
    } catch (error) {
      renderForcedPasswordChange(error.message);
    }
  });
};

const renderApplicationForm = (message = "") => {
  app.innerHTML = `
    <div class="login-shell">
      <section class="login-hero">
        <img src="logo.jpg" alt="State logo" />
        <h1>Apply to Register a Notary Office</h1>
        <p>Submit your office profile so the Ministry of Justice can review and activate your tenant account.</p>
      </section>
      <section class="login-panel">
        <form id="application-form" class="panel-card">
          <label>Office name<input name="name" required /></label>
          <label>Applicant full name<input name="applicant_name" required /></label>
          <label>Applicant email<input name="applicant_email" type="email" required /></label>
          <label>Applicant phone<input name="applicant_phone" required /></label>
          <label>Region<input name="region" required /></label>
          <label>District<input name="district" required /></label>
          <label>Category
            <select name="category">
              <option>A</option>
              <option>B</option>
              <option>C</option>
              <option>D</option>
            </select>
          </label>
          <label>Status
            <select name="registration_type">
              <option value="new">New</option>
              <option value="renewed">Renewed</option>
            </select>
          </label>
          <label>Issue Date<input name="issued_date" type="date" required /></label>
          <label>Expiry Date<input name="expired_date" type="date" required /></label>
          <label>License document
            <input id="license-file" name="license_upload" type="file" accept=".pdf,.jpg,.jpeg,.png" required />
          </label>
          <label>Stored file name
            <input id="license-path" name="license_file" value="" placeholder="Choose a file above" readonly required />
          </label>
          <button class="solid-button" type="submit">Submit application</button>
          ${message ? `<p class="success-text">${escapeHtml(message)}</p>` : ""}
        </form>
        <button id="back-login" class="ghost-button">Back to login</button>
      </section>
    </div>
  `;

  document.getElementById("application-form").addEventListener("submit", async (event) => {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    await api("/api/applications", {
      method: "POST",
      body: JSON.stringify(Object.fromEntries(form.entries()))
    });
    renderApplicationForm("Application submitted successfully.");
  });

  document.getElementById("license-file").addEventListener("change", (event) => {
    const file = event.target.files?.[0];
    const target = document.getElementById("license-path");
    target.value = file ? `uploads/${file.name}` : "";
  });

  document.getElementById("back-login").addEventListener("click", () => renderLogin());
};

const statCards = () => {
  const items =
    state.user.role === "ministry_finance"
      ? [
          ["Total Revenue", money(state.summary.totalRevenue)],
          ["Total Tax Collected", money(state.summary.totalTax)],
          ["Transactions Today", state.summary.transactionsToday]
        ]
      : [
          ["Total Transactions", state.transactions.length],
          ["Pending", state.transactions.filter((item) => item.status === "pending").length],
          ["Paid", state.transactions.filter((item) => item.status === "paid").length],
          ["Completed", state.transactions.filter((item) => item.status === "completed").length]
        ];

  return items
    .map(
      ([label, value]) => `
        <article class="card stat-card">
          <p class="muted">${escapeHtml(label)}</p>
          <strong>${escapeHtml(value)}</strong>
        </article>
      `
    )
    .join("");
};

const chartRows = () => {
  const entries = Object.entries(state.summary.byService || {});
  const max = Math.max(1, ...entries.map(([, total]) => Number(total)));

  return entries
    .map(
      ([label, total]) => `
        <div class="bar-row">
          <span>${escapeHtml(formatLabel(label))}</span>
          <div class="bar-track">
            <div class="bar-fill" style="width:${(Number(total) / max) * 100}%"></div>
          </div>
        </div>
      `
    )
    .join("");
};

const renderTransactionsTable = (filterFn = () => true, actionRenderer = () => "") => `
  <section class="card">
    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Customer</th>
            <th>Service</th>
            <th>Asset</th>
            <th>Amount</th>
            <th>Tax</th>
            <th>Total</th>
            <th>Status</th>
            <th>Archive</th>
            <th>Invoice</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          ${state.transactions
            .filter(filterFn)
            .map(
              (item) => `
                <tr>
                  <td>${item.id}</td>
                  <td>${escapeHtml(item.client_name)}</td>
                  <td>${escapeHtml(formatLabel(item.type))}</td>
                  <td>${escapeHtml(formatLabel(item.asset_type))}</td>
                  <td>${money(item.amount)}</td>
                  <td>${money(item.tax_amount)}</td>
                  <td>${money(item.total_amount)}</td>
                  <td>${statusChip(item.status)}</td>
                  <td>
                    ${item.attachment_path 
                      ? `<a href="${window.location.pathname.replace(/\/(index\.html)?$/, '').replace(/\/$/, '')}${item.attachment_path}" target="_blank" class="link-button" style="font-size: 0.75rem;">View File</a>` 
                      : '<span class="muted">N/A</span>'}
                  </td>
                  <td><a href="#invoice/${item.id}" class="ghost-button small-btn" style="padding: 2px 8px; font-size: 0.75rem;">View</a></td>
                  <td>
                    ${
                      state.user.role === 'teller' && item.status === 'returned'
                        ? `<button class="solid-button action-edit-trx" data-id="${item.id}" style="padding: 2px 8px; font-size: 0.75rem; background: var(--warning); color: #000;">Edit & Fix</button>`
                        : actionRenderer(item)
                    }
                  </td>
                </tr>
              `
            )
            .join("")}
        </tbody>
      </table>
    </div>
  </section>
`;

const renderDashboardHome = () => `
  <section class="page-intro">
    <div>
      <h2>Dashboard</h2>
      <p class="muted">${escapeHtml(dashboardSubtitleByRole[state.user.role] || "Overview of activity and metrics.")}</p>
    </div>
  </section>
  <section class="stats-grid">${statCards()}</section>
  <section class="dual-grid">
    <section class="card chart-card">
      <h3>Status Breakdown</h3>
      <div class="donut-wrap">
        <div class="donut-ring"></div>
      </div>
      <div class="legend-row">
        <span><i class="legend-dot legend-paid"></i>Paid</span>
        <span><i class="legend-dot legend-completed"></i>Completed</span>
        <span><i class="legend-dot legend-pending"></i>Pending</span>
      </div>
    </section>
    <section class="card chart-card">
      <h3>Transaction Types</h3>
      <div class="bars">${chartRows()}</div>
    </section>
  </section>
  <section class="card">
    <div class="section-head">
      <h3>Recent Transactions</h3>
      <span class="muted">Latest office activity</span>
    </div>
    <div class="list-stack">
      ${state.transactions
        .slice(0, 6)
        .map(
          (item) => `
            <article class="transaction-row">
              <div>
                <strong>${escapeHtml(item.client_name)}</strong>
                <p class="muted">${escapeHtml(formatLabel(item.type))} | ${money(item.total_amount)}</p>
              </div>
              <div class="list-meta">
                <span class="muted">${String(item.created_at || "").slice(0, 10)}</span>
                ${statusChip(item.status)}
              </div>
            </article>
          `
        )
        .join("")}
    </div>
  </section>
`;

const renderIdCardsView = () => {
  const staff = state.staffMembers.filter((s) => s.staff_id_code);

  return `
    <div class="view-header">
      <div>
        <h1>Staff ID Cards</h1>
        <p class="muted">Generate and print official ID cards for your staff members.</p>
      </div>
      <button class="solid-button" onclick="window.print()">Print All Cards</button>
    </div>

    <div class="id-card-grid">
      ${staff
        .map((row) => {
          const verifyUrl = `${window.location.origin}${window.location.pathname}#verify/${row.staff_id_code}`;
          const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=${encodeURIComponent(
            verifyUrl
          )}`;

          return `
          <div class="id-card">
            <div class="card-inner">
              <div class="card-front">
                <div class="id-brand">
                  <img src="logo.jpg" alt="Logo" />
                  <span>North East State E-Notary</span>
                </div>
                <div class="id-body">
                  <div class="id-photo-placeholder">
                    <svg viewBox="0 0 24 24"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/></svg>
                  </div>
                  <div class="id-info">
                    <h2>${escapeHtml(row.name)}</h2>
                    <p class="role">${escapeHtml(formatLabel(row.role))}</p>
                    <p class="id-num">ID: <strong>${escapeHtml(row.staff_id_code)}</strong></p>
                  </div>
                </div>
                <div class="id-footer">
                  <div class="id-qr">
                    <img src="${qrUrl}" alt="QR Code" />
                    <span>Scan to verify</span>
                  </div>
                  <div class="id-notary">
                    <p>${escapeHtml(state.user.notary?.name || "Official Office")}</p>
                    <small>Issued: ${new Date().toLocaleDateString()}</small>
                  </div>
                </div>
              </div>
            </div>
          </div>
        `;
        })
        .join("")}
    </div>
    
    <style>
      .id-card-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
        gap: 24px;
        margin-top: 24px;
      }
      .id-card {
        width: 350px;
        height: 220px;
        perspective: 1000px;
        margin: 0 auto;
      }
      .card-inner {
        width: 100%;
        height: 100%;
        position: relative;
        background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
        color: white;
        border-radius: 12px;
        box-shadow: 0 10px 25px rgba(0,0,0,0.2);
        padding: 16px;
        display: flex;
        flex-direction: column;
        border: 1px solid rgba(255,255,255,0.1);
      }
      .id-brand {
        display: flex;
        align-items: center;
        gap: 8px;
        border-bottom: 1px solid rgba(255,255,255,0.1);
        padding-bottom: 8px;
        margin-bottom: 12px;
      }
      .id-brand img { width: 30px; height: 30px; border-radius: 50%; }
      .id-brand span { font-size: 0.8rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
      
      .id-body {
        display: flex;
        gap: 16px;
        align-items: center;
        flex: 1;
      }
      .id-photo-placeholder {
        width: 70px;
        height: 85px;
        background: rgba(255,255,255,0.1);
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .id-photo-placeholder svg { width: 40px; fill: rgba(255,255,255,0.3); }
      
      .id-info h2 { margin: 0; font-size: 1.1rem; }
      .id-info .role { color: var(--accent); font-weight: 600; margin: 2px 0; font-size: 0.9rem; }
      .id-info .id-num { font-size: 0.8rem; margin: 4px 0; opacity: 0.8; }
      
      .id-footer {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        margin-top: auto;
      }
      .id-qr { display: flex; flex-direction: column; align-items: center; gap: 2px; }
      .id-qr img { width: 50px; height: 50px; background: white; padding: 2px; border-radius: 4px; }
      .id-qr span { font-size: 0.6rem; opacity: 0.7; }
      
      .id-notary { text-align: right; }
      .id-notary p { margin: 0; font-size: 0.75rem; font-weight: 600; max-width: 150px; }
      .id-notary small { font-size: 0.6rem; opacity: 0.6; }

      @media print {
        .app-shell { display: block !important; padding: 0 !important; }
        .sidebar, .view-header, header { display: none !important; }
        .id-card-grid { display: block !important; }
        .id-card { break-inside: avoid; margin-bottom: 20px !important; }
      }
    </style>
  `;
};

const renderPublicVerification = async (code) => {
  try {
    const data = await api(`/api/public/verify-staff/${code}`);
    app.innerHTML = `
      <div class="login-shell">
        <section class="login-panel">
          <div class="card" style="text-align: center; padding: 40px; max-width: 450px; width: 100%;">
            <div style="margin-bottom: 24px;">
              <div style="width: 80px; height: 80px; background: #22c55e; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto;">
                <svg style="width: 40px; fill: white;" viewBox="0 0 24 24"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>
              </div>
              <h2 style="margin-top: 16px;">Verified Staff Member</h2>
              <p class="muted">This ID has been successfully verified by North East State E-Notary System.</p>
            </div>
            
            <div style="background: #f8fafc; padding: 24px; border-radius: 12px; text-align: left; border: 1px solid #e2e8f0;">
              <p style="margin: 0 0 4px; font-size: 0.8rem; text-transform: uppercase; color: #64748b;">Full Name</p>
              <h3 style="margin: 0 0 16px;">${escapeHtml(data.name)}</h3>
              
              <p style="margin: 0 0 4px; font-size: 0.8rem; text-transform: uppercase; color: #64748b;">Official Role</p>
              <p style="margin: 0 0 16px; font-weight: 600; color: var(--accent);">${escapeHtml(
                formatLabel(data.role)
              )}</p>
              
              <p style="margin: 0 0 4px; font-size: 0.8rem; text-transform: uppercase; color: #64748b;">Notary Office</p>
              <p style="margin: 0 0 16px; font-weight: 600;">${escapeHtml(data.notary_name)}</p>
              
              <p style="margin: 0 0 4px; font-size: 0.8rem; text-transform: uppercase; color: #64748b;">Location</p>
              <p style="margin: 0;">${escapeHtml(data.region)}, ${escapeHtml(data.district)}</p>
            </div>
            
            <button class="solid-button" style="margin-top: 24px; width: 100%;" onclick="window.location.hash = ''">Back to Login</button>
          </div>
        </section>
      </div>
    `;
  } catch (err) {
    app.innerHTML = `
      <div class="login-shell">
        <section class="login-panel">
          <div class="card" style="text-align: center; padding: 40px; max-width: 450px; width: 100%;">
            <div style="width: 80px; height: 80px; background: #ef4444; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 24px;">
              <svg style="width: 40px; fill: white;" viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>
            </div>
            <h2>Verification Failed</h2>
            <p class="error">${escapeHtml(err.message)}</p>
            <button class="solid-button" style="margin-top: 24px; width: 100%;" onclick="window.location.hash = ''">Back to Login</button>
          </div>
        </section>
      </div>
     `;
  }
};

const renderPublicNotaryVerification = async (id) => {
  try {
    const data = await api(`/api/public/verify-notary/${id}`);
    const isExpired = data.expired_date && new Date() > new Date(data.expired_date);
    const isValid = data.status === 'active' && !isExpired;

    app.innerHTML = `
      <div class="login-shell">
        <section class="login-panel">
          <div class="card" style="text-align: center; padding: 40px; max-width: 500px; width: 100%;">
            <div style="margin-bottom: 24px;">
              <div style="width: 80px; height: 80px; background: ${isValid ? '#22c55e' : '#ef4444'}; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto;">
                ${isValid 
                  ? '<svg style="width: 40px; fill: white;" viewBox="0 0 24 24"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>'
                  : '<svg style="width: 40px; fill: white;" viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>'
                }
              </div>
              <h2 style="margin-top: 16px;">${isValid ? 'Verified Notary Office' : 'Invalid License'}</h2>
              <p class="muted">Status: <strong style="color: ${isValid ? '#22c55e' : '#ef4444'};">${escapeHtml(data.status.toUpperCase())} ${isExpired ? '(EXPIRED)' : ''}</strong></p>
            </div>
            
            <div style="background: #f8fafc; padding: 24px; border-radius: 12px; text-align: left; border: 1px solid #e2e8f0;">
              <p style="margin: 0 0 4px; font-size: 0.8rem; text-transform: uppercase; color: #64748b;">Office Name</p>
              <h3 style="margin: 0 0 16px;">${escapeHtml(data.name)}</h3>
              
              <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                <div>
                  <p style="margin: 0 0 4px; font-size: 0.8rem; text-transform: uppercase; color: #64748b;">Category</p>
                  <p style="margin: 0 0 16px; font-weight: 600;">Class ${escapeHtml(data.category)}</p>
                </div>
                <div>
                  <p style="margin: 0 0 4px; font-size: 0.8rem; text-transform: uppercase; color: #64748b;">Region</p>
                  <p style="margin: 0 0 16px; font-weight: 600;">${escapeHtml(data.region)}</p>
                </div>
              </div>
              
              <div style="margin-top: 8px; padding-top: 16px; border-top: 1px solid #e2e8f0;">
                 <p style="margin: 0 0 4px; font-size: 0.8rem; text-transform: uppercase; color: #64748b;">License Validity</p>
                 <p style="margin: 0; font-size: 0.9rem;">Expires: <strong>${formatDate(data.expired_date)}</strong></p>
              </div>
            </div>
            
            <button class="solid-button" style="margin-top: 24px; width: 100%;" onclick="window.location.hash = ''">Back to Login</button>
          </div>
        </section>
      </div>
    `;
  } catch (err) {
    app.innerHTML = `
      <div class="login-shell">
        <section class="login-panel">
          <div class="card" style="text-align: center; padding: 40px; max-width: 450px; width: 100%;">
            <div style="width: 80px; height: 80px; background: #ef4444; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 24px;">
              <svg style="width: 40px; fill: white;" viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>
            </div>
            <h2>Verification Failed</h2>
            <p class="error">${escapeHtml(err.message)}</p>
            <button class="solid-button" style="margin-top: 24px; width: 100%;" onclick="window.location.hash = ''">Back to Login</button>
          </div>
        </section>
      </div>
     `;
  }
};

const renderInvoiceView = async (id) => {
  try {
    const item = state.transactions.find(t => String(t.id) === String(id));
    if (!item) {
        app.innerHTML = '<div class="login-shell"><section class="login-panel"><div class="card"><p class="muted">Transaction not found. Please refresh and try again.</p><button class="solid-button" onclick="window.location.hash = \'\'">Back</button></div></section></div>';
        return;
    }

    const notary = state.user.notary || { name: "Official Notary Office", region: "", district: "" };

    app.innerHTML = `
      <div class="invoice-container">
        <header class="view-header no-print" style="margin-bottom: 20px; display: flex; justify-content: space-between;">
            <button class="ghost-button" onclick="window.location.hash = ''">Back to Dashboard</button>
            <button class="solid-button" onclick="window.print()">Print Invoice</button>
        </header>

        <div class="official-invoice">
          <div class="invoice-header">
            <div class="invoice-brand">
              <img src="logo.jpg" alt="Logo" />
              <div>
                <h2>NORTH EAST STATE E-NOTARY</h2>
                <p>Official Transaction Invoice</p>
              </div>
            </div>
            <div class="invoice-meta">
              <h1>INVOICE</h1>
              <p><strong># ${escapeHtml(item.invoice_number || 'INV-' + item.id)}</strong></p>
              <p>Date: ${new Date(item.created_at).toLocaleDateString()}</p>
            </div>
          </div>

          <div class="invoice-split">
            <div class="bill-from">
              <p class="eyebrow">ISSUED BY</p>
              <strong>${escapeHtml(notary.name)}</strong>
              <p>${escapeHtml(notary.region)}, ${escapeHtml(notary.district)}</p>
            </div>
            <div class="bill-to">
              <p class="eyebrow">BILL TO (CUSTOMER)</p>
              <strong>${escapeHtml(item.client_name)}</strong>
              <p>Service: ${escapeHtml(formatLabel(item.type))}</p>
            </div>
          </div>

          <table class="invoice-table">
            <thead>
              <tr>
                <th style="text-align: left; width: 70%; border-radius: 4px 0 0 4px;">Description</th>
                <th style="text-align: right; width: 30%; border-radius: 0 4px 4px 0;">Amount</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>
                  <strong>${escapeHtml(formatLabel(item.type))} / ${escapeHtml(formatLabel(item.asset_type))}</strong>
                  <p class="muted small" style="margin-top: 4px;">Official notary service fee for processing.</p>
                </td>
                <td style="text-align: right;">${money(item.amount)}</td>
              </tr>
            </tbody>
          </table>

          <div class="invoice-summary-box">
             <div class="summary-row"><span>Subtotal</span><strong>${money(item.amount)}</strong></div>
             <div class="summary-row"><span>MOF Tax (Government)</span><strong>${money(item.tax_amount)}</strong></div>
             <div class="summary-row total-row"><span>Final Total</span><strong>${money(item.total_amount)}</strong></div>
          </div>

          <div class="invoice-footer">
            <div class="invoice-notes">
              <p class="eyebrow">STATUS</p>
              <span class="status-chip ${item.status}">${item.status.toUpperCase()}</span>
              <p class="muted" style="margin-top: 10px; font-size: 0.85rem;">This is a system-generated official invoice. For any inquiries, please contact the issuing notary office.</p>
            </div>
            <div class="invoice-verification">
               <div style="width: 80px; height: 80px; background: #eee; border-radius: 4px; display: flex; align-items: center; justify-content: center;">
                 <svg style="width: 40px; opacity: 0.2;" viewBox="0 0 24 24"><path d="M9.5,13H14.5V14.5H9.5V13M9.5,16H14.5V17.5H9.5V16M20,2H4C2.9,2,2.01,2.9,2.01,4L2,22L6,18H20C21.1,18,22,17.1,22,16V4C22,2.9,21.1,2,20,2M20,16H5.17L4,17.17V4H20V16Z"/></svg>
               </div>
               <span style="font-size: 0.65rem; color: #64748b; font-weight: 700;">SYSTEM AUTHENTICATED</span>
            </div>
          </div>
        </div>
      </div>

      <style>
        .invoice-container { max-width: 800px; margin: 0 auto; padding: 40px 20px; }
        .official-invoice { background: white; padding: 40px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); border-radius: 8px; font-family: 'Inter', sans-serif; overflow: hidden; }
        
        .invoice-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 50px; border-bottom: 2px solid #f1f5f9; padding-bottom: 30px; }
        .invoice-brand { display: flex; align-items: center; gap: 15px; }
        .invoice-brand img { width: 60px; height: 60px; border-radius: 50%; }
        .invoice-brand h2 { margin: 0; font-size: 1.2rem; color: #1e5a46; letter-spacing: 0.5px; }
        .invoice-brand p { margin: 2px 0 0; font-size: 0.85rem; font-weight: 600; opacity: 0.6; }
        
        .invoice-meta { text-align: right; }
        .invoice-meta h1 { margin: 0; font-size: 2.5rem; letter-spacing: -1px; color: #cbd5e1; }
        .invoice-meta p { margin: 5px 0 0; }
        
        .invoice-split { display: grid; grid-template-columns: 1fr 1fr; gap: 40px; margin-bottom: 50px; }
        .eyebrow { font-size: 0.7rem; font-weight: 800; color: #64748b; letter-spacing: 1px; margin-bottom: 8px; }
        
        .invoice-table { width: 100%; border-collapse: separate; border-spacing: 0; margin-bottom: 40px; min-width: 0 !important; }
        .invoice-table th { text-align: left; background: #f8fafc; padding: 12px 15px; font-size: 0.85rem; color: #64748b; border-top: 1px solid #e2e8f0; border-bottom: 1px solid #e2e8f0; white-space: normal !important; }
        .invoice-table td { padding: 20px 15px; border-bottom: 1px solid #f1f5f9; vertical-align: top; white-space: normal !important; }
        
        .invoice-summary-box { margin-left: auto; width: 300px; }
        .summary-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #f1f5f9; }
        .total-row { border-bottom: none; padding-top: 15px; font-size: 1.2rem; color: #1e5a46; }
        
        .invoice-footer { margin-top: 60px; border-top: 2px solid #f1f5f9; padding-top: 40px; display: flex; justify-content: space-between; align-items: flex-end; }
        .invoice-verification { text-align: center; display: flex; flex-direction: column; align-items: center; gap: 8px; }
        
        @media print {
            body { background: white !important; -webkit-print-color-adjust: exact; }
            body * { visibility: hidden; }
            .invoice-container, .invoice-container * { visibility: visible; }
            .invoice-container { position: absolute; left: 0; top: 0; width: 100%; margin: 0; padding: 0; }
            .official-invoice { box-shadow: none; border: none; padding: 20px; }
            .no-print { display: none !important; }
        }
      </style>
    `;
  } catch (err) {
    app.innerHTML = `<p class="error">${err.message}</p>`;
  }
};

const renderGovernmentDashboard = (title, subtitle) => `
  <section class="page-intro">
    <div>
      <h2>${escapeHtml(title)}</h2>
      <p class="muted">${escapeHtml(subtitle)}</p>
    </div>
  </section>
  <section class="stats-grid">${statCards()}</section>
  <section class="dual-grid">
    <section class="card chart-card">
      <div class="section-head">
        <h3>Revenue Trends (Service Type)</h3>
        <span class="badge active">Live Data</span>
      </div>
      <p class="muted small" style="margin-bottom: 20px;">Monthly distribution based on notary filings.</p>
      <div class="bars government-bars">${chartRows()}</div>
    </section>
    
    <section class="card chart-card">
      <h3>Tax Contribution by Region</h3>
      <div class="donut-wrap">
        <div class="donut-ring" style="background: conic-gradient(var(--accent) 0 45%, var(--accent-2) 45% 75%, #f59e0b 75% 100%);"></div>
      </div>
      <div class="legend-row">
        <span><i class="legend-dot" style="background: var(--accent);"></i>Banaadir</span>
        <span><i class="legend-dot" style="background: var(--accent-2);"></i>Puntland</span>
        <span><i class="legend-dot" style="background: #f59e0b;"></i>Jubaland</span>
      </div>
    </section>
  </section>

  <section class="card">
    <div class="section-head">
      <h3>Priority Government Oversight</h3>
      <button class="ghost-button action-export-finance">Export National Report</button>
    </div>
    <div class="list-stack">
      ${state.transactions
        .slice(0, 8)
        .map(
          (item) => `
            <article class="transaction-row">
              <div>
                <strong>${escapeHtml(item.client_name)}</strong>
                <p class="muted">${escapeHtml(formatLabel(item.type))} | ${money(item.total_amount)}</p>
              </div>
              <div class="list-meta">
                <span class="muted">${String(item.created_at || "").slice(0, 10)}</span>
                ${statusChip(item.status)}
              </div>
            </article>
          `
        )
        .join("")}
    </div>
  </section>
`;

const renderJusticeDashboard = () => {
  const pendingApplications = state.applications.filter((item) => item.status === "pending").length;
  const activeNotaries = state.applications.filter((item) => item.status === "active").length;
  const rejectedApplications = state.applications.filter((item) => item.status === "rejected").length;
  const regionRows = Object.entries(
    state.applications.reduce((acc, item) => {
      if (item.status === "active") {
        acc[item.region] = (acc[item.region] || 0) + 1;
      }
      return acc;
    }, {})
  );
  const max = Math.max(1, ...regionRows.map(([, total]) => total));

  return `
    <section class="page-intro">
      <div>
        <h2>Dashboard</h2>
        <p class="muted">Overview of activity and metrics.</p>
      </div>
    </section>
    <section class="stats-grid justice-stats">
      <article class="card stat-card"><p class="muted">Pending Applications</p><strong>${pendingApplications}</strong></article>
      <article class="card stat-card"><p class="muted">Active Notaries</p><strong>${activeNotaries}</strong></article>
      <article class="card stat-card"><p class="muted">Rejected Applications</p><strong>${rejectedApplications}</strong></article>
    </section>
    <section class="dual-grid">
      <section class="card chart-card">
        <h3>Notaries by Region</h3>
        <div class="bars region-bars">
          ${regionRows
            .map(
              ([region, total]) => `
                <div class="bar-row">
                  <span>${escapeHtml(region)}</span>
                  <div class="bar-track">
                    <div class="bar-fill" style="width:${(Number(total) / max) * 100}%"></div>
                  </div>
                </div>
              `
            )
            .join("")}
        </div>
      </section>
      <section class="card">
        <h3>Recent Applications</h3>
        <div class="list-stack">
          ${state.applications
            .slice(0, 5)
            .map(
              (item) => `
                <article class="transaction-row">
                  <div>
                    <strong>${escapeHtml(item.name)}</strong>
                    <p class="muted">${escapeHtml(item.region)} | Category ${escapeHtml(item.category)}</p>
                  </div>
                  <div class="list-meta">
                    <span class="muted">${String(item.created_at || "").slice(0, 10)}</span>
                    ${statusChip(item.status)}
                  </div>
                </article>
              `
            )
            .join("")}
        </div>
      </section>
    </section>
    
    </section>
  `;
};

const renderTransactionManagement = (title, subtitle, rows, actionMode) => {
  const statuses = [...new Set(rows.map(r => r.status))].sort();
  const types = [...new Set(rows.map(r => r.type))].sort();

  const html = `
  <section class="page-intro">
    <div>
      <h2>${escapeHtml(title)}</h2>
      <p class="muted">${escapeHtml(subtitle)}</p>
    </div>
  </section>
  <section class="card filters-card" style="margin-bottom: 20px;">
    <div class="inline-actions filters-inline">
      <select id="filter-trx-status">
        <option value="">All Statuses</option>
        ${statuses.map(s => `<option value="${s}">${formatLabel(s)}</option>`).join('')}
      </select>
      <select id="filter-trx-type">
        <option value="">All Types</option>
        ${types.map(t => `<option value="${t}">${formatLabel(t)}</option>`).join('')}
      </select>
    </div>
  </section>
  <section class="card">
    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Type</th>
            <th>Client</th>
            <th>Amount</th>
            <th>Tax</th>
            <th>Total</th>
            <th>Status</th>
            <th>Created</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody id="trx-body">
          ${rows
            .map(
              (item) => `
                <tr data-status="${item.status}" data-type="${item.type}">
                  <td>#${item.id}</td>
                  <td>${escapeHtml(formatLabel(item.type))}</td>
                  <td>${escapeHtml(item.client_name)}</td>
                  <td>${money(item.amount)}</td>
                  <td>${money(item.tax_amount)}</td>
                  <td>${money(item.total_amount)}</td>
                  <td>${statusChip(item.status)}</td>
                  <td>${String(item.created_at || "").slice(0, 10)}</td>
                  <td>
                    ${
                      actionMode === "payment"
                        ? item.status === "pending"
                          ? `<button class="solid-button action-pay" data-id="${item.id}">Collect</button>`
                          : `<button class="ghost-button action-view-invoice" data-id="${item.id}" type="button">View</button>`
                        : actionMode === "executive"
                          ? item.status === "paid"
                            ? `<div class="inline-actions compact-actions"><button class="solid-button action-complete" data-id="${item.id}">Approve</button><button class="ghost-button action-reject" data-id="${item.id}">Reject</button></div>`
                            : item.status === "returned"
                              ? `<span class="badge" style="background: #fee2e2; color: #991b1b;">Returned to Teller</span>`
                              : `<button class="ghost-button action-view-invoice" data-id="${item.id}" type="button">View</button>`
                          : state.user.role === "teller" && item.status === "returned"
                            ? `<button class="solid-button action-edit-trx" data-id="${item.id}" style="background: var(--warning); color: #000;">Edit & Fix</button>`
                            : `<button class="ghost-button action-view-invoice" data-id="${item.id}" type="button">View</button>`
                    }
                  </td>
                </tr>
              `
            )
            .join("")}
        </tbody>
      </table>
    </div>
  </section>
  `;

  // Inject logic for filtering
  setTimeout(() => {
    const statusFilter = document.getElementById("filter-trx-status");
    const typeFilter = document.getElementById("filter-trx-type");
    if (!statusFilter || !typeFilter) return;

    const applyTrxFilters = () => {
      const s = statusFilter.value;
      const t = typeFilter.value;
      document.querySelectorAll("#trx-body tr").forEach(row => {
        const matchesS = !s || row.dataset.status === s;
        const matchesT = !t || row.dataset.type === t;
        row.style.display = (matchesS && matchesT) ? "" : "none";
      });
    };

    statusFilter.addEventListener("change", applyTrxFilters);
    typeFilter.addEventListener("change", applyTrxFilters);
  }, 0);

  return html;
};

const renderGroupedTaxRules = () => {
  const grouped = state.taxRules.reduce((acc, row) => {
    acc[row.service_type] = acc[row.service_type] || [];
    acc[row.service_type].push(row);
    return acc;
  }, {});

  return `
    <section class="page-intro">
      <div>
        <h2>Tax & Fee Rules</h2>
        <p class="muted">Official government fee structures for notary services.</p>
      </div>
    </section>
    <section class="tax-groups">
      ${Object.entries(grouped)
        .map(
          ([service, rows]) => `
            <section class="card tax-group-card">
              <h3>${escapeHtml(formatLabel(service))}</h3>
              <div class="table-wrap">
                <table>
                  <thead>
                    <tr>
                      <th>Asset Type</th>
                      <th>Value Range</th>
                      <th>Tax Rate</th>
                      <th>Description</th>
                    </tr>
                  </thead>
                  <tbody>
                    ${rows
                      .map(
                        (row) => `
                          <tr>
                            <td>${escapeHtml(formatLabel(row.asset_type))}</td>
                            <td>${money(row.min_amount)} - ${Number(row.max_amount) > 999999999 ? "∞" : money(row.max_amount)}</td>
                            <td>${row.tax_type === "percentage" ? `${row.tax_value}%` : money(row.tax_value)}</td>
                            <td>${escapeHtml(formatLabel(service))} ${escapeHtml(formatLabel(row.asset_type))} rule</td>
                          </tr>
                        `
                      )
                      .join("")}
                  </tbody>
                </table>
              </div>
            </section>
          `
        )
        .join("")}
    </section>
  `;
};

const renderGuaranteeForm = () => {
  const g = state.guaranteeData || {};
  const isEdit = state.view === "edit_guarantee";
  
  return `
    <div class="guarantee-layout">
      <div class="card guarantee-form-card">
        <div class="section-head" style="margin-bottom: 20px;">
          <h3>${isEdit ? 'Fix' : 'New'} Guarantee Letter</h3>
          <button class="ghost-button" onclick="window.location.hash='dashboard'">Cancel</button>
        </div>
        
        ${isEdit ? `
          <div style="background: #fff7ed; border-left: 4px solid #f97316; padding: 12px; margin-bottom: 20px; border-radius: 4px;">
             <p style="font-size: 0.75rem; font-weight: 700; color: #9a3412; margin-bottom: 4px;">REJECTION REASON:</p>
             <p style="font-size: 0.9rem; color: #7c2d12;">${escapeHtml(state.editingTrx?.rejection_note || "No reason provided.")}</p>
          </div>
        ` : ''}

        <form id="guarantee-form" class="form-grid" style="grid-template-columns: 1fr;">
          <label>Reference No (REF)<input name="ref" value="${escapeHtml(g.ref || '')}" oninput="updateGuaranteePreview(this)" required /></label>
          <label>Date<input name="date" type="date" value="${g.date || new Date().toISOString().split('T')[0]}" oninput="updateGuaranteePreview(this)" required /></label>
          <label>Bank Name (KU:)<input name="bank_name" value="${escapeHtml(g.bank_name || 'DAHABSHIIL BANK INTERNATIONAL')}" oninput="updateGuaranteePreview(this)" required /></label>
          <label>Branch<input name="branch" value="${escapeHtml(g.branch || 'HARGEISA, MAIN BRANCH')}" oninput="updateGuaranteePreview(this)" required /></label>
          <label>Magaca Damiinka (Guarantor Name)<input name="guarantor_name" value="${escapeHtml(g.guarantor_name || '')}" oninput="updateGuaranteePreview(this)" required /></label>
          <label>ID Number (National ID)<input name="national_id" value="${escapeHtml(g.national_id || '')}" oninput="updateGuaranteePreview(this)" required /></label>
          <label>Phone (Tel)<input name="phone" value="${escapeHtml(g.phone || '')}" oninput="updateGuaranteePreview(this)" required /></label>
          <label>Magaca Faa'illaha (Beneficiary Name)<input name="beneficiary_name" value="${escapeHtml(g.beneficiary_name || '')}" oninput="updateGuaranteePreview(this)" required /></label>
          <label>Nooca Maalgelinta<input name="investment_type" value="${escapeHtml(g.investment_type || 'MURAABAXO')}" oninput="updateGuaranteePreview(this)" required /></label>
          
          <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
            <label>Amount ($) - Number<input name="amount" type="number" step="0.01" value="${g.amount || ''}" oninput="updateGuaranteePreview(this)" required /></label>
            <label>Amount in Words<input name="amount_words" value="${escapeHtml(g.amount_words || '')}" oninput="updateGuaranteePreview(this)" required /></label>
          </div>

          <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
            <label>Mudada Deynta (Duration)<input name="duration" value="${escapeHtml(g.duration || '')}" oninput="updateGuaranteePreview(this)" required /></label>
            <label>Duration in Words<input name="duration_words" value="${escapeHtml(g.duration_words || '')}" oninput="updateGuaranteePreview(this)" required /></label>
          </div>

          <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
            <label>Haftada Bishii ($) - Number<input name="monthly" type="number" step="0.01" value="${g.monthly || ''}" oninput="updateGuaranteePreview(this)" required /></label>
            <label>Monthly in Words<input name="monthly_words" value="${escapeHtml(g.monthly_words || '')}" oninput="updateGuaranteePreview(this)" required /></label>
          </div>

          <label>Qodobada Sharciga<input name="clauses" value="${escapeHtml(g.clauses || '651,652,653XM')}" oninput="updateGuaranteePreview(this)" required /></label>
          
          <button class="solid-button" type="submit" style="margin-top: 10px; width: 100%;">Tallaabada Xigta: Kaydi & Gudbi</button>
        </form>
      </div>

      <div class="card guarantee-preview-card">
        <div class="preview-header">
          <p class="eyebrow" style="margin: 0;"><svg style="width: 14px; vertical-align: middle; margin-right: 4px;" viewBox="0 0 24 24"><path d="M12,9A3,3 0 0,0 9,12A3,3 0 0,0 12,15A3,3 0 0,0 15,12A3,3 0 0,0 12,9M12,17A5,5 0 0,1 7,12A5,5 0 0,1 12,7A5,5 0 0,1 17,12A5,5 0 0,1 12,17M12,4.5C7,4.5 2.73,7.61 1,12C2.73,16.39 7,19.5 12,19.5C17,19.5 21.27,16.39 23,12C21.27,7.61 17,4.5 12,4.5Z"/></svg> Live Letter Preview</p>
          <button class="solid-button sm no-print" onclick="window.print()" style="background: #f59e0b;">Hordhac Print</button>
        </div>
        <div class="letter-scroll-area">
          <div class="official-letter" id="letter-content">
            ${generateLetterHtml(g)}
          </div>
        </div>
      </div>
    </div>
  `;
};

const generateLetterHtml = (g) => {
  const notary = state.user?.notary || { name: 'ALMIS PUBLIC NOTARY', region: 'HARGEISA' };
  return `
    <div class="letter-header">
      <div class="letter-logo-box">
        <h2>NORTH EAST STATE</h2>
        <p>MINISTRY OF JUSTICE</p>
        <p style="color: var(--accent); font-weight: 800;">${escapeHtml(notary.name.toUpperCase())}</p>
        <p>${escapeHtml(notary.region.toUpperCase())}</p>
      </div>
      <div class="letter-center-logo" style="text-align: center;">
        <img src="logo.jpg" alt="Seal" style="width: 80px; height: 80px; margin-bottom: 5px;" />
        <div style="font-weight: 800; font-size: 0.75rem; color: #1e293b;">
          DAWLAD GOBOLEEDKA<br/>SHIARQ-WOQOYI<br/>
          <span style="font-size: 0.65rem;">WASAARADA CADAALADA</span>
        </div>
      </div>
      <div class="letter-logo-box" style="text-align: right;">
        <h2 dir="rtl">ولاية شمال شرق</h2>
        <p dir="rtl">وزارة العدل</p>
        <p dir="rtl" style="color: var(--accent); font-weight: 800;">مكتب كاتب العدل ألمس</p>
        <p dir="rtl">هرجيسا</p>
      </div>
    </div>

    <div class="letter-meta">
      <span>REF: ${escapeHtml(g.ref || '___/___/___')}</span>
      <span>Date: ${formatDate(g.date) || '__________'}</span>
    </div>

    <div class="letter-subject">
      <h2>UJEEDDO: CADDEYN DAMAANADEED</h2>
    </div>

    <div class="letter-content">
      <p>
        Anigoo ah <strong>${escapeHtml(g.guarantor_name || '____________________')}</strong> 
        IDNo: <span style="color: #2563eb;">${escapeHtml(g.national_id || '__________')}</span> 
        Tel: <span style="color: #2563eb;">${escapeHtml(g.phone || '__________')}</span>, 
        Waxaan halkan ku caddeynayaa (qirayaa) in aan anigu damiinal maal kaga ahay 
        <strong>${escapeHtml(g.beneficiary_name || '____________________')}</strong> 
        Lacagta maalgelinta ah ee ${escapeHtml(g.bank_name || '____________________')} 
        u ogolaaday ee faahfaahinteedu tahay:-
      </p>

      <table class="letter-table">
        <tr><td>NOOCA MAALGELINTA</td><td>${escapeHtml(g.investment_type || '_______')}</td></tr>
        <tr><td>QADARKA MAALGELINTA</td><td>($${escapeHtml(g.amount || '0')}) ${escapeHtml(g.amount_words || '_________')}</td></tr>
        <tr><td>MUDADA DEYNTA</td><td>(${escapeHtml(g.duration || '0')}) ${escapeHtml(g.duration_words || '_________')}</td></tr>
        <tr><td>HAFTADA BISHII</td><td>($${escapeHtml(g.monthly || '0')}) ${escapeHtml(g.monthly_words || '_________')}</td></tr>
      </table>

      <p>Waxaan balan qaadayaa In haddii <strong>${escapeHtml(g.beneficiary_name || '__________')}</strong> hafta kasta oo waajibta bixin waayo aan anigu bixinaayo oo masuul ka ahay.</p>
      <p>Damaanadani waxay waafaqsan tahay Qodobada: <strong>${escapeHtml(g.clauses || '__________')}</strong>.</p>
      <p>Waxaan saxeexay caddeyntan damaanadeed anigoo miyir iyo maanba qaba kuna hor saxeexay Xafiiska Nootaayada ${escapeHtml(notary.name)}.</p>
    </div>

    <div class="letter-footer">
      <div class="signature-box">
        <p class="eyebrow" style="text-align: left;">MAGACA & SAXEEXA DAMIINKA</p>
        <strong>${escapeHtml(g.guarantor_name || '____________________')}</strong>
        <div style="height: 40px;"></div>
        <div class="sig-line"></div>
        <span>SAXEEXA</span>
      </div>
    </div>

    <div style="margin-top: 30px; border-top: 1px solid #eee; padding-top: 20px; text-align: center;">
      <p class="eyebrow">CADDEYN NOTAAYO</p>
      <p style="font-size: 0.8rem; line-height: 1.4;">
        Waxaan caddeynayaa in hortayda lagu saxeexay caddeyntan damaanadeed maanta oo bishani tahay ${formatDate(g.date)}. 
        Saxeexa ku yaala yahay kii ${escapeHtml(g.guarantor_name || '__________')}. Sidaa darteed qoraalkani waa mid sugan.
      </p>
      <div style="margin-top: 15px;">
        <strong>(GAR/QAAN. QAASIM ISMACIIL DUCALE)</strong><br/>
        <span style="font-weight: 700; text-decoration: underline;">SARK. NOTAAYADA ALMIS PUBLIC NOTARY</span>
      </div>
    </div>
  `;
};

const renderGuaranteePrint = () => {
  const g = state.guaranteeData || {};
  return `
    <header class="view-header no-print" style="margin-bottom: 20px; display: flex; justify-content: space-between;">
        <button class="ghost-button" onclick="window.location.hash = ''">Back to Dashboard</button>
        <button class="solid-button" onclick="window.print()" style="background: #f59e0b;">Print Guarantee Letter</button>
    </header>
    <div class="letter-scroll-area">
      <div class="official-letter">
        ${generateLetterHtml(g)}
      </div>
    </div>
  `;
};

window.updateGuaranteePreview = (input) => {
  state.guaranteeData = state.guaranteeData || {};
  state.guaranteeData[input.name] = input.value;
  const preview = document.getElementById('letter-content');
  if (preview) {
    preview.innerHTML = generateLetterHtml(state.guaranteeData);
  }
};

window.updateTrxButtonText = (select) => {
  const btn = document.getElementById('trx-submit-btn');
  if (btn) {
    if (select.value === 'guarantee') {
      btn.innerText = 'Next: Create Guarantee Letter';
      btn.style.background = 'var(--accent-2)';
    } else {
      btn.innerText = 'Save transaction';
      btn.style.background = 'var(--accent)';
    }
  }
};

const renderCurrentView = () => {
  if (state.view === "create_guarantee" || state.view === "edit_guarantee") {
    return renderGuaranteeForm();
  }

  if (state.view === "view_guarantee") {
    return renderGuaranteePrint();
  }

  if (state.view === "create_transaction") {
    return `
      <section class="card">
        <h3>Create Transaction</h3>
        <form id="transaction-form" class="form-grid">
          <label>Client name<input name="client_name" required /></label>
          <label>Service type
            <select name="type" id="trx-type-select" onchange="updateTrxButtonText(this)">${serviceOptions
              .map((item) => `<option value="${item}">${formatLabel(item)}</option>`)
              .join("")}</select>
          </label>
          <label>Asset type
            <select name="asset_type">${assetOptions
              .map((item) => `<option value="${item}">${formatLabel(item)}</option>`)
              .join("")}</select>
          </label>
          <label>Amount<input type="number" step="0.01" name="amount" value="0" required /></label>
          <label class="full-width">Supporting details<textarea name="details" placeholder="Brief notes about the document, parties, or asset"></textarea></label>
          <label class="full-width">Supporting Document (PDF/Image)
            <input type="file" name="attachment" accept="image/*,application/pdf" />
          </label>
          <button class="solid-button" type="submit" id="trx-submit-btn">Save transaction</button>
        </form>
      </section>
      ${renderTransactionsTable()}
    `;
  }

  if (state.view === "payments") {
    return renderTransactionsTable(
      (item) => item.status === "pending",
      (item) => `<button class="solid-button action-pay" data-id="${item.id}">Mark Paid</button>`
    );
  }

  if (state.view === "approvals") {
    return renderTransactionsTable(
      (item) => item.status === "paid",
      (item) => `
        <div class="inline-actions">
          <button class="solid-button action-complete" data-id="${item.id}">Approve</button>
          <button class="ghost-button action-return" data-id="${item.id}">Return</button>
        </div>
      `
    );
  }

  if (state.view === "applications") {
    return `
      <section class="page-intro split-intro">
        <div>
          <h2>Notary Applications</h2>
          <p class="muted">Review, approve, and monitor newly submitted notary offices.</p>
        </div>
        <button class="ghost-button action-export-applications" style="border: 1px solid var(--line);">Export to Excel</button>
      </section>
      ${
        state.issuedCredentials
          ? `
            <section class="card credentials-panel" style="border: 2px solid var(--accent); margin-bottom: 20px;">
              <div class="section-head">
                <h3 style="color: var(--accent);">Issued Login Credentials</h3>
                <div class="inline-actions">
                  <button class="solid-button" onclick="copyCredentials()">Copy Details</button>
                  <button class="ghost-button" onclick="clearMessage(); renderApp();">Dismiss</button>
                </div>
              </div>
              <p class="muted">Share these credentials securely with the approved notary owner. They will be required to change this password on their first login.</p>
              
              <div style="background: #f0fdf4; border-left: 4px solid var(--accent); padding: 16px; margin: 16px 0; border-radius: 8px;">
                <h4 style="margin: 0 0 8px; color: #166534; font-size: 0.95rem;">Talaabooyinka Ansixinta (Mobile):</h4>
                <ul style="margin: 0; padding-left: 20px; font-size: 0.85rem; color: #166534; line-height: 1.5;">
                  <li>Milkiilaha wuxuu heli doonaa ogeysiis ku saabsan oggolaanshaha nidaamka.</li>
                  <li>Waa in uu ku dhuftaa <strong>'Allow'</strong> (Oggolow) si uu u dhammaystiro xaqiijinta.</li>
                  <li>Kadib, wuxuu u isticmaali karaa xogta hoose si uu u galo (Login) markii ugu horreysay.</li>
                </ul>
              </div>

              <div class="credentials-grid">
                <div><strong>Owner</strong><p>${escapeHtml(state.issuedCredentials.owner_name)}</p></div>
                <div><strong>Username</strong><p>${escapeHtml(state.issuedCredentials.username)}</p></div>
                <div><strong>Temporary Password</strong><p style="font-family: monospace; font-size: 1.4rem; color: var(--accent); background: #eee; padding: 4px 8px; border-radius: 4px; display: inline-block;">${escapeHtml(state.issuedCredentials.temporary_password)}</p></div>
              </div>
            </section>
          `
          : ""
      }
      <section class="card">
        <div class="section-head" style="margin-bottom: 15px;">
          <h3>Recent Applications</h3>
        </div>
        <div class="application-list">
          ${state.applications
            .map(
              (item) => `
                <article class="application-row">
                  <div>
                    <strong>${escapeHtml(item.name)}</strong>
                    <p class="muted">${escapeHtml(item.region)} | ${escapeHtml(item.district)} | Category ${escapeHtml(item.category)}</p>
                    <p class="muted small-line" style="margin-bottom: 4px;">${escapeHtml(item.applicant_name || "-")} | ${escapeHtml(item.applicant_email || "-")} | ${escapeHtml(item.applicant_phone || "-")}</p>
                    <p class="muted small-line" style="color: var(--primary);"><strong>${escapeHtml(item.registration_type ? item.registration_type.toUpperCase() : "NEW")}</strong> | Issued: ${escapeHtml(formatDate(item.issued_date, "Pending"))} | Expires: ${escapeHtml(formatDate(item.expired_date, "Pending"))}</p>
                  </div>
                  <div class="inline-actions">
                    ${statusChip(item.status)}
                    ${
                      item.status === "pending"
                        ? `
                          <button class="solid-button action-approve-application" data-id="${item.id}">Approve</button>
                          <button class="ghost-button action-reject-application" data-id="${item.id}">Reject</button>
                        `
                        : ""
                    }
                  </div>
                </article>
              `
            )
            .join("")}
        </div>
      </section>
    `;
  }

  if (state.view === "notaries") {
    return `
      <section class="page-intro split-intro">
        <div>
          <h2>Notaries</h2>
          <p class="muted">Directory and oversight view for registered notary offices.</p>
        </div>
        <button class="ghost-button action-export-notaries" style="border: 1px solid var(--line);">Export to Excel</button>
      </section>
      ${
        state.issuedCredentials
          ? `
            <section class="card credentials-panel" style="border: 2px solid var(--accent); margin-bottom: 20px;">
              <div class="section-head">
                <h3 style="color: var(--accent);">Issued Login Credentials</h3>
                <div class="inline-actions">
                  <button class="solid-button" onclick="copyCredentials()">Copy Details</button>
                  <button class="ghost-button" onclick="clearMessage(); renderApp();">Dismiss</button>
                </div>
              </div>
              <p class="muted">Share these newly generated credentials securely with the notary owner. They will be required to change this password on their next login.</p>
              <div class="credentials-grid">
                <div><strong>Owner</strong><p>${escapeHtml(state.issuedCredentials.owner_name)}</p></div>
                <div><strong>Username</strong><p>${escapeHtml(state.issuedCredentials.username)}</p></div>
                <div><strong>Temporary Password</strong><p style="font-family: monospace; font-size: 1.4rem; color: var(--accent); background: #eee; padding: 4px 8px; border-radius: 4px; display: inline-block;">${escapeHtml(state.issuedCredentials.temporary_password)}</p></div>
              </div>
            </section>
          `
          : ""
      }
      <section class="card">
        <div class="application-list">
          ${state.notaries
            .map(
              (item) => `
                <details class="application-row" style="cursor: default;">
                  <summary style="outline: none;">
                    <div>
                      <strong style="font-size: 1.1rem;">${escapeHtml(item.name)}</strong>
                      <p class="muted" style="margin-top: 4px;">${escapeHtml(item.region)} | ${escapeHtml(item.district)}</p>
                    </div>
                    <div style="pointer-events: none;">
                      ${statusChip(item.status)}
                    </div>
                  </summary>
                  <div class="accordion-content">
                    <div>
                      <p class="muted small-line" style="margin-bottom: 4px;"><strong>Owner:</strong> ${escapeHtml(item.owner_name || "-")} | ${escapeHtml(item.owner_email || "-")} | ${escapeHtml(item.owner_phone || "-")}</p>
                      <p class="muted small-line" style="color: var(--primary);"><strong>${escapeHtml(item.registration_type ? item.registration_type.toUpperCase() : "NEW")}</strong> | Issued: ${escapeHtml(formatDate(item.issued_date, "Pending"))} | Expires: ${escapeHtml(formatDate(item.expired_date, "Pending"))}</p>
                    </div>
                    <div class="inline-actions compact-actions">
                      <button class="ghost-button action-edit-notary" data-id="${item.id}" data-name="${escapeHtml(item.name)}" data-region="${escapeHtml(item.region)}" data-district="${escapeHtml(item.district)}" data-category="${escapeHtml(item.category)}" data-status="${escapeHtml(item.status)}">Edit</button>
                      <button class="ghost-button action-reset-password" data-id="${item.id}" data-name="${escapeHtml(item.name)}" style="color: var(--danger);">Reset Password</button>
                      <button class="solid-button action-renew-notary" data-id="${item.id}" data-name="${escapeHtml(item.name)}">Renew License</button>
                    </div>
                  </div>
                </details>
              `
            )
            .join("")}
        </div>
      </section>
    `;
  }

  if (state.view === "finance") {
    return `
      <section class="page-intro split-intro">
        <div>
          <h2>Ministry of Finance Report</h2>
          <p class="muted">Read-only view of completed transactions, government tax, and notary fees.</p>
        </div>
        <div class="inline-actions">
          <button class="solid-button action-export-finance">Export to Excel</button>
        </div>
      </section>
      <section class="card filters-card">
        <h3>Filters</h3>
        <div class="form-grid">
          <label>From<input type="date" /></label>
          <label>To<input type="date" /></label>
          <label>Service Type
            <select><option>All services</option></select>
          </label>
          <label>Asset Type
            <select><option>All assets</option></select>
          </label>
          <label>Notary
            <select><option>All notaries</option></select>
          </label>
          <label>Region
            <select><option>All regions</option></select>
          </label>
          <label>District<input placeholder="e.g. Hodan" /></label>
          <div class="filter-actions">
            <button class="solid-button" type="button">Apply</button>
            <button class="ghost-button" type="button">Reset</button>
          </div>
        </div>
      </section>
      <section class="stats-grid finance-stats">
        <article class="card stat-card"><p class="muted">Transactions</p><strong>${state.financeRows.length}</strong></article>
        <article class="card stat-card"><p class="muted">Commodity Value</p><strong>${money(state.financeRows.reduce((sum, row) => sum + Number(row.commodity_value || 0), 0))}</strong></article>
        <article class="card stat-card"><p class="muted">MOF Tax</p><strong>${money(state.financeRows.reduce((sum, row) => sum + Number(row.mof_tax || 0), 0))}</strong></article>
        <article class="card stat-card"><p class="muted">Notary Fees</p><strong>${money(state.financeRows.reduce((sum, row) => sum + Number(row.notary_fee || 0), 0))}</strong></article>
        <article class="card stat-card"><p class="muted">Total Payments</p><strong>${money(state.financeRows.reduce((sum, row) => sum + Number(row.total_payment || 0), 0))}</strong></article>
      </section>
      <section class="card">
        <div class="table-wrap">
          <table>
            <thead>
              <tr>
                <th>ID</th>
                <th>Service</th>
                <th>Asset</th>
                <th>Notary</th>
                <th>Region</th>
                <th>District</th>
                <th>Customer</th>
                <th>Paid</th>
                <th>Reference</th>
                <th>Phone</th>
                <th>Commodity</th>
                <th>Tax</th>
                <th>Notary Fee</th>
                <th>Total</th>
              </tr>
            </thead>
            <tbody>
              ${state.financeRows
                .map(
                  (row) => `
                    <tr>
                      <td>${row.transaction_id}</td>
                      <td>${escapeHtml(formatLabel(row.service_name))}</td>
                      <td>${escapeHtml(formatLabel(row.asset_type))}</td>
                      <td>${escapeHtml(row.notary)}</td>
                      <td>${escapeHtml(row.region)}</td>
                      <td>${escapeHtml(row.district)}</td>
                      <td>${escapeHtml(row.customer)}</td>
                      <td>${escapeHtml(row.payment_date)}</td>
                      <td>${escapeHtml(row.reference_number)}</td>
                      <td>${escapeHtml(row.phone)}</td>
                      <td>${money(row.commodity_value)}</td>
                      <td>${money(row.mof_tax)}</td>
                      <td>${money(row.notary_fee)}</td>
                      <td>${money(row.total_payment)}</td>
                    </tr>
                  `
                )
                .join("")}
            </tbody>
          </table>
        </div>
      </section>
      <p class="muted note-line">Read-only access. Ministry of Finance cannot modify any system data.</p>
    `;
  }

  if (state.view === "tax_rules") {
    return renderGroupedTaxRules();
  }

  if (state.view === "audit_logs") {
    const filteredLogs = state.auditLogs.filter(row => {
      const f = state.auditLogFilters;
      const matchesUser = !f.user || row.user_name.toLowerCase().includes(f.user.toLowerCase()) || String(row.user_id).includes(f.user);
      const matchesAction = !f.action || row.action.toLowerCase().includes(f.action.toLowerCase());
      const matchesDetails = !f.details || row.description.toLowerCase().includes(f.details.toLowerCase());
      const matchesIp = !f.ip || (row.ip_address || "127.0.0.1").includes(f.ip);
      const matchesDate = !f.date || new Date(row.created_at).toLocaleDateString('en-GB').includes(f.date);
      return matchesUser && matchesAction && matchesDetails && matchesIp && matchesDate;
    });

    return `
      <section class="page-intro split-intro">
        <div>
          <h2>Audit Logs</h2>
          <p class="muted">System-wide immutable activity tracker for compliance and oversight.</p>
        </div>
        <button class="ghost-button action-export-logs" style="border: 1px solid var(--line);">Export to Excel</button>
      </section>

      <section class="card filters-card" style="margin-bottom: 20px;">
        <div class="form-grid compact-filters" style="grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));">
          <label>Filter User<input id="filter-audit-user" value="${escapeHtml(state.auditLogFilters.user)}" placeholder="Name or ID..." /></label>
          <label>Filter Action<input id="filter-audit-action" value="${escapeHtml(state.auditLogFilters.action)}" placeholder="LOGIN, RENEW..." /></label>
          <label>Filter Details<input id="filter-audit-details" value="${escapeHtml(state.auditLogFilters.details)}" placeholder="Search description..." /></label>
          <label>Filter IP<input id="filter-audit-ip" value="${escapeHtml(state.auditLogFilters.ip)}" placeholder="127.0.0.1..." /></label>
          <label>Filter Date<input id="filter-audit-date" value="${escapeHtml(state.auditLogFilters.date)}" placeholder="DD/MM/YYYY..." /></label>
        </div>
      </section>

      <section class="card">
        <div class="table-wrap">
          <table class="audit-table">
            <thead>
              <tr>
                <th>User</th>
                <th>Action</th>
                <th>Details</th>
                <th>IP Address</th>
                <th>Timestamp</th>
              </tr>
            </thead>
            <tbody>
              ${filteredLogs.length > 0 
                ? filteredLogs.map(row => `
                  <tr>
                    <td>
                      <div class="user-cell">
                        <strong>${escapeHtml(row.user_name)}</strong>
                        <span class="muted small">${row.user_id}</span>
                      </div>
                    </td>
                    <td><span class="badge ${row.action.toLowerCase()}">${escapeHtml(row.action)}</span></td>
                    <td style="max-width: 300px; font-size: 0.9rem;">${escapeHtml(row.description)}</td>
                    <td class="muted">${escapeHtml(row.ip_address || "127.0.0.1")}</td>
                    <td class="muted">${escapeHtml(new Date(row.created_at).toLocaleString('en-GB', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' }))}</td>
                  </tr>
                `).join("")
                : '<tr><td colspan="5" style="text-align: center; padding: 40px;" class="muted">Ma jirto diiwaan waafaqsan shaandhayntaada.</td></tr>'
              }
            </tbody>
          </table>
        </div>
      </section>
    `;
  }

  if (state.view === "transactions") {
    if (state.user.role === "payment") {
      return renderTransactionManagement(
        "Transactions",
        "Manage notary transactions and payments.",
        state.transactions,
        "payment"
      );
    }

    if (state.user.role === "executive") {
      return renderTransactionManagement(
        "Transactions",
        "Review legal files and finalize decisions.",
        state.transactions,
        "executive"
      );
    }

    return `
      <section class="page-intro">
        <div>
          <h2>Transactions</h2>
          <p class="muted">View all files available to your role.</p>
        </div>
      </section>
      ${renderTransactionsTable()}
    `;
  }

  if (state.view === "staff") {
    return `
      <section class="page-intro">
        <div>
          <h2>Staff</h2>
          <p class="muted">Owner view of office staff and assigned roles.</p>
        </div>
      </section>

      ${
        state.issuedStaffCredentials
          ? `
            <section class="card credentials-panel" style="border: 2px solid var(--accent); margin-bottom: 20px;">
              <div class="section-head">
                <h3 style="color: var(--accent);">Staff Login Credentials</h3>
                <div class="inline-actions">
                  <button class="solid-button" onclick="copyCredentials('staff')">Copy Details</button>
                  <button class="ghost-button" onclick="clearMessage(); renderApp();">Dismiss</button>
                </div>
              </div>
              <p class="muted">Share these credentials securely with the new staff member. They will be required to change this password on their first login.</p>
              <div class="credentials-grid">
                <div><strong>Name</strong><p>${escapeHtml(state.issuedStaffCredentials.owner_name)}</p></div>
                <div><strong>Username/Email</strong><p>${escapeHtml(state.issuedStaffCredentials.username)}</p></div>
                <div><strong>Temporary Password</strong><p style="font-family: monospace; font-size: 1.4rem; color: var(--accent); background: #eee; padding: 4px 8px; border-radius: 4px; display: inline-block;">${escapeHtml(state.issuedStaffCredentials.temporary_password)}</p></div>
              </div>
            </section>
          `
          : ""
      }

      <div class="dual-grid">
        <section class="card">
          <h3>${state.editingStaffId ? "Edit Staff Member" : "Add New Staff Member"}</h3>
          <p class="muted">${state.editingStaffId ? "Update the details of your staff member." : "Register a new staff member for your office."}</p>
          <form id="staff-form" class="form-grid">
            <label>Full Name<input name="name" required placeholder="e.g. Hassan Ali" /></label>
            <label>Email Address<input name="email" type="email" required placeholder="e.g. hassan@notary.so" /></label>
            <label>Staff Role
              <select name="role" required>
                <option value="teller">Teller (Registration)</option>
                <option value="payment">Payment (Finance)</option>
                <option value="executive">Executive (Decision)</option>
              </select>
            </label>
            <div class="form-actions">
              <button class="solid-button" type="submit">${state.editingStaffId ? "Update Account" : "Create Account"}</button>
              ${state.editingStaffId ? '<button class="ghost-button" type="button" onclick="state.editingStaffId = null; renderApp();">Cancel</button>' : ""}
            </div>
          </form>
        </section>

        <section class="card">
          <h3>Existing Staff</h3>
          <div class="table-wrap">
            <table>
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Email</th>
                  <th>Role</th>
                  <th>Created</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody>
                ${state.staffMembers
                  .map(
                    (row) => `
                      <tr>
                        <td>${escapeHtml(row.name)}</td>
                        <td>${escapeHtml(row.email)}</td>
                        <td>${escapeHtml(formatLabel(row.role))}</td>
                        <td>${String(row.created_at || "").slice(0, 10)}</td>
                        <td>
                          ${
                            row.role !== "owner"
                              ? `
                            <div class="inline-actions compact-actions">
                              <button class="ghost-button action-edit-staff" data-id="${row.id}" data-name="${escapeHtml(row.name)}" data-email="${escapeHtml(row.email)}" data-role="${row.role}">Edit</button>
                              <button class="ghost-button action-reset-staff-password" data-id="${row.id}" data-name="${escapeHtml(row.name)}" style="color: var(--warning);">Reset Password</button>
                              <button class="ghost-button action-delete-staff" data-id="${row.id}" style="color: var(--danger);">Delete</button>
                            </div>
                          `
                              : '<span class="muted small">System</span>'
                          }
                        </td>
                      </tr>
                    `
                  )
                  .join("")}
              </tbody>
            </table>
          </div>
        </section>
      </div>
    `;
  }

  if (state.view === "license") {
    const notary = state.user.notary;
    if (!notary) return '<p class="muted">Ma jirto xog nootaayo oo kugu xiran.</p>';

    const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${encodeURIComponent(
      window.location.origin + window.location.pathname + "#verify-notary/" + notary.id
    )}`;

    return `
      <section class="page-intro split-intro">
        <div>
          <h2>Office License</h2>
          <p class="muted">Download or print your official practice license.</p>
        </div>
        <button class="solid-button" onclick="window.print()">Print Certificate</button>
      </section>

      <div class="certificate-container">
        <div class="notary-certificate">
          <div class="cert-border"></div>
          <div class="cert-content">
            <header class="cert-header">
              <img src="logo.jpg" alt="Logo" class="cert-logo" />
              <div class="cert-state-box">
                <h3>NORTH EAST STATE OF SOMALIA</h3>
                <p>Ministry of Justice, Religious Affairs & Rehabilitation</p>
              </div>
            </header>

            <div class="cert-title-box">
              <h1>NOTARY PRACTICE LICENSE</h1>
              <p class="license-number">License No: NESOS-L-${String(notary.id).padStart(5, '0')}</p>
            </div>

            <p class="cert-statement">This is to certify that </p>
            <h2 class="cert-notary-name">${escapeHtml(notary.name)}</h2>
            <p class="cert-statement">has been duly registered and authorized to practice as a </p>
            <h3 class="cert-category">CLASS ${escapeHtml(notary.category)} NOTARY OFFICE</h3>
            
            <div class="cert-location">
              <p>Region: <strong>${escapeHtml(notary.region)}</strong> | District: <strong>${escapeHtml(notary.district)}</strong></p>
            </div>

            <div class="cert-footer">
              <div class="cert-dates">
                <div class="date-item">
                  <span>ISSUE DATE</span>
                  <strong>${formatDate(notary.issued_date)}</strong>
                </div>
                <div class="date-item">
                  <span>EXPIRY DATE</span>
                  <strong>${formatDate(notary.expired_date)}</strong>
                </div>
              </div>

              <div class="cert-qr">
                <img src="${qrUrl}" alt="Verification QR" />
                <span>SCAN TO VERIFY</span>
              </div>

              <div class="cert-signature">
                <div class="sig-line"></div>
                <span>DIRECTOR GENERAL</span>
                <p>Ministry of Justice</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <style>
        .certificate-container {
          display: flex;
          justify-content: center;
          padding: 40px 0;
          background: #f1f5f9;
          border-radius: 12px;
        }
        .notary-certificate {
          width: 800px;
          height: 600px;
          background: white;
          position: relative;
          padding: 50px;
          box-shadow: 0 15px 35px rgba(0,0,0,0.1);
          color: #1e293b;
          font-family: 'Times New Roman', serif;
          border: 1px solid #e2e8f0;
          display: flex;
          flex-direction: column;
        }
        .cert-border {
          position: absolute;
          top: 15px; left: 15px; right: 15px; bottom: 15px;
          border: 4px double #1e5a46;
          pointer-events: none;
        }
        .cert-header {
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 20px;
          margin-bottom: 20px;
        }
        .cert-logo { width: 70px; height: 70px; border-radius: 50%; }
        .cert-state-box { text-align: center; }
        .cert-state-box h3 { margin: 0; font-size: 1.4rem; color: #1e5a46; letter-spacing: 1px; }
        .cert-state-box p { margin: 2px 0 0; font-size: 0.9rem; font-weight: 600; opacity: 0.8; }
        
        .cert-title-box { text-align: center; margin-bottom: 15px; }
        .cert-title-box h1 { 
          margin: 0; font-size: 2.2rem; 
          color: #1e293b; 
          border-bottom: 2px solid #edeff2;
          display: inline-block;
          padding-bottom: 10px;
          margin-bottom: 10px;
        }
        .license-number { font-weight: 700; color: #64748b; font-size: 1rem; }
        
        .cert-statement { text-align: center; font-style: italic; margin: 10px 0; font-size: 1.2rem; }
        .cert-notary-name { text-align: center; font-size: 2.4rem; color: #1e5a46; margin: 10px 0; font-family: 'Inter', sans-serif; }
        .cert-category { text-align: center; font-size: 1.3rem; margin: 5px 0; font-weight: 800; color: #334155; }
        .cert-location { text-align: center; margin-top: 15px; font-size: 1.1rem; }

        .cert-footer {
          margin-top: auto;
          display: flex;
          justify-content: space-between;
          align-items: flex-end;
          padding-bottom: 15px;
        }
        .cert-dates { display: flex; gap: 30px; }
        .date-item { display: flex; flex-direction: column; }
        .date-item span { font-size: 0.75rem; color: #64748b; font-weight: 700; }
        .date-item strong { font-size: 1.1rem; }

        .cert-qr { text-align: center; }
        .cert-qr img { width: 90px; height: 90px; border: 1px solid #e2e8f0; padding: 4px; }
        .cert-qr span { display: block; font-size: 0.65rem; font-weight: 700; margin-top: 4px; color: #64748b; }

        .cert-signature { text-align: center; width: 180px; }
        .sig-line { border-top: 1.5px solid #1e293b; margin-bottom: 8px; }
        .cert-signature span { font-weight: 700; font-size: 0.9rem; }
        .cert-signature p { margin: 2px 0 0; font-size: 0.8rem; opacity: 0.7; }

        @media print {
          body * { visibility: hidden; }
          .certificate-container, .certificate-container * { visibility: visible; }
          .certificate-container { 
            position: absolute; left: 0; top: 0; width: 100%; height: 100%; 
            padding: 0; background: white; border-radius: 0; justify-content: center; align-items: center;
          }
          .notary-certificate { 
            box-shadow: none; border: 1px solid #ccc; 
            transform: scale(1.1); /* Slightly larger for A4 landscape */
          }
        }
      </style>
    `;
  }

  if (state.view === "settings") {
    const isSuper = state.user.role === "super_admin";
    const config = state.settings?.systemConfig || {};

    return `
      <section class="page-intro">
        <div>
          <h2>Settings & Configuration</h2>
          <p class="muted">Manage your office profile and system-wide preferences.</p>
        </div>
      </section>

      <div class="tax-groups">
        <section class="dual-grid">
          <article class="card">
            <h3>Office Profile</h3>
            <div style="margin-top: 15px; display: grid; gap: 10px;">
              <p class="small-line"><strong>Name:</strong> ${escapeHtml(state.settings?.name || state.settings?.office_name || "Government Office")}</p>
              <p class="small-line"><strong>Region:</strong> ${escapeHtml(state.settings?.region || "-")}</p>
              <p class="small-line"><strong>Primary Email:</strong> ${escapeHtml(state.settings?.owner_email || state.user.email)}</p>
              <p class="small-line"><strong>Current Role:</strong> <span class="badge">${formatLabel(state.user.role)}</span></p>
            </div>
          </article>

          <article class="card">
            <h3>Security</h3>
            <p class="muted small-line">Update your login credentials and security preferences.</p>
            <button class="ghost-button" style="margin-top: 15px; width: 100%;">Change Password</button>
            <button class="ghost-button" style="margin-top: 10px; width: 100%;">Setup 2FA (Coming Soon)</button>
          </article>
        </section>

        ${isSuper ? `
          <section class="card">
            <div class="section-head">
              <h3>Global System Settings</h3>
              <span class="pill" style="background: var(--accent); color: white;">ADMIN ONLY</span>
            </div>
            <p class="muted" style="margin-bottom: 25px;">Configure the core system behavior, including SMS and Email notification gateways.</p>
            
            <form id="system-config-form" class="form-grid">
              <div class="full-width">
                 <label style="flex-direction: row; align-items: center; gap: 10px; cursor: pointer;">
                   <input type="checkbox" name="notifications_enabled" value="true" ${config.notifications_enabled === 'true' ? 'checked' : ''} style="width: 20px; min-height: 0;" />
                   Enable Global Notifications (SMS/Email)
                 </label>
              </div>

              <label>SMS Gateway URL
                <input name="sms_gateway_url" value="${escapeHtml(config.sms_gateway_url || '')}" placeholder="https://api.sms.com/send" />
              </label>
              <label>SMS API Key
                <input name="sms_api_key" type="password" value="${escapeHtml(config.sms_api_key || '')}" placeholder="Your secret key" />
              </label>
              
              <label>SMTP Host
                <input name="email_smtp_host" value="${escapeHtml(config.email_smtp_host || '')}" placeholder="smtp.gmail.com" />
              </label>
              <label>SMTP User
                <input name="email_smtp_user" value="${escapeHtml(config.email_smtp_user || '')}" placeholder="notifications@nesos.gov" />
              </label>
              <label>SMTP Password
                <input name="email_smtp_pass" type="password" value="${escapeHtml(config.email_smtp_pass || '')}" placeholder="••••••••" />
              </label>

              <div class="full-width" style="margin-top: 10px; padding-top: 20px; border-top: 1px solid var(--line);">
                <button class="solid-button" type="submit">Save System Configuration</button>
              </div>
            </form>
          </section>
        ` : ""}
      </div>
    `;
  }

  if (state.view === "id-cards") {
    return renderIdCardsView();
  }

  if (state.view === "dashboard" && state.user.role === "ministry_finance") {
    return renderGovernmentDashboard(
      "Dashboard",
      "National financial overview across notaries and completed transactions."
    );
  }

  if (
    state.view === "dashboard" &&
    state.user.role === "ministry_justice"
  ) {
    return renderJusticeDashboard();
  }

  if (
    state.view === "dashboard" &&
    state.user.role === "super_admin"
  ) {
    return renderGovernmentDashboard(
      "Dashboard",
      "Government oversight of notary applications, activity, and compliance."
    );
  }

  return renderDashboardHome();
};

// Global Click Delegation (Handles Navigation and all Action Buttons)
document.addEventListener("click", async (e) => {
  // Find the button or the data-view element regardless of where exactly they clicked
  let target = e.target;
  while (target && target !== document) {
    if (target.tagName === 'BUTTON' || target.dataset.view || target.id === 'logout-button' || target.classList.contains('nav-item')) {
       break;
    }
    target = target.parentNode;
  }
  
  if (!target || target === document) return;
  
  console.log(`[Click Event] Tag: ${target.tagName}, Class: ${target.className}, View: ${target.dataset.view}`);

  // 1. Sidebar/Menu Navigation
  if (target.dataset.view) {
    window.location.hash = target.dataset.view;
    return;
  }

  // 2. Auth: Sign Out
  if (target.id === "logout-button") {
    state.token = "";
    state.user = null;
    state.view = "dashboard";
    localStorage.removeItem("nesos_token");
    localStorage.removeItem("nesos_user");
    clearMessage();
    renderLogin();
    return;
  }

  // 3. Notary Actions (Justice Ministry)
  if (target.classList.contains("action-reset-password")) {
    const { id, name } = target.dataset;
    if (!confirm(`Ma ku qanacsan tahay in aad password-ka u reset-gareeyo: ${name}?`)) return;
    try {
      const response = await api(`/api/notaries/${id}/reset-password`, { method: "PATCH" });
      state.issuedCredentials = response.credentials;
      setMessage("Password successfully reset. Share the new credentials shown at the top.");
      renderApp();
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch (err) { alert(err.message); }
    return;
  }

  if (target.classList.contains("action-edit-notary")) {
    const { id, name, region, district, category, status } = target.dataset;
    document.getElementById("edit-notary-id").value = id;
    document.getElementById("edit-notary-name").value = name;
    document.getElementById("edit-notary-region").value = region;
    document.getElementById("edit-notary-district").value = district;
    document.getElementById("edit-notary-category").value = category;
    document.getElementById("edit-notary-status").value = status;
    document.getElementById("notary-edit-modal").showModal();
    return;
  }

  if (target.classList.contains("action-renew-notary")) {
    const { id, name } = target.dataset;
    document.getElementById("renew-notary-id").value = id;
    document.getElementById("renew-notary-title").textContent = `Renewing ${name}`;
    document.getElementById("notary-renew-modal").showModal();
    return;
  }

  // 4. Staff Actions (Notary Owner)
  if (target.classList.contains("action-edit-staff")) {
    state.editingStaffId = target.dataset.id;
    renderApp();
    const form = document.getElementById("staff-form");
    if (form) {
      form.name.value = target.dataset.name;
      form.email.value = target.dataset.email;
      form.role.value = target.dataset.role;
      form.scrollIntoView({ behavior: "smooth" });
    }
    return;
  }

  if (target.classList.contains("action-reset-staff-password")) {
    const { id, name } = target.dataset;
    if (!confirm(`Ma hubtaa in aad password-ka shaqaalahan badasho: ${name}?`)) return;
    try {
      const res = await api(`/api/staff/${id}/reset-password`, { method: "PATCH" });
      state.issuedStaffCredentials = res.credentials;
      setMessage("Staff password reset successful. New credentials generation shown above.");
      renderApp();
    } catch (err) { alert(err.message); }
    return;
  }

  if (target.classList.contains("action-delete-staff")) {
    const { id } = target.dataset;
    if (!confirm("Ma hubtaa in aad tirtirto shaqaalahan? (Yes / No)")) return;
    try {
      await api(`/api/staff/${id}`, { method: "DELETE" });
      setMessage("Shaqaalaha waa la tirtiray.");
      await fetchProtectedData();
      renderApp();
    } catch (err) { alert(err.message); }
    return;
  }

  if (target.classList.contains("action-view-invoice")) {
    const trxId = target.dataset.id;
    const item = state.transactions.find(t => String(t.id) === String(trxId));
    if (item) {
      const details = JSON.parse(item.details || '{}');
      if (details.guarantee) {
        state.guaranteeData = details.guarantee;
        state.view = "view_guarantee";
        renderApp();
        return;
      }
    }
    window.location.hash = `invoice/${trxId}`;
    return;
  }

  // 5. Transaction Actions (Teller/Payment/Executive)
  if (target.classList.contains("action-pay")) {
    const reference = prompt("Geli nambarka tixraaca lacag bixinta (Payment Reference):", `REF-${target.dataset.id}`);
    if (!reference) return;
    try {
      await api(`/api/transactions/${target.dataset.id}/pay`, {
        method: "PATCH",
        body: JSON.stringify({ reference_number: reference, phone: "" })
      });
      setMessage("Payment recorded.");
      await fetchProtectedData();
      renderApp();
    } catch (err) { alert(err.message); }
  }

  if (target.classList.contains("action-complete")) {
    if (!confirm("Ma ku qanacsan tahay in aad ansixiso codsigan?")) return;
    try {
      await api(`/api/transactions/${target.dataset.id}/decision`, {
        method: "PATCH", body: JSON.stringify({ status: "completed" })
      });
      setMessage("Transaction completed.");
      await fetchProtectedData();
      renderApp();
    } catch (err) { alert(err.message); }
    return;
  }

  if (target.classList.contains("action-reject")) {
    const reason = prompt("Fadlan qor sababta aad u diiday (Rejection Reason):");
    if (reason === null) return; // Cancelled
    try {
      await api(`/api/transactions/${target.dataset.id}/decision`, {
        method: "PATCH", body: JSON.stringify({ status: "rejected", rejection_note: reason })
      });
      setMessage("Codsiga waa la soo celiyey si loo saxo.");
      await fetchProtectedData();
      renderApp();
    } catch (err) { alert(err.message); }
    return;
  }

  if (target.classList.contains("action-edit-trx")) {
    const trxId = target.dataset.id;
    const item = state.transactions.find(t => String(t.id) === String(trxId));
    if (!item) return;

    const details = JSON.parse(item.details || '{}');
    if (item.type === 'guarantee' || details.guarantee) {
      state.editingTrx = item;
      state.guaranteeData = details.guarantee || { 
        beneficiary_name: item.client_name, 
        amount: item.amount,
        date: new Date().toISOString().split('T')[0]
      };
      state.view = "edit_guarantee";
      renderApp();
      return;
    }

    document.getElementById("edit-trx-id").value = item.id;
    document.getElementById("edit-trx-name").value = item.client_name;
    document.getElementById("edit-trx-type").value = item.type;
    document.getElementById("edit-trx-asset").value = item.asset_type;
    document.getElementById("edit-trx-amount").value = item.amount;
    document.getElementById("edit-trx-details").value = JSON.parse(item.details || '{}').notes || "";
    document.getElementById("edit-trx-rejection-note").textContent = item.rejection_note || "No reason provided.";
    
    document.getElementById("trx-edit-modal").showModal();
    return;
  }

  // 6. Application Actions (Ministry of Justice)
  if (target.classList.contains("action-approve-application")) {
    const { id } = target.dataset;
    if (!confirm("Ma ku qanacsan tahay in aad ansixiso codsigan nootaayada cusub?")) return;
    try {
      const response = await api(`/api/applications/${id}/review`, {
        method: "PATCH",
        body: JSON.stringify({ status: "active" })
      });
      state.issuedCredentials = response.credentials;
      setMessage("Codsiga waa la ansixiyey. Fadlan nuqul ka qaad xogta gelitaanka (credentials) ee hoos ka muuqata.");
      await fetchProtectedData();
      renderApp();
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch (err) { alert(err.message); }
    return;
  }

  if (target.classList.contains("action-reject-application")) {
    const { id } = target.dataset;
    if (!confirm("Ma hubtaa in aad diido (Reject) codsigan nootaayada?")) return;
    try {
      await api(`/api/applications/${id}/review`, {
        method: "PATCH",
        body: JSON.stringify({ status: "rejected" })
      });
      setMessage("Codsiga nootaayada waa la diiday.");
      await fetchProtectedData();
      renderApp();
    } catch (err) { alert(err.message); }
    return;
  }
});

// GLOBAL SUBMIT DELEGATION
document.addEventListener("submit", async (e) => {
  const target = e.target;
  console.log(`[Global Submit] Form ID: ${target.id}`);

  // 1. Transaction Form
  if (target.id === "transaction-form") {
    e.preventDefault();
    const fd = new FormData(target);
    const type = fd.get("type");
    
    if (type === "guarantee") {
      // Step 1: Store temp transaction data
      state.tempTrx = {
        client_name: fd.get("client_name"),
        type: fd.get("type"),
        asset_type: fd.get("asset_type"),
        amount: fd.get("amount"),
        details: { notes: fd.get("details") },
        attachment: fd.get("attachment")
      };
      state.guaranteeData = {
        beneficiary_name: state.tempTrx.client_name,
        amount: state.tempTrx.amount,
        date: new Date().toISOString().split('T')[0]
      };
      state.view = "create_guarantee";
      renderApp();
      return;
    }

    try {
      await api("/api/transactions", { method: "POST", body: new FormData(target) });
      setMessage("Transaction created successfully.");
      await fetchProtectedData();
      renderApp();
    } catch (err) { alert(err.message); }
  }

  // 1.2 Guarantee Form Submit
  if (target.id === "guarantee-form") {
    e.preventDefault();
    const fd = new FormData(target);
    const guaranteeDetails = Object.fromEntries(fd.entries());
    
    const finalFd = new FormData();
    const baseData = state.view === "edit_guarantee" ? state.editingTrx : state.tempTrx;
    
    finalFd.append("client_name", baseData.client_name);
    finalFd.append("type", baseData.type);
    finalFd.append("asset_type", baseData.asset_type);
    finalFd.append("amount", baseData.amount);
    
    // Merge general notes with guarantee fields
    const finalDetails = {
      ...(baseData.details || {}),
      guarantee: guaranteeDetails
    };
    finalFd.append("details", JSON.stringify(finalDetails));
    
    if (baseData.attachment) {
      finalFd.append("attachment", baseData.attachment);
    }

    try {
      if (state.view === "edit_guarantee") {
        await api(`/api/transactions/${state.editingTrx.id}`, {
          method: "PUT",
          body: JSON.stringify({
             ...baseData,
             details: finalDetails
          })
        });
        setMessage("Guarantee Letter updated and resubmitted.");
      } else {
        await api("/api/transactions", { method: "POST", body: finalFd });
        setMessage("Guarantee Letter created successfully.");
      }
      state.view = "dashboard";
      state.tempTrx = null;
      state.guaranteeData = null;
      await fetchProtectedData();
      renderApp();
    } catch (err) { alert(err.message); }
  }

  // 1.1 Transaction Edit Form
  if (target.id === "transaction-edit-form") {
    e.preventDefault();
    const fd = new FormData(target);
    const id = fd.get("id");
    const payload = {
      client_name: fd.get("client_name"),
      type: fd.get("type"),
      asset_type: fd.get("asset_type"),
      amount: fd.get("amount"),
      details: { notes: fd.get("details") }
    };
    try {
      await api(`/api/transactions/${id}`, { 
        method: "PUT", 
        body: JSON.stringify(payload) 
      });
      document.getElementById("trx-edit-modal").close();
      setMessage("Codsiga waa la saxay, waana lagu celiyey Executive-ka.");
      await fetchProtectedData();
      renderApp();
    } catch (err) { alert(err.message); }
  }

  // 2. Notary Edit Form
  if (target.id === "notary-edit-form") {
    e.preventDefault();
    const fd = new FormData(target);
    try {
      await api(`/api/notaries/${fd.get("id")}`, {
        method: "PUT",
        body: JSON.stringify(Object.fromEntries(fd))
      });
      document.getElementById("notary-edit-modal").close();
      setMessage("Notary details updated.");
      await fetchProtectedData();
      renderApp();
    } catch (err) { alert(err.message); }
  }

  // 3. Notary Renew Form
  if (target.id === "notary-renew-form") {
    e.preventDefault();
    const fd = new FormData(target);
    try {
      await api(`/api/notaries/${fd.get("id")}/renew`, {
        method: "PATCH",
        body: JSON.stringify({ issued_date: fd.get("issued_date"), expired_date: fd.get("expired_date") })
      });
      document.getElementById("notary-renew-modal").close();
      setMessage("License renewed successfully.");
      await fetchProtectedData();
      renderApp();
    } catch (err) { alert(err.message); }
  }

  // 4. Staff Form
  if (target.id === "staff-form") {
    e.preventDefault();
    const fd = new FormData(target);
    const payload = Object.fromEntries(fd);
    try {
      if (state.editingStaffId) {
        await api(`/api/staff/${state.editingStaffId}`, { method: "PUT", body: JSON.stringify(payload) });
        state.editingStaffId = null;
      } else {
        const res = await api("/api/staff", { method: "POST", body: JSON.stringify(payload) });
        state.issuedStaffCredentials = res.credentials;
      }
      await fetchProtectedData();
      renderApp();
    } catch (err) { alert(err.message); }
  }

  // 5. System Configuration
  if (target.id === "system-config-form") {
    e.preventDefault();
    const fd = new FormData(target);
    const payload = Object.fromEntries(fd);
    try {
      await api("/api/settings/system", { method: "POST", body: JSON.stringify(payload) });
      setMessage("System configuration updated.");
      await fetchProtectedData();
      renderApp();
    } catch (err) { alert(err.message); }
  }
});

const renderPublicNotaryDirectory = async () => {
  try {
    const notaries = await api("/api/public/notaries");
    const regions = [...new Set(notaries.map(n => n.region))].filter(Boolean).sort();
    const categories = [...new Set(notaries.map(n => n.category))].filter(Boolean).sort();

    app.innerHTML = `
      <div class="login-shell" style="grid-template-columns: 1fr; background: white;">
        <div class="login-panel" style="padding: 40px; max-width: 1200px; margin: 0 auto; width: 100%; grid-template-columns: 1fr; align-content: start; background: white;">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; border-bottom: 1px solid var(--line); padding-bottom: 20px;">
            <div>
              <h1 style="font-size: 2.5rem; margin-bottom: 5px;">Public Notary Directory</h1>
              <p class="muted" style="font-size: 1.1rem;">Official registry of active notary offices in the North East State.</p>
            </div>
            <button class="solid-button" onclick="window.location.hash='login'">Back to System Login</button>
          </div>

          <div style="display: flex; gap: 15px; margin-bottom: 30px; flex-wrap: wrap; align-items: flex-end;">
            <div style="flex: 2; min-width: 300px;">
              <label class="eyebrow" style="display: block; margin-bottom: 8px;">Search by Name</label>
              <input type="text" id="dir-search" placeholder="🔍 Enter office name..." 
                     style="width: 100%; height: 48px; padding: 0 16px; border: 1px solid var(--line); border-radius: 10px;" />
            </div>
            <div style="flex: 1; min-width: 180px;">
              <label class="eyebrow" style="display: block; margin-bottom: 8px;">Region</label>
              <select id="dir-region" style="width: 100%; height: 48px;">
                <option value="">All Regions</option>
                ${regions.map(r => `<option value="${r}">${r}</option>`).join('')}
              </select>
            </div>
            <div style="flex: 1; min-width: 150px;">
              <label class="eyebrow" style="display: block; margin-bottom: 8px;">Category</label>
              <select id="dir-cat" style="width: 100%; height: 48px;">
                <option value="">All Classes</option>
                ${categories.map(c => `<option value="${c}">Class ${c}</option>`).join('')}
              </select>
            </div>
          </div>
          
          <div class="card">
            <div class="table-wrap">
              <table>
                <thead>
                  <tr>
                    <th>Notary Office Name</th>
                    <th>Region</th>
                    <th>District</th>
                    <th>Category</th>
                    <th>Registry Status</th>
                  </tr>
                </thead>
                <tbody id="directory-body">
                  ${notaries.map(n => `
                    <tr data-region="${escapeHtml(n.region)}" data-cat="${escapeHtml(n.category)}">
                      <td style="font-weight: 700; color: var(--accent); font-size: 1.1rem;">${escapeHtml(n.name)}</td>
                      <td>${escapeHtml(n.region)}</td>
                      <td>${escapeHtml(n.district || '-')}</td>
                      <td>Class ${escapeHtml(n.category)}</td>
                      <td><span class="status-chip active">OFFICIALLY REGISTERED</span></td>
                    </tr>
                  `).join('')}
                </tbody>
              </table>
              <div id="no-results" class="hidden" style="padding: 40px; text-align: center; color: var(--muted); font-size: 1.1rem;">
                No notary offices found matching your filters.
              </div>
            </div>
          </div>
          
          <footer style="margin-top: 40px; text-align: center; border-top: 1px solid var(--line); padding-top: 20px;">
            <p class="muted">This directory is updated in real-time by the Ministry of Justice.</p>
          </footer>
        </div>
      </div>
    `;

    const searchInput = document.getElementById("dir-search");
    const regionSelect = document.getElementById("dir-region");
    const catSelect = document.getElementById("dir-cat");
    const noResults = document.getElementById("no-results");

    const applyFilters = () => {
      const term = searchInput.value.toLowerCase().trim();
      const region = regionSelect.value;
      const category = catSelect.value;
      const rows = document.querySelectorAll("#directory-body tr");
      let visibleCount = 0;

      rows.forEach(row => {
        const text = row.cells[0].textContent.toLowerCase();
        const rowRegion = row.dataset.region;
        const rowCat = row.dataset.cat;

        const matchesSearch = text.includes(term);
        const matchesRegion = !region || rowRegion === region;
        const matchesCat = !category || rowCat === category;

        if (matchesSearch && matchesRegion && matchesCat) {
          row.style.display = "";
          visibleCount++;
        } else {
          row.style.display = "none";
        }
      });
      noResults.classList.toggle("hidden", visibleCount > 0);
    };

    [searchInput, regionSelect, catSelect].forEach(el => el.addEventListener("input", applyFilters));

  } catch (err) {
    app.innerHTML = `<div class="login-shell"><section class="login-panel"><p class="error">${err.message}</p><button onclick="window.location.hash='login'">Back</button></section></div>`;
  }
};

const renderApp = () => {
  const allowedMenus = menus[state.user.role] || ["dashboard"];
  let expirationBanner = "";
  state.isReadOnly = false;

  if (state.user.notary?.expired_date) {
    const expiredDate = new Date(state.user.notary.expired_date);
    const diffTime = new Date() - expiredDate;
    const daysOverdue = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

    if (daysOverdue > 0 && daysOverdue <= 3) {
      state.isReadOnly = true;
      expirationBanner = `<div class="card" style="background: var(--danger); color: white; margin-bottom: 20px;">
        <strong>Read-Only Mode</strong>: Your notary license expired on ${state.user.notary.expired_date}. You are in a 3-day grace period where you can only view data. Please contact the Ministry of Justice to renew immediately.
      </div>`;
    } else if (daysOverdue > -14 && daysOverdue <= 0) {
      expirationBanner = `<div class="card" style="background: var(--warning); color: #856404; margin-bottom: 20px;">
        <strong>License Expiring Soon</strong>: Your notary license will expire in ${Math.abs(daysOverdue)} days (on ${state.user.notary.expired_date}). Please renew to avoid service interruption.
      </div>`;
    }
  }

  app.innerHTML = `
    <div class="app-shell ${state.isReadOnly ? 'read-only-mode' : ''}">
      <aside class="sidebar">
        <div class="brand">
          <img src="logo.jpg" alt="State logo" />
          <div>
            <p class="brand-title">North East State of Somalia</p>
            <span class="pill">${escapeHtml(badgeLabels[state.user.role])}</span>
          </div>
        </div>
        <nav class="nav-list">
          ${allowedMenus
            .map(
              (menu) => `
                <button class="nav-item ${state.view === menu ? "active" : ""}" data-view="${menu}">
                  ${escapeHtml(menuLabels[menu])}
                </button>
              `
            )
            .join("")}
        </nav>
      </aside>
      <main class="main-shell">
        <header class="topbar">
          <div>
            <h1>${escapeHtml(menuLabels[state.view] || "Dashboard")}</h1>
            <div class="muted">${escapeHtml(state.user.notary?.name || "Government Office")}</div>
          </div>
          <div class="profile-strip">
            <div class="profile-copy">
              <strong>${escapeHtml(state.user.name)}</strong>
              <span class="muted">${escapeHtml(state.user.notary?.name || "Government Office")}</span>
            </div>
            <button id="logout-button" class="ghost-button">Sign out</button>
          </div>
        </header>
        <section class="role-switcher">
          <div>
            <p class="eyebrow">North East State E-Notary Platform</p>
            <h2>${escapeHtml(formatLabel(state.user.role))}</h2>
          </div>
          ${state.message ? `<div class="success-text">${escapeHtml(state.message)}</div>` : ""}
        </section>
        <section class="content-grid">
          ${expirationBanner}
          ${renderCurrentView()}
        </section>
      </main>
      
      <dialog id="notary-edit-modal" class="card" style="padding: 30px; border: none; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); max-width: 500px; width: 100%;">
        <div class="section-head" style="margin-bottom: 20px;">
          <h3>Edit Notary Details</h3>
          <button class="ghost-button" type="button" onclick="document.getElementById('notary-edit-modal').close();" style="min-height: auto; padding: 4px 10px;">Close</button>
        </div>
        <form id="notary-edit-form" class="form-grid">
          <input type="hidden" name="id" id="edit-notary-id" />
          <label class="full-width">Office Name<input name="name" id="edit-notary-name" required /></label>
          <label>Region<input name="region" id="edit-notary-region" required /></label>
          <label>District<input name="district" id="edit-notary-district" required /></label>
          <label>Category
            <select name="category" id="edit-notary-category" required>
              <option value="A">A</option>
              <option value="B">B</option>
              <option value="C">C</option>
              <option value="D">D</option>
            </select>
          </label>
          <label>Status
            <select name="status" id="edit-notary-status" required>
              <option value="active">Active</option>
              <option value="pending">Pending</option>
              <option value="rejected">Rejected</option>
            </select>
          </label>
          <button class="solid-button full-width" type="submit" style="margin-top: 10px;">Save Changes</button>
        </form>
      </dialog>

      <dialog id="notary-renew-modal" class="card" style="padding: 30px; border: 2px solid var(--accent); border-radius: 12px; box-shadow: 0 10px 30px rgba(15, 90, 70, 0.15); max-width: 450px; width: 100%;">
        <div class="section-head" style="margin-bottom: 20px;">
          <div>
            <h3 style="color: var(--accent);">Renew License</h3>
            <span class="muted" id="renew-notary-title">Update active license validity</span>
          </div>
          <button class="ghost-button" type="button" onclick="document.getElementById('notary-renew-modal').close();" style="min-height: auto; padding: 4px 10px;">Close</button>
        </div>
        <form id="notary-renew-form" class="form-grid">
          <input type="hidden" name="id" id="renew-notary-id" />
          <label class="full-width">New Issue Date<input name="issued_date" id="renew-notary-issued" type="date" required /></label>
          <label class="full-width">New Expiry Date<input name="expired_date" id="renew-notary-expired" type="date" required /></label>
          <button class="solid-button full-width" type="submit" style="margin-top: 15px; background: var(--success);">Confirm Renewal</button>
        </form>
      </dialog>

      <dialog id="trx-edit-modal" class="card" style="padding: 30px; border: none; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); max-width: 600px; width: 100%;">
        <div class="section-head" style="margin-bottom: 20px;">
          <div>
            <h3>Saxi Trans-section-ka</h3>
            <span class="muted">Wax ka bedel macluumaadka si loo ogolaado.</span>
          </div>
          <button class="ghost-button" type="button" onclick="document.getElementById('trx-edit-modal').close();" style="min-height: auto; padding: 4px 10px;">Close</button>
        </div>
        
        <div id="rejection-alert" style="background: #fff7ed; border-left: 4px solid #f97316; padding: 12px; margin-bottom: 20px; border-radius: 4px;">
           <p style="font-size: 0.75rem; font-weight: 700; color: #9a3412; margin-bottom: 4px; text-transform: uppercase;">Sababta loo soo celiyey:</p>
           <p id="edit-trx-rejection-note" style="font-size: 0.9rem; color: #7c2d12;"></p>
        </div>

        <form id="transaction-edit-form" class="form-grid">
          <input type="hidden" name="id" id="edit-trx-id" />
          <label class="full-width">Customer Name<input name="client_name" id="edit-trx-name" required /></label>
          <label>Service Type
            <select name="type" id="edit-trx-type">
              ${serviceOptions.map(s => `<option value="${s}">${formatLabel(s)}</option>`).join('')}
            </select>
          </label>
          <label>Asset Type
            <select name="asset_type" id="edit-trx-asset">
              ${assetOptions.map(a => `<option value="${a}">${formatLabel(a)}</option>`).join('')}
            </select>
          </label>
          <label>Amount (USD)<input type="number" step="0.01" name="amount" id="edit-trx-amount" required /></label>
          <label class="full-width">Corrected Details<textarea name="details" id="edit-trx-details"></textarea></label>
          
          <div class="full-width" style="margin-top: 15px; display: grid; gap: 10px;">
            <button class="solid-button" type="submit">Save & Resubmit to Executive</button>
            <button class="ghost-button" type="button" onclick="document.getElementById('trx-edit-modal').close();">Cancel</button>
          </div>
        </form>
      </dialog>
    </div>
  `;

// No local bindings needed anymore as we use Global Delegation below
};

const init = async () => {
  const hash = window.location.hash;
  if (hash.startsWith("#verify/")) {
    const code = hash.split("/")[1];
    await renderPublicVerification(code);
    return;
  }

  if (hash.startsWith("#verify-notary/")) {
    const id = hash.split("/")[1];
    await renderPublicNotaryVerification(id);
    return;
  }

  if (hash === "#notaries-directory") {
    await renderPublicNotaryDirectory();
    return;
  }

  if (hash.startsWith("#invoice/")) {
    const id = hash.split("/")[1];
    await renderInvoiceView(id);
    return;
  }

  const savedToken = localStorage.getItem("nesos_token");
  const savedUser = localStorage.getItem("nesos_user");

  if (savedToken && savedUser) {
    try {
      state.token = savedToken;
      state.user = JSON.parse(savedUser);
      state.mustChangePassword = Boolean(state.user.password_must_change);
      
      const currentView = hash.substring(1);
      const allowedViews = menus[state.user.role] || ["dashboard"];
      if (currentView && allowedViews.includes(currentView)) {
        state.view = currentView;
      } else {
        state.view = "dashboard";
      }

      if (state.mustChangePassword) {
        renderForcedPasswordChange();
      } else {
        if (state.user.notary?.issued_date) {
            const issuedDate = new Date(state.user.notary.issued_date);
            const now = new Date();
            const diffHours = (now - issuedDate) / (1000 * 60 * 60);
            if (diffHours < 24 && !localStorage.getItem(`welcomed_${state.user.notary.issued_date}`)) {
              localStorage.setItem(`welcomed_${state.user.notary.issued_date}`, 'true');
              alert(`Welcome back!\nYour notary license has been successfully renewed.\n\nNew Issue Date: ${formatDate(state.user.notary.issued_date)}\nNew Expiry Date: ${formatDate(state.user.notary.expired_date)}`);
            }
        }
        await fetchProtectedData();
        renderApp();
      }
    } catch (e) {
      localStorage.removeItem("nesos_token");
      localStorage.removeItem("nesos_user");
      renderLogin();
    }
  } else {
    renderLogin();
  }
};

init();

window.addEventListener("hashchange", () => {
  init();
});

// Global Error Catcher for Debugging
window.onerror = function(msg, url, lineNo, columnNo, error) {
  const string = msg.toLowerCase();
  const substring = "script error";
  if (string.indexOf(substring) > -1){
    alert('Script Error: See Browser Console for Detail');
  } else {
    const message = [
      'Message: ' + msg,
      'URL: ' + url,
      'Line: ' + lineNo,
      'Column: ' + columnNo,
      'Error object: ' + JSON.stringify(error)
    ].join('\n');
    alert("SYSTEM ERROR:\n" + message);
  }
  return false;
};
