// ─── Support Module ─────────────────────────────────────────────────

const Support = {
  async render(app) {
    const res = await app.api('support/tickets');
    const tickets = res.success && res.data ? res.data.items || [] : [];

    app.$content.innerHTML = `
      <div class="card">
        <div class="card-header">
          <h3>Support Tickets</h3>
          <a href="#new-ticket" data-nav="new-ticket" class="btn btn-primary btn-sm"><i class="fas fa-plus"></i> New Ticket</a>
        </div>
        <div class="card-body">
          <div class="table-container">
            <table>
              <thead>
                <tr><th>Ticket #</th><th>Subject</th><th>Status</th><th>Last Updated</th><th></th></tr>
              </thead>
              <tbody>
                ${tickets.length ? tickets.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>
      </div>
    `;
  },

  async view(rid) {
    window.location.hash = `ticket-${rid}`;
    const app = App;
    app.showLoading();
    
    const res = await app.api(`support/ticket&rid=${rid}`);
    if (!res.success) { app.$content.innerHTML = '<div class="empty-state">Ticket not found</div>'; return; }
    
    const t = res.data;
    app.$content.innerHTML = `
      <div class="card">
        <div class="card-header">
          <h3>Ticket #${t.rid} — ${app.escape(t.subject)}</h3>
          <div>
            <a href="#tickets" data-nav="tickets" class="btn btn-secondary btn-sm"><i class="fas fa-arrow-left"></i> Back</a>
            <button class="btn btn-danger btn-sm" onclick="Support.close(${t.rid})">Close</button>
          </div>
        </div>
        <div class="card-body">
          <div id="ticket-messages">
            ${t.messages && t.messages.length ? t.messages.map(m => `
              <div style="padding:1rem;margin-bottom:1rem;background:${m.is_staff ? 'var(--primary-light)' : 'var(--gray-50)'};border-radius:var(--radius)">
                <div style="display:flex;justify-content:space-between;margin-bottom:.5rem">
                  <strong>${app.escape(m.user_name)}</strong>
                  <small>${m.date}</small>
                </div>
                <p>${app.escape(m.message)}</p>
              </div>
            `).join('') : '<p>No messages</p>'}
          </div>
          
          <form id="reply-form" style="margin-top:1.5rem">
            <div class="form-group">
              <label>Your Reply</label>
              <textarea name="message" class="form-control" rows="5" required></textarea>
            </div>
            <button type="submit" class="btn btn-primary">Send Reply</button>
          </form>
        </div>
      </div>
    `;

    document.getElementById('reply-form').onsubmit = async (e) => {
      e.preventDefault();
      const fd = new FormData(e.target);
      const data = { rid, subject: t.subject, message: fd.get('message') };
      const r = await app.api('support/reply', 'POST', data);
      if (r.success) { app.showMessage('Reply sent!', 'success'); Support.view(rid); }
    };
  },

  async renderNew(app) {
    app.$content.innerHTML = `
      <div class="card">
        <div class="card-header"><h3>Open New Ticket</h3></div>
        <div class="card-body">
          <form id="new-ticket-form">
            <div class="form-group">
              <label>Subject</label>
              <input type="text" name="subject" class="form-control" maxlength="40" required>
            </div>
            <div class="form-group">
              <label>Message</label>
              <textarea name="message" class="form-control" rows="8" required></textarea>
            </div>
            <button type="submit" class="btn btn-primary">Submit Ticket</button>
            <a href="#tickets" data-nav="tickets" class="btn btn-secondary">Cancel</a>
          </form>
        </div>
      </div>
    `;

    document.getElementById('new-ticket-form').onsubmit = async (e) => {
      e.preventDefault();
      const fd = new FormData(e.target);
      const data = {};
      fd.forEach((v, k) => data[k] = v);
      const r = await app.api('support/create', 'POST', data);
      if (r.success) { app.showMessage('Ticket created!', 'success'); app.navigate('tickets'); }
    };
  },

  async close(rid) {
    const app = App;
    await app.api(`support/close&rid=${rid}`);
    app.showMessage('Ticket closed.', 'success');
    app.navigate('tickets');
  }
};