// Support Tickets — customers / suppliers raise; staff & admin respond.

const TICKET_STATUS_META = {
  'open':              { label: 'Open',              kind: 'blue'   },
  'in-progress':       { label: 'In progress',       kind: 'amber'  },
  'waiting-customer':  { label: 'Waiting on user',   kind: 'amber'  },
  'resolved':          { label: 'Resolved',          kind: 'green'  },
  'closed':            { label: 'Closed',            kind: 'grey'   },
};

const TICKET_PRIORITY_META = {
  low:    { label: 'Low',    color: 'var(--text-mute)' },
  medium: { label: 'Medium', color: 'var(--blue)' },
  high:   { label: 'High',   color: 'var(--amber)' },
  urgent: { label: 'Urgent', color: 'var(--red)' },
};

const TICKET_CATEGORY_META = {
  document:  { label: 'Document', icon: 'docs' },
  payment:   { label: 'Payment',  icon: 'po' },
  account:   { label: 'Account',  icon: 'users' },
  access:    { label: 'Access',   icon: 'shield' },
  technical: { label: 'Technical',icon: 'settings' },
  other:     { label: 'Other',    icon: 'comment' },
};

const TicketsPage = ({ role, openTicket, openTicketId }) => {
  const { TICKETS, STAFF, ME_ADMIN, ME_SUPPLIER, SAIF_COMPANIES } = window.SaifData;
  const [filter, setFilter] = React.useState('all');
  const [query, setQuery] = React.useState('');

  if (openTicketId) {
    const t = TICKETS.find(x => x.id === openTicketId);
    if (t) return <TicketDetail ticket={t} onClose={() => openTicket(null)} role={role}/>;
  }

  // Scope: supplier role sees only their own tickets
  let scoped = TICKETS;
  if (role === 'supplier') {
    scoped = TICKETS.filter(t => t.requester.kind === 'supplier' && t.requester.org === ME_SUPPLIER.company_name);
  }

  const counts = {
    all: scoped.length,
    open: scoped.filter(t => t.status === 'open').length,
    'in-progress': scoped.filter(t => t.status === 'in-progress').length,
    'waiting-customer': scoped.filter(t => t.status === 'waiting-customer').length,
    resolved: scoped.filter(t => t.status === 'resolved').length,
    closed: scoped.filter(t => t.status === 'closed').length,
  };

  const q = query.trim().toLowerCase();
  const filtered = scoped.filter(t => {
    if (filter !== 'all' && t.status !== filter) return false;
    if (!q) return true;
    return t.subject.toLowerCase().includes(q)
        || t.number.toLowerCase().includes(q)
        || t.requester.name.toLowerCase().includes(q)
        || t.requester.org.toLowerCase().includes(q);
  });

  const allUsers = [...STAFF, ME_ADMIN];
  const userById = (id) => allUsers.find(u => u.id === id);
  const coById = (id) => SAIF_COMPANIES.find(c => c.id === id);

  const kpiOpen      = counts.open;
  const kpiActive    = counts['in-progress'] + counts.open + counts['waiting-customer'];
  const kpiUrgent    = scoped.filter(t => t.priority === 'urgent' && t.status !== 'resolved' && t.status !== 'closed').length;
  const kpiUnassigned= scoped.filter(t => !t.assignee && t.status !== 'resolved' && t.status !== 'closed').length;

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Support</h1>
          <p className="page-subtitle">{role === 'supplier' ? 'Your support tickets — open a new one or follow up on existing.' : 'Tickets raised by suppliers and customers — assign, respond, and close.'}</p>
        </div>
        <div className="page-actions">
          {role !== 'supplier' && <button className="btn"><Icon name="download" size={14}/> Export</button>}
          <button className="btn btn-primary"><Icon name="plus" size={14}/> New ticket</button>
        </div>
      </div>

      <div className="kpi-grid" style={{ marginBottom: 18 }}>
        <KPICard label="Open" value={kpiOpen} meta="awaiting first response" icon="inbox"/>
        <KPICard label="Active" value={kpiActive} meta="in progress + open" icon="comment"/>
        <KPICard label="Urgent" value={kpiUrgent} meta="needs immediate attention" icon="alert"/>
        <KPICard label="Unassigned" value={kpiUnassigned} meta="no owner yet" icon="users"/>
      </div>

      <div className="tabs" style={{ marginBottom: 14 }}>
        {[
          { id: 'all',              label: 'All' },
          { id: 'open',             label: 'Open' },
          { id: 'in-progress',      label: 'In progress' },
          { id: 'waiting-customer', label: 'Waiting on user' },
          { id: 'resolved',         label: 'Resolved' },
          { id: 'closed',           label: 'Closed' },
        ].map(t => (
          <button key={t.id} className="tab" data-active={filter === t.id} onClick={() => setFilter(t.id)}>
            {t.label} <span className="tab-count">{counts[t.id]}</span>
          </button>
        ))}
      </div>

      <div style={{ marginBottom: 14, position: 'relative', maxWidth: 360 }}>
        <input
          className="form-control"
          placeholder="Search tickets by subject, number, or requester…"
          value={query}
          onChange={e => setQuery(e.target.value)}
          style={{ paddingLeft: 32 }}
        />
        <span style={{ position: 'absolute', left: 10, top: 9, color: 'var(--text-mute)' }}>
          <Icon name="search" size={13}/>
        </span>
      </div>

      {filtered.length === 0 ? (
        <div className="card"><div className="empty-state">
          <Icon name="comment" size={28} className="text-dim"/>
          <h3>No tickets here</h3>
          <p>Try a different filter, or open a new ticket.</p>
        </div></div>
      ) : (
        <div className="card">
          <table className="tbl tkt-tbl">
            <thead>
              <tr>
                <th>Number</th>
                <th>Subject</th>
                <th>Requester</th>
                <th>Category</th>
                <th>Priority</th>
                <th>Assignee</th>
                <th>Updated</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(t => {
                const assignee = t.assignee ? userById(t.assignee) : null;
                const cat = TICKET_CATEGORY_META[t.category];
                const prio = TICKET_PRIORITY_META[t.priority];
                const stat = TICKET_STATUS_META[t.status];
                return (
                  <tr key={t.id} onClick={() => openTicket(t.id)}>
                    <td className="text-mono text-xs" style={{ fontWeight: 600, color: 'var(--accent-ink)', whiteSpace: 'nowrap' }}>{t.number}</td>
                    <td>
                      <div style={{ fontWeight: 600, color: 'var(--ink)', fontSize: 13 }}>{t.subject}</div>
                      <div style={{ fontSize: 11, color: 'var(--text-mute)', marginTop: 2 }}>
                        <span className="company-dot" style={{ background: coById(t.company)?.color, width: 6, height: 6, borderRadius: '50%', display: 'inline-block', marginRight: 5 }}></span>
                        {coById(t.company)?.name} · {t.messages.length} message{t.messages.length > 1 ? 's' : ''}
                      </div>
                    </td>
                    <td>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <Avatar name={t.requester.name} size="sm" tone={t.requester.tone}/>
                        <div>
                          <div style={{ fontSize: 12, fontWeight: 500 }}>{t.requester.name}</div>
                          <div style={{ fontSize: 10, color: 'var(--text-mute)' }}>
                            <span className={`tkt-kind tkt-kind-${t.requester.kind}`}>{t.requester.kind}</span> · {t.requester.org}
                          </div>
                        </div>
                      </div>
                    </td>
                    <td>
                      <span className="tkt-cat"><Icon name={cat.icon} size={11}/> {cat.label}</span>
                    </td>
                    <td>
                      <span className="tkt-prio" style={{ color: prio.color }}>● {prio.label}</span>
                    </td>
                    <td className="text-xs">{assignee ? assignee.name : <span className="text-mute">— Unassigned</span>}</td>
                    <td className="text-xs text-mute">{t.updated.split(' ')[0]}</td>
                    <td><Badge kind={stat.kind}>{stat.label}</Badge></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

const TicketDetail = ({ ticket, onClose, role }) => {
  const { STAFF, ME_ADMIN, SAIF_COMPANIES } = window.SaifData;
  const [draft, setDraft] = React.useState('');
  const [internal, setInternal] = React.useState(false);

  const allUsers = [...STAFF, ME_ADMIN];
  const userById = (id) => allUsers.find(u => u.id === id);
  const coById = (id) => SAIF_COMPANIES.find(c => c.id === id);

  const stat = TICKET_STATUS_META[ticket.status];
  const prio = TICKET_PRIORITY_META[ticket.priority];
  const cat = TICKET_CATEGORY_META[ticket.category];
  const co = coById(ticket.company);
  const assignee = ticket.assignee ? userById(ticket.assignee) : null;
  const isClosed = ticket.status === 'resolved' || ticket.status === 'closed';

  return (
    <div className="page">
      <div style={{ marginBottom: 16 }}>
        <button className="btn btn-ghost btn-sm" onClick={onClose}>
          <Icon name="chevronLeft" size={13}/> Back to support
        </button>
      </div>

      <div className="page-header">
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="text-mono text-xs" style={{ color: 'var(--accent-ink)', fontWeight: 600, marginBottom: 4 }}>{ticket.number}</div>
          <h1 className="page-title">{ticket.subject}</h1>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 6, flexWrap: 'wrap' }}>
            <Badge kind={stat.kind}>{stat.label}</Badge>
            <span className="tkt-prio" style={{ color: prio.color, fontSize: 12, fontWeight: 600 }}>● {prio.label} priority</span>
            <span className="text-mute text-md">·</span>
            <span className="tkt-cat"><Icon name={cat.icon} size={11}/> {cat.label}</span>
            <span className="text-mute text-md">·</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12 }}>
              <span className="company-dot" style={{ background: co.color }}></span> {co.name}
            </span>
          </div>
        </div>
        <div className="page-actions">
          {!isClosed && role !== 'supplier' && (
            <>
              <button className="btn"><Icon name="users" size={14}/> Assign</button>
              <button className="btn"><Icon name="check" size={14}/> Mark resolved</button>
            </>
          )}
        </div>
      </div>

      <div className="tkt-detail-grid">
        {/* LEFT: Conversation */}
        <div className="card">
          <div className="card-header">
            <div>
              <h3 className="card-title">Conversation</h3>
              <div className="card-sub">{ticket.messages.length} message{ticket.messages.length > 1 ? 's' : ''}</div>
            </div>
          </div>
          <div className="tkt-thread">
            {ticket.messages.map(m => (
              <div key={m.id} className={`tkt-msg tkt-msg-${m.side}`}>
                <Avatar name={m.author} size="sm" tone={m.side === 'requester' ? ticket.requester.tone : null}/>
                <div className="tkt-msg-body">
                  <div className="tkt-msg-head">
                    <span className="tkt-msg-author">{m.author}</span>
                    <span className={`tkt-msg-side tkt-msg-side-${m.side}`}>{m.role}</span>
                    <span className="tkt-msg-time">{m.time}</span>
                  </div>
                  <div className="tkt-msg-text">{m.text}</div>
                </div>
              </div>
            ))}
          </div>

          {!isClosed && (
            <div className="tkt-reply">
              <textarea
                className="form-control"
                placeholder={internal ? 'Write an internal note (visible to staff only)…' : 'Reply to the requester…'}
                value={draft}
                onChange={e => setDraft(e.target.value)}
                rows={4}
              />
              <div className="tkt-reply-actions">
                <button className="btn btn-sm btn-ghost"><Icon name="paperclip" size={12}/> Attach</button>
                {role !== 'supplier' && (
                  <label style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--text-mute)' }}>
                    <input type="checkbox" checked={internal} onChange={e => setInternal(e.target.checked)}/> Internal note
                  </label>
                )}
                <span style={{ flex: 1 }}/>
                <button className="btn btn-sm">Save draft</button>
                <button className="btn btn-sm btn-primary" disabled={!draft.trim()}>
                  <Icon name="send" size={12}/> Send reply
                </button>
              </div>
            </div>
          )}
        </div>

        {/* RIGHT: Sidebar info */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div className="card">
            <div className="card-header"><h3 className="card-title">Requester</h3></div>
            <div className="card-body" style={{ paddingTop: 6 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <Avatar name={ticket.requester.name} size="md" tone={ticket.requester.tone}/>
                <div>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>{ticket.requester.name}</div>
                  <div style={{ fontSize: 12, color: 'var(--text-mute)' }}>
                    <span className={`tkt-kind tkt-kind-${ticket.requester.kind}`}>{ticket.requester.kind}</span>
                  </div>
                </div>
              </div>
              <div style={{ marginTop: 14, fontSize: 12, lineHeight: 1.7 }}>
                <div><span className="text-mute">Organization · </span>{ticket.requester.org}</div>
                <div><span className="text-mute">Email · </span><span className="text-mono text-xs">{ticket.requester.email}</span></div>
              </div>
            </div>
          </div>

          <div className="card">
            <div className="card-header"><h3 className="card-title">Ticket details</h3></div>
            <div className="card-body" style={{ paddingTop: 6, fontSize: 12, lineHeight: 1.8 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span className="text-mute">Status</span>
                <Badge kind={stat.kind}>{stat.label}</Badge>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span className="text-mute">Priority</span>
                <span className="tkt-prio" style={{ color: prio.color, fontWeight: 600 }}>● {prio.label}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span className="text-mute">Category</span>
                <span className="tkt-cat"><Icon name={cat.icon} size={11}/> {cat.label}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span className="text-mute">Group company</span>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
                  <span className="company-dot" style={{ background: co.color }}></span> {co.name}
                </span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span className="text-mute">Assignee</span>
                <span>{assignee ? assignee.name : <em className="text-mute">Unassigned</em>}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span className="text-mute">Opened</span>
                <span className="text-mono text-xs">{ticket.created}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span className="text-mute">Last update</span>
                <span className="text-mono text-xs">{ticket.updated}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { TicketsPage, TicketDetail });
