// ─── Admin Module ────────────────────────────────────────────────────
// Reuses the exact same cards/tables/badges as the client-facing pages —
// no separate admin template, per the unified-layout requirement.

const Admin = {
  render(page, app) {
    const sub = page.replace('admin-', '');
    if (sub.startsWith('registrar-tlds-')) { this.registrarTlds(app, sub.replace('registrar-tlds-', '')); return; }
    if (this[sub]) this[sub](app);
    else app.$content.innerHTML = '<div class="empty"><i class="fas fa-tools"></i><p>Admin page not found</p></div>';
  },

  async orders(app) {
    const res = await app.api('admin/orders');
    const items = res.success && res.data ? res.data.items || [] : [];

    app.$content.innerHTML = `
      <div class="page-header"><h1>All Orders</h1></div>
      <div class="card card-flat">
        <div class="table-wrap">
          <table>
            <thead><tr><th>#</th><th>Customer</th><th>Package</th><th>Domain</th><th>Status</th><th>Date</th><th></th></tr></thead>
            <tbody>
              ${items.length ? items.map(o => `
                <tr>
                  <td>#${o.id}</td>
                  <td>${app.escape(o.owner_name || '')}<br><small style="color:var(--gray-500)">${app.escape(o.owner_email || '')}</small></td>
                  <td>${app.escape(o.package || '')}</td>
                  <td>${app.escape(o.domain) || '-'}</td>
                  <td><span class="${app.statusClass(o.status)}">${app.statusLabel(o.status)}</span></td>
                  <td>${o.date ? o.date.slice(0,10) : '-'}</td>
                  <td><button class="btn btn-sm btn-secondary" onclick="Admin.cycleOrderStatus('${o.id_enc}', ${o.status})">Cycle Status</button></td>
                </tr>
              `).join('') : '<tr><td colspan="7" class="text-center">No orders found.</td></tr>'}
            </tbody>
          </table>
        </div>
      </div>
    `;
  },

  async cycleOrderStatus(idEnc, currentStatus) {
    const app = App;
    const r = await app.api(`admin/order-status&oid=${encodeURIComponent(idEnc)}&status=${currentStatus}`);
    if (r.success) { app.showMessage('Order status updated.', 'success'); Admin.orders(app); }
  },

  async invoices(app) {
    const [res, revRes] = await Promise.all([
      app.api('admin/invoices'),
      app.api('admin/revenue&ord=mnz')
    ]);
    const items = res.success && res.data ? res.data.items || [] : [];
    const rev = revRes.success && revRes.data ? revRes.data : { total: 0, fee: 0, net: 0 };

    app.$content.innerHTML = `
      <div class="page-header">
        <h1>All Invoices</h1>
        <div class="btn-group">
          <button class="btn btn-sm btn-secondary" onclick="Admin.bulkReminders()">Send Payment Reminders</button>
          <button class="btn btn-sm btn-secondary" onclick="Admin.bulkInvoices()">Generate Renewal Invoices</button>
        </div>
      </div>
      <div class="stats mb-4">
        <div class="stat"><div class="stat-label">Revenue (This Month)</div><div class="stat-value">$${Number(rev.total).toFixed(2)}</div></div>
        <div class="stat"><div class="stat-label">Est. PayPal Fee (18%)</div><div class="stat-value">$${Number(rev.fee).toFixed(2)}</div></div>
        <div class="stat"><div class="stat-label">Net</div><div class="stat-value">$${Number(rev.net).toFixed(2)}</div></div>
      </div>
      <div class="card card-flat">
        <div class="table-wrap">
          <table>
            <thead><tr><th>Invoice #</th><th>Customer</th><th>Amount</th><th>Due</th><th>Status</th><th></th></tr></thead>
            <tbody>
              ${items.length ? items.map(i => `
                <tr>
                  <td>#${i.id}</td>
                  <td>${app.escape(i.owner_email || '')}</td>
                  <td>$${i.price}</td>
                  <td>${i.exdate ? i.exdate.slice(0,10) : '-'}</td>
                  <td><span class="${app.invClass(i.status)}">${app.invLabel(i.status)}</span></td>
                  <td>
                    <select class="form-control" style="display:inline-block;width:auto" onchange="Admin.setInvoiceStatus('${i.iid_enc}','${i.oid_enc}',this.value)">
                      <option value="">Set status...</option>
                      <option value="1">Paid</option>
                      <option value="2">Hold</option>
                      <option value="3">Refunded</option>
                      <option value="4">Cancelled</option>
                      <option value="0">Unpaid</option>
                    </select>
                  </td>
                </tr>
              `).join('') : '<tr><td colspan="6" class="text-center">No invoices found.</td></tr>'}
            </tbody>
          </table>
        </div>
      </div>
    `;
  },

  async setInvoiceStatus(iidEnc, oidEnc, status) {
    if (status === '') return;
    const app = App;
    const r = await app.api(`admin/invoice-action&iid=${encodeURIComponent(iidEnc)}&oid=${encodeURIComponent(oidEnc)}&status=${status}`);
    if (r.success) { app.showMessage('Invoice updated.', 'success'); Admin.invoices(app); }
  },

  async bulkReminders() {
    const app = App;
    const r = await app.api('admin/bulk-reminders');
    app.showMessage(r.message || 'Done.', r.success ? 'success' : 'danger');
  },

  async bulkInvoices() {
    const app = App;
    const r = await app.api('admin/bulk-invoices');
    app.showMessage(r.message || 'Done.', r.success ? 'success' : 'danger');
  },

  async users(app) {
    const res = await app.api('admin/users');
    const items = res.success && res.data ? res.data.items || [] : [];

    app.$content.innerHTML = `
      <div class="page-header"><h1>User Management</h1></div>
      <div class="card card-flat">
        <div class="table-wrap">
          <table>
            <thead><tr><th>#</th><th>Name</th><th>Email</th><th>Phone</th><th>Verified</th><th>Joined</th></tr></thead>
            <tbody>
              ${items.length ? items.map(u => `
                <tr>
                  <td>#${u.id}</td>
                  <td>${app.escape(u.name || '')}</td>
                  <td>${app.escape(u.email || '')}</td>
                  <td>${app.escape(u.phone || '-')}</td>
                  <td>${u.status == 1 ? '<span class="badge badge-active">Verified</span>' : '<span class="badge badge-pending">Unverified</span>'}</td>
                  <td>${u.date ? u.date.slice(0,10) : '-'}</td>
                </tr>
              `).join('') : '<tr><td colspan="6" class="text-center">No users found.</td></tr>'}
            </tbody>
          </table>
        </div>
      </div>
    `;
  },

  async products(app) {
    const res = await app.api('admin/products');
    const items = res.success && res.data ? res.data.items || [] : [];

    app.$content.innerHTML = `
      <div class="page-header"><h1>Product Catalog</h1></div>
      <div class="card card-flat">
        <div class="table-wrap">
          <table>
            <thead><tr><th>#</th><th>Name</th><th>Type</th><th>Billing Cycle</th><th>Yearly</th><th>Status</th><th></th></tr></thead>
            <tbody>
              ${items.length ? items.map(p => `
                <tr>
                  <td>#${p.id}</td>
                  <td>${app.escape(p.pkname || '')}</td>
                  <td>${app.escape(p.htype || '')}</td>
                  <td>${p.fmonth} Month${p.fmonth > 1 ? 's' : ''} — $${Number(p.fprice).toFixed(2)}</td>
                  <td>$${Number(p.yprice).toFixed(2)}</td>
                  <td>${p.status === '0' ? '<span class="badge badge-active">Active</span>' : '<span class="badge badge-cancelled">Disabled</span>'}</td>
                  <td><button class="btn btn-sm btn-secondary" onclick="Admin.toggleProduct(${p.id})">${p.status === '0' ? 'Disable' : 'Enable'}</button></td>
                </tr>
              `).join('') : '<tr><td colspan="7" class="text-center">No products found.</td></tr>'}
            </tbody>
          </table>
        </div>
      </div>
    `;
  },

  async toggleProduct(pid) {
    const app = App;
    const r = await app.api(`admin/product-toggle&pid=${pid}`);
    if (r.success) Admin.products(app);
  },

  async servers(app) {
    const res = await app.api('admin/servers');
    const items = res.success && res.data ? res.data.items || [] : [];

    app.$content.innerHTML = `
      <div class="page-header"><h1>Server Management</h1></div>
      <div class="card card-flat">
        <div class="table-wrap">
          <table>
            <thead><tr><th>#</th><th>Server URL</th><th>WHM User</th><th>Nameservers</th><th>WHM Token</th><th>Status</th></tr></thead>
            <tbody>
              ${items.length ? items.map(s => `
                <tr>
                  <td>#${s.id}</td>
                  <td>${app.escape(s.server_url || '')}</td>
                  <td>${app.escape(s.whm_user || '-')}</td>
                  <td>${app.escape(s.nameserver || '-')}</td>
                  <td>${s.has_token == 1 ? '<span class="badge badge-active">Configured</span>' : '<span class="badge badge-pending">Not set</span>'}</td>
                  <td>${s.status == 1 ? '<span class="badge badge-active">Online</span>' : '<span class="badge badge-suspended">Offline</span>'}</td>
                </tr>
              `).join('') : '<tr><td colspan="6" class="text-center">No servers configured.</td></tr>'}
            </tbody>
          </table>
        </div>
      </div>
      <p style="color:var(--gray-500);margin-top:.75rem">WHM tokens are configured in <code>config/servers.php</code> / the <code>h_server</code> table directly — they are never sent to the browser.</p>
    `;
  },

  async tlds(app) {
    const [tldRes, settingsRes] = await Promise.all([
      app.api('admin/tlds'),
      app.api('admin/settings')
    ]);
    const items = tldRes.success && tldRes.data ? tldRes.data.items || [] : [];
    const threshold = tldRes.success && tldRes.data ? tldRes.data.free_domain_threshold : 2;
    Admin._tlds = items;

    app.$content.innerHTML = `
      <div class="page-header">
        <h1>Free Domain TLD List</h1>
        <a href="#admin-registrars" data-nav="admin-registrars" class="btn btn-sm btn-secondary">Manage Registrars</a>
      </div>
      <p style="color:var(--gray-500);margin-bottom:1.5rem">
        This is just an allow-list of which extensions appear in the "free domain" picker at checkout.
        Actual availability and pricing are always shopped live across every active registrar (see
        <a href="#admin-registrars" data-nav="admin-registrars">Registrars</a>) — a TLD only actually
        comes out free if its shopped price is at or under the threshold below.
      </p>

      <div class="card">
        <div class="card-header"><h3>Free Domain Threshold</h3></div>
        <div class="card-body">
          <form id="threshold-form" style="display:flex;gap:.5rem;align-items:flex-end;max-width:320px">
            <div class="form-group" style="margin-bottom:0;flex:1">
              <label>Price Threshold ($/yr)</label>
              <input type="number" step="0.01" min="0" name="free_domain_threshold" class="form-control" value="${Number(threshold).toFixed(2)}" required>
            </div>
            <button type="submit" class="btn btn-primary">Save</button>
          </form>
        </div>
      </div>

      <div class="card mt-4">
        <div class="card-header"><h3 id="tld-form-title">Add TLD</h3></div>
        <div class="card-body">
          <form id="tld-form">
            <input type="hidden" name="id" value="">
            <div class="form-group">
              <label id="tld-input-label">Extension(s) — no dot; separate several with a comma or space to add them all at once</label>
              <input type="text" name="tld" id="tld-input" class="form-control" placeholder="com, net, xyz, shop, top, buzz, site, io" required>
            </div>
            <label style="display:flex;align-items:center;gap:.5rem;margin-bottom:1rem"><input type="checkbox" name="status" checked> Active</label>
            <div class="btn-group">
              <button type="submit" class="btn btn-primary">Save</button>
              <button type="button" class="btn btn-secondary" onclick="Admin.resetTldForm()">Cancel</button>
            </div>
          </form>
        </div>
      </div>
      <div class="card card-flat mt-4">
        <p style="color:var(--gray-500);padding:0 1rem;margin-top:1rem">This order is what customers see in the free-domain picker at checkout.</p>
        <div class="table-wrap">
          <table>
            <thead><tr><th style="width:1%"></th><th>Extension</th><th>Status</th><th></th></tr></thead>
            <tbody>
              ${items.length ? items.map((t, i) => `
                <tr>
                  <td style="white-space:nowrap">
                    <button class="btn btn-sm btn-secondary" onclick="Admin.moveTld(${t.id},'up')" ${i === 0 ? 'disabled' : ''} title="Move up"><i class="fas fa-arrow-up"></i></button>
                    <button class="btn btn-sm btn-secondary" onclick="Admin.moveTld(${t.id},'down')" ${i === items.length - 1 ? 'disabled' : ''} title="Move down"><i class="fas fa-arrow-down"></i></button>
                  </td>
                  <td>.${app.escape(t.tld)}</td>
                  <td>${t.status == 1 ? '<span class="badge badge-active">Active</span>' : '<span class="badge badge-cancelled">Disabled</span>'}</td>
                  <td>
                    <button class="btn btn-sm btn-secondary" onclick="Admin.editTld(${t.id})">Edit</button>
                    <button class="btn btn-sm btn-danger" onclick="Admin.deleteTld(${t.id})">Delete</button>
                  </td>
                </tr>
              `).join('') : '<tr><td colspan="4" class="text-center">No TLDs configured yet.</td></tr>'}
            </tbody>
          </table>
        </div>
      </div>
    `;

    document.getElementById('threshold-form').onsubmit = async (e) => {
      e.preventDefault();
      const fd = new FormData(e.target);
      const r = await app.api('admin/settings-save', 'POST', { free_domain_threshold: fd.get('free_domain_threshold') });
      if (r.success) { app.showMessage('Threshold saved.', 'success'); Admin.tlds(app); }
      else app.showMessage(r.message || 'Could not save.', 'danger');
    };

    document.getElementById('tld-form').onsubmit = async (e) => {
      e.preventDefault();
      const fd = new FormData(e.target);
      const data = { id: fd.get('id') || '', tld: fd.get('tld'), status: fd.get('status') ? '1' : '' };
      const r = await app.api('admin/tld-save', 'POST', data);
      if (r.success) { app.showMessage(r.message || 'TLD saved.', 'success'); Admin.resetTldForm(); Admin.tlds(app); }
      else app.showMessage(r.message || 'Could not save TLD.', 'danger');
    };
  },

  editTld(id) {
    const t = (Admin._tlds || []).find(x => x.id == id);
    if (!t) return;
    const form = document.getElementById('tld-form');
    form.id.value = t.id;
    form.tld.value = t.tld;
    form.status.checked = t.status == 1;
    document.getElementById('tld-form-title').textContent = `Edit .${t.tld}`;
    document.getElementById('tld-input-label').textContent = 'Extension — no dot';
    document.getElementById('tld-input').placeholder = 'com';
    form.scrollIntoView({ behavior: 'smooth' });
  },

  resetTldForm() {
    const form = document.getElementById('tld-form');
    if (!form) return;
    form.reset();
    form.id.value = '';
    form.status.checked = true;
    document.getElementById('tld-form-title').textContent = 'Add TLD';
    document.getElementById('tld-input-label').textContent = 'Extension(s) — no dot; separate several with a comma or space to add them all at once';
    document.getElementById('tld-input').placeholder = 'com, net, xyz, shop, top, buzz, site, io';
  },

  async deleteTld(id) {
    const app = App;
    if (!confirm('Delete this TLD? Existing orders that already used it are unaffected.')) return;
    const r = await app.api(`admin/tld-delete&id=${id}`);
    if (r.success) Admin.tlds(app);
  },

  async moveTld(id, dir) {
    const app = App;
    const r = await app.api(`admin/tld-move&id=${id}&dir=${dir}`);
    if (r.success) Admin.tlds(app);
    else app.showMessage(r.message || 'Could not reorder.', 'danger');
  },

  async registrars(app) {
    const res = await app.api('admin/registrars');
    const items = res.success && res.data ? res.data.items || [] : [];
    Admin._registrars = items;

    app.$content.innerHTML = `
      <div class="page-header">
        <h1>Domain Registrars</h1>
        <a href="#admin-tlds" data-nav="admin-tlds" class="btn btn-sm btn-secondary">Free Domain TLD List</a>
      </div>
      <p style="color:var(--gray-500);margin-bottom:1.5rem">
        Every ACTIVE registrar below is checked on every domain search — the cheapest available one is
        chosen automatically and used for registration. Customers never see or pick a registrar.
      </p>

      <div class="card">
        <div class="card-header"><h3 id="registrar-form-title">Add Registrar</h3></div>
        <div class="card-body">
          <form id="registrar-form">
            <input type="hidden" name="id" value="">
            <div class="form-row">
              <div class="form-group"><label>Name</label><input type="text" name="name" class="form-control" placeholder="NameSilo" required></div>
              <div class="form-group">
                <label>Driver</label>
                <select name="driver" class="form-control">
                  <option value="namesilo">NameSilo</option>
                  <option value="dynadot">Dynadot</option>
                  <option value="generic">Generic REST (config below)</option>
                </select>
              </div>
            </div>
            <div class="form-row">
              <div class="form-group"><label>API Key</label><input type="text" name="api_key" class="form-control" placeholder="Enter to set/replace"></div>
              <div class="form-group"><label>API Secret (if needed)</label><input type="text" name="api_secret" class="form-control" placeholder="Enter to set/replace"></div>
            </div>
            <div class="form-row">
              <div class="form-group"><label>API Endpoint (optional, informational)</label><input type="text" name="api_endpoint" class="form-control" placeholder="https://api.example.com"></div>
              <div class="form-group"><label>Priority (lower checked first on ties)</label><input type="number" name="priority" class="form-control" value="100"></div>
            </div>
            <div class="form-group">
              <label>Generic Driver Config (JSON — only used when Driver = Generic REST)</label>
              <textarea name="config" class="form-control" rows="4" placeholder='{"check_url":"https://api.example.com/check?domain={domain}&key={api_key}","available_path":"available","price_path":"price","register_url":"...","ns_url":"...","success_path":"success"}'></textarea>
            </div>
            <label style="display:flex;align-items:center;gap:.5rem;margin-bottom:1rem"><input type="checkbox" name="status" checked> Active</label>
            <div class="btn-group">
              <button type="submit" class="btn btn-primary">Save</button>
              <button type="button" class="btn btn-secondary" onclick="Admin.resetRegistrarForm()">Cancel</button>
            </div>
          </form>
        </div>
      </div>

      <div class="card card-flat mt-4">
        <div class="table-wrap">
          <table>
            <thead><tr><th>Name</th><th>Driver</th><th>API Key</th><th>Priority</th><th>Status</th><th></th></tr></thead>
            <tbody>
              ${items.length ? items.map(r => `
                <tr>
                  <td>${app.escape(r.name)}</td>
                  <td>${app.escape(r.driver)}</td>
                  <td>${r.has_token == 1 || r.has_key == 1 ? '<span class="badge badge-active">Set</span>' : '<span class="badge badge-pending">Not set</span>'}</td>
                  <td>${r.priority}</td>
                  <td>${r.status == 1 ? '<span class="badge badge-active">Active</span>' : '<span class="badge badge-cancelled">Disabled</span>'}</td>
                  <td>
                    <button class="btn btn-sm btn-secondary" onclick="Admin.editRegistrar(${r.id})">Edit</button>
                    <a href="#admin-registrar-tlds-${r.id}" class="btn btn-sm btn-secondary">TLD Pricing</a>
                    <button class="btn btn-sm btn-danger" onclick="Admin.deleteRegistrar(${r.id})">Delete</button>
                  </td>
                </tr>
              `).join('') : '<tr><td colspan="6" class="text-center">No registrars configured yet.</td></tr>'}
            </tbody>
          </table>
        </div>
      </div>
    `;

    document.getElementById('registrar-form').onsubmit = async (e) => {
      e.preventDefault();
      const fd = new FormData(e.target);
      const data = {
        id: fd.get('id') || '',
        name: fd.get('name'),
        driver: fd.get('driver'),
        api_key: fd.get('api_key') || '',
        api_secret: fd.get('api_secret') || '',
        api_endpoint: fd.get('api_endpoint') || '',
        priority: fd.get('priority'),
        config: fd.get('config') || '',
        status: fd.get('status') ? '1' : ''
      };
      const r = await app.api('admin/registrar-save', 'POST', data);
      if (r.success) { app.showMessage('Registrar saved.', 'success'); Admin.resetRegistrarForm(); Admin.registrars(app); }
      else app.showMessage(r.message || 'Could not save registrar.', 'danger');
    };
  },

  editRegistrar(id) {
    const r = (Admin._registrars || []).find(x => x.id == id);
    if (!r) return;
    const form = document.getElementById('registrar-form');
    form.id.value = r.id;
    form.name.value = r.name;
    form.driver.value = r.driver;
    form.api_endpoint.value = r.api_endpoint || '';
    form.priority.value = r.priority;
    form.config.value = r.config || '';
    form.status.checked = r.status == 1;
    form.api_key.placeholder = r.has_key ? 'Configured — enter a new key to replace it' : 'Enter to set';
    document.getElementById('registrar-form-title').textContent = `Edit ${r.name}`;
    form.scrollIntoView({ behavior: 'smooth' });
  },

  resetRegistrarForm() {
    const form = document.getElementById('registrar-form');
    if (!form) return;
    form.reset();
    form.id.value = '';
    form.priority.value = '100';
    form.status.checked = true;
    document.getElementById('registrar-form-title').textContent = 'Add Registrar';
  },

  async deleteRegistrar(id) {
    const app = App;
    if (!confirm('Delete this registrar and all of its TLD pricing? This does not affect domains already registered through it.')) return;
    const r = await app.api(`admin/registrar-delete&id=${id}`);
    if (r.success) Admin.registrars(app);
  },

  async registrarTlds(app, registrarId) {
    const registrar = (Admin._registrars || []).find(x => x.id == registrarId);
    const res = await app.api(`admin/registrar-tlds&registrar_id=${registrarId}`);
    const items = res.success && res.data ? res.data.items || [] : [];
    Admin._registrarTlds = items;

    app.$content.innerHTML = `
      <div class="page-header">
        <h1>TLD Pricing — ${app.escape(registrar ? registrar.name : 'Registrar #' + registrarId)}</h1>
        <a href="#admin-registrars" data-nav="admin-registrars" class="btn btn-sm btn-secondary">Back to Registrars</a>
      </div>
      <p style="color:var(--gray-500);margin-bottom:1.5rem">
        Base Price is used when this registrar's own API doesn't return a live price for a TLD.
        The adjustment (fixed amount or percentage, either can be negative for a discount) is
        applied on top of whichever cost is used — live or base — every time a domain is shopped.
      </p>

      <div class="card">
        <div class="card-header"><h3 id="rtld-form-title">Add TLD Price</h3></div>
        <div class="card-body">
          <form id="rtld-form">
            <input type="hidden" name="id" value="">
            <input type="hidden" name="registrar_id" value="${registrarId}">
            <div class="form-row">
              <div class="form-group"><label>Extension (no dot)</label><input type="text" name="tld" class="form-control" placeholder="com" required></div>
              <div class="form-group"><label>Base Price / yr</label><input type="number" step="0.01" min="0" name="base_price" class="form-control" value="8.70" required></div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>Adjustment Type</label>
                <select name="markup_type" class="form-control">
                  <option value="fixed">Fixed Amount ($)</option>
                  <option value="percent">Percentage (%)</option>
                </select>
              </div>
              <div class="form-group">
                <label>Adjustment Value</label>
                <input type="number" step="0.01" name="markup" class="form-control" value="0" required>
                <small style="color:var(--gray-500)">Positive adds, negative discounts — e.g. 1, -0.30, 1 (%), or -0.5 (%)</small>
              </div>
            </div>
            <label style="display:flex;align-items:center;gap:.5rem;margin-bottom:1rem"><input type="checkbox" name="status" checked> Active</label>
            <div class="btn-group">
              <button type="submit" class="btn btn-primary">Save</button>
              <button type="button" class="btn btn-secondary" onclick="Admin.resetRegistrarTldForm(${registrarId})">Cancel</button>
            </div>
          </form>
        </div>
      </div>

      <div class="card card-flat mt-4">
        <div class="table-wrap">
          <table>
            <thead><tr><th>Extension</th><th>Base</th><th>Adjustment</th><th>Est. Final</th><th>Status</th><th></th></tr></thead>
            <tbody>
              ${items.length ? items.map(t => `
                <tr>
                  <td>.${app.escape(t.tld)}</td>
                  <td>$${Number(t.base_price).toFixed(2)}</td>
                  <td>${Number(t.markup) >= 0 ? '+' : ''}${Number(t.markup)}${t.markup_type === 'percent' ? '%' : '$'}</td>
                  <td>$${Number(t.final_price_est).toFixed(2)}</td>
                  <td>${t.status == 1 ? '<span class="badge badge-active">Active</span>' : '<span class="badge badge-cancelled">Disabled</span>'}</td>
                  <td>
                    <button class="btn btn-sm btn-secondary" onclick="Admin.editRegistrarTld(${t.id})">Edit</button>
                    <button class="btn btn-sm btn-danger" onclick="Admin.deleteRegistrarTld(${t.id}, ${registrarId})">Delete</button>
                  </td>
                </tr>
              `).join('') : '<tr><td colspan="6" class="text-center">No TLD pricing configured yet.</td></tr>'}
            </tbody>
          </table>
        </div>
      </div>
    `;

    document.getElementById('rtld-form').onsubmit = async (e) => {
      e.preventDefault();
      const fd = new FormData(e.target);
      const data = {
        id: fd.get('id') || '',
        registrar_id: registrarId,
        tld: fd.get('tld'),
        base_price: fd.get('base_price'),
        markup_type: fd.get('markup_type'),
        markup: fd.get('markup'),
        status: fd.get('status') ? '1' : ''
      };
      const r = await app.api('admin/registrar-tld-save', 'POST', data);
      if (r.success) { app.showMessage('Saved.', 'success'); Admin.resetRegistrarTldForm(registrarId); Admin.registrarTlds(app, registrarId); }
      else app.showMessage(r.message || 'Could not save.', 'danger');
    };
  },

  editRegistrarTld(id) {
    const t = (Admin._registrarTlds || []).find(x => x.id == id);
    if (!t) return;
    const form = document.getElementById('rtld-form');
    form.id.value = t.id;
    form.tld.value = t.tld;
    form.base_price.value = t.base_price;
    form.markup_type.value = t.markup_type || 'fixed';
    form.markup.value = t.markup;
    form.status.checked = t.status == 1;
    document.getElementById('rtld-form-title').textContent = `Edit .${t.tld}`;
    form.scrollIntoView({ behavior: 'smooth' });
  },

  resetRegistrarTldForm(registrarId) {
    const form = document.getElementById('rtld-form');
    if (!form) return;
    form.reset();
    form.id.value = '';
    form.registrar_id.value = registrarId;
    form.base_price.value = '8.70';
    form.markup_type.value = 'fixed';
    form.markup.value = '0';
    form.status.checked = true;
    document.getElementById('rtld-form-title').textContent = 'Add TLD Price';
  },

  async deleteRegistrarTld(id, registrarId) {
    const app = App;
    if (!confirm('Delete this TLD pricing?')) return;
    const r = await app.api(`admin/registrar-tld-delete&id=${id}`);
    if (r.success) Admin.registrarTlds(app, registrarId);
  },

  async coupons(app) {
    const [couponRes, prodRes] = await Promise.all([
      app.api('admin/coupons'),
      app.api('admin/products')
    ]);
    const items = couponRes.success && couponRes.data ? couponRes.data.items || [] : [];
    const products = prodRes.success && prodRes.data ? prodRes.data.items || [] : [];
    Admin._coupons = items;
    Admin._couponProducts = products;

    app.$content.innerHTML = `
      <div class="page-header"><h1>Coupons</h1></div>

      <div class="card">
        <div class="card-header"><h3 id="coupon-form-title">Add Coupon</h3></div>
        <div class="card-body">
          <form id="coupon-form">
            <input type="hidden" name="id" value="">
            <div class="form-row">
              <div class="form-group"><label>Code</label><input type="text" name="code" class="form-control" placeholder="SAVE10" required style="text-transform:uppercase"></div>
              <div class="form-group">
                <label>Discount Type</label>
                <select name="type" class="form-control">
                  <option value="percent">Percentage</option>
                  <option value="fixed">Fixed Amount</option>
                </select>
              </div>
              <div class="form-group"><label>Discount Value</label><input type="number" step="0.01" min="0" name="value" class="form-control" placeholder="10" required></div>
            </div>
            <div class="form-row">
              <div class="form-group"><label>Start Date (optional)</label><input type="date" name="start_date" class="form-control"></div>
              <div class="form-group"><label>Expiration Date (optional)</label><input type="date" name="end_date" class="form-control"></div>
            </div>
            <div class="form-row">
              <div class="form-group"><label>Max Total Uses (blank = unlimited)</label><input type="number" min="0" name="max_uses" class="form-control"></div>
              <div class="form-group"><label>Per-User Limit (blank = unlimited)</label><input type="number" min="0" name="per_user_limit" class="form-control"></div>
              <div class="form-group"><label>Minimum Order Amount</label><input type="number" step="0.01" min="0" name="min_order_amount" class="form-control" value="0"></div>
            </div>
            <div class="form-group">
              <label>Applicable Hosting Products (none selected = all products)</label>
              <select name="applicable_products" class="form-control" multiple size="6">
                ${products.map(p => `<option value="${p.id}">${app.escape(p.pkname)} (#${p.id})</option>`).join('')}
              </select>
            </div>
            <label style="display:flex;align-items:center;gap:.5rem;margin-bottom:1rem"><input type="checkbox" name="status" checked> Active</label>
            <div class="btn-group">
              <button type="submit" class="btn btn-primary">Save</button>
              <button type="button" class="btn btn-secondary" onclick="Admin.resetCouponForm()">Cancel</button>
            </div>
          </form>
        </div>
      </div>

      <div class="card card-flat mt-4">
        <div class="table-wrap">
          <table>
            <thead><tr><th>Code</th><th>Discount</th><th>Uses</th><th>Valid</th><th>Status</th><th></th></tr></thead>
            <tbody>
              ${items.length ? items.map(c => `
                <tr>
                  <td><code>${app.escape(c.code)}</code></td>
                  <td>${c.type === 'percent' ? Number(c.value) + '%' : '$' + Number(c.value).toFixed(2)}</td>
                  <td>${c.used_count}${c.max_uses !== null ? ' / ' + c.max_uses : ''}</td>
                  <td>${c.start_date || '—'} to ${c.end_date || '—'}</td>
                  <td>${c.status == 1 ? '<span class="badge badge-active">Active</span>' : '<span class="badge badge-cancelled">Disabled</span>'}</td>
                  <td>
                    <button class="btn btn-sm btn-secondary" onclick="Admin.editCoupon(${c.id})">Edit</button>
                    <button class="btn btn-sm btn-danger" onclick="Admin.deleteCoupon(${c.id})">Delete</button>
                  </td>
                </tr>
              `).join('') : '<tr><td colspan="6" class="text-center">No coupons yet.</td></tr>'}
            </tbody>
          </table>
        </div>
      </div>
    `;

    document.getElementById('coupon-form').onsubmit = async (e) => {
      e.preventDefault();
      const form = e.target;
      const selected = Array.from(form.applicable_products.selectedOptions).map(o => o.value);
      const data = {
        id: form.id.value || '',
        code: form.code.value,
        type: form.type.value,
        value: form.value.value,
        start_date: form.start_date.value,
        end_date: form.end_date.value,
        max_uses: form.max_uses.value,
        per_user_limit: form.per_user_limit.value,
        min_order_amount: form.min_order_amount.value,
        applicable_products: selected.join(','),
        status: form.status.checked ? '1' : ''
      };
      const r = await app.api('admin/coupon-save', 'POST', data);
      if (r.success) { app.showMessage('Coupon saved.', 'success'); Admin.resetCouponForm(); Admin.coupons(app); }
      else app.showMessage(r.message || 'Could not save coupon.', 'danger');
    };
  },

  editCoupon(id) {
    const c = (Admin._coupons || []).find(x => x.id == id);
    if (!c) return;
    const form = document.getElementById('coupon-form');
    form.id.value = c.id;
    form.code.value = c.code;
    form.type.value = c.type;
    form.value.value = c.value;
    form.start_date.value = c.start_date || '';
    form.end_date.value = c.end_date || '';
    form.max_uses.value = c.max_uses ?? '';
    form.per_user_limit.value = c.per_user_limit ?? '';
    form.min_order_amount.value = c.min_order_amount;
    form.status.checked = c.status == 1;
    const ids = (c.applicable_products || '').split(',').filter(Boolean);
    Array.from(form.applicable_products.options).forEach(o => { o.selected = ids.includes(o.value); });
    document.getElementById('coupon-form-title').textContent = `Edit ${c.code}`;
    form.scrollIntoView({ behavior: 'smooth' });
  },

  resetCouponForm() {
    const form = document.getElementById('coupon-form');
    if (!form) return;
    form.reset();
    form.id.value = '';
    form.status.checked = true;
    document.getElementById('coupon-form-title').textContent = 'Add Coupon';
  },

  async deleteCoupon(id) {
    const app = App;
    if (!confirm('Delete this coupon? Usage history will also be removed.')) return;
    const r = await app.api(`admin/coupon-delete&id=${id}`);
    if (r.success) Admin.coupons(app);
  },

  async tickets(app) {
    const res = await app.api('admin/tickets');
    const items = res.success && res.data ? res.data.items || [] : [];
    const stale = items.filter(t => t.status == 1).length;

    app.$content.innerHTML = `
      <div class="page-header">
        <h1>All Support Tickets</h1>
        <button class="btn btn-sm btn-secondary" onclick="Admin.bulkCloseTickets()">Close Old Answered Tickets</button>
      </div>
      <div class="card card-flat">
        <div class="table-wrap">
          <table>
            <thead><tr><th>#</th><th>Subject</th><th>Status</th><th>Last Updated</th><th></th></tr></thead>
            <tbody>
              ${items.length ? items.map(t => `
                <tr>
                  <td>#${t.rid}</td>
                  <td>${app.escape(t.subject || '')}</td>
                  <td><span class="${app.ticketClass(t.status)}">${app.ticketLabel(t.status)}</span></td>
                  <td>${t.date || '-'}</td>
                  <td><a href="#ticket-${t.rid}" class="btn btn-sm btn-primary" onclick="Support.view(${t.rid})">View</a></td>
                </tr>
              `).join('') : '<tr><td colspan="5" class="text-center">No tickets found.</td></tr>'}
            </tbody>
          </table>
        </div>
      </div>
    `;
  },

  async bulkCloseTickets() {
    const app = App;
    const r = await app.api('admin/bulk-close');
    app.showMessage(r.message || 'Done.', r.success ? 'success' : 'danger');
    if (r.success) Admin.tickets(app);
  },

  async news(app) {
    const res = await app.api('admin/news');
    const items = res.success && res.data ? res.data.items || [] : [];

    app.$content.innerHTML = `
      <div class="page-header"><h1>News Editor</h1></div>
      <div class="card">
        <div class="card-body">
          <form id="news-form">
            <div class="form-group"><label>Title</label><input type="text" name="title" class="form-control" required></div>
            <div class="form-group"><label>Message</label><textarea name="message" class="form-control" rows="6" required></textarea></div>
            <label style="display:flex;align-items:center;gap:.5rem;margin-bottom:1rem"><input type="checkbox" name="pinned"> Pin to top</label>
            <button type="submit" class="btn btn-primary">Add News</button>
          </form>
        </div>
      </div>
      <div class="card card-flat mt-4">
        <div class="table-wrap">
          <table>
            <thead><tr><th>Title</th><th>Date</th><th></th></tr></thead>
            <tbody>
              ${items.length ? items.map(n => `
                <tr>
                  <td>${n.pinned == 1 ? '<i class="fas fa-thumbtack" style="color:var(--primary)"></i> ' : ''}${app.escape(n.title)}</td>
                  <td>${n.date ? n.date.slice(0,10) : '-'}</td>
                  <td><button class="btn btn-sm btn-danger" onclick="Admin.deleteNews(${n.id})">Delete</button></td>
                </tr>
              `).join('') : '<tr><td colspan="3" class="text-center">No news posted yet.</td></tr>'}
            </tbody>
          </table>
        </div>
      </div>
    `;

    document.getElementById('news-form')?.addEventListener('submit', async (e) => {
      e.preventDefault();
      const fd = new FormData(e.target);
      const data = { title: fd.get('title'), message: fd.get('message'), pinned: fd.get('pinned') ? '1' : '' };
      const r = await app.api('admin/news-create', 'POST', data);
      if (r.success) { app.showMessage('News added.', 'success'); Admin.news(app); }
      else app.showMessage(r.message || 'Failed to add news.', 'danger');
    });
  },

  async deleteNews(id) {
    const app = App;
    const r = await app.api(`admin/news-delete&id=${id}`);
    if (r.success) Admin.news(app);
  }
};
