// Approvals screen — shows pending edits and creates.
// Smart: only one pending request per entity (the latest one).

const ApprovalsScreen = ({ approvals, domains, servers, clients, role, onApprove, onReject }) => {
  const entityFor = (a) => {
    if (a.kind === 'create') return null;
    return a.entity === 'domain' ? domains.find(d => d.id === a.entityId) : servers.find(s => s.id === a.entityId);
  };

  if (!approvals.length) {
    return (
      <>
        <div className="page-head">
          <div><h1>Approvals</h1><div className="sub">Pending changes awaiting admin review</div></div>
        </div>
        <Empty
          icon="check"
          title="All caught up"
          body="No changes are waiting for approval right now."
        />
      </>
    );
  }

  return (
    <>
      <div className="page-head">
        <div>
          <h1>Approvals</h1>
          <div className="sub">{approvals.length} change{approvals.length === 1 ? '' : 's'} awaiting review</div>
        </div>
      </div>

      <div className="notice brand">
        <Icon name="info" size={14}/>
        <div>
          <strong>Smart queue.</strong> If the same employee re-submits an edit for the same record, the older request is replaced with the latest one — only the freshest version sits here.
        </div>
      </div>

      {approvals.map(a => {
        const e = entityFor(a);
        const client = clients.find(c => c.id === (e?.clientId || a.payload?.clientId));
        const kindLabel = a.entity === 'domain' ? 'domain' : 'server';
        const title = a.kind === 'create'
          ? `New ${kindLabel} · ${a.entity === 'domain' ? a.payload.name : a.payload.label}`
          : `Edit ${kindLabel} · ${a.entity === 'domain' ? e?.name : e?.label}`;

        return (
          <div className="approval-card" key={a.id}>
            <div className="approval-head">
              <Avatar name={a.by} size={26} />
              <div style={{ flex: 1 }}>
                <div className="what">{title}</div>
                <div className="who">
                  Requested by <strong>{a.by}</strong> · {a.at}
                  {client && <> · for <strong>{client.name}</strong></>}
                </div>
              </div>
              <KindPill kind={a.entity} />
              {a.kind === 'create'
                ? <span className="badge blue">New</span>
                : <span className="badge amber">Edit</span>}
            </div>
            <div className="approval-body">
              {a.kind === 'edit' ? (
                <>
                  <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 8 }}>
                    {Object.keys(a.changes).length} field{Object.keys(a.changes).length === 1 ? '' : 's'} changing
                  </div>
                  {Object.entries(a.changes).map(([field, newVal]) => (
                    <div className="diff-row" key={field}>
                      <div className="diff-label">{FIELD_LABELS[field] || field}</div>
                      <div className="diff-old">{renderFieldValue(e, field, e?.[field], clients, servers)}</div>
                      <div className="diff-arrow"><Icon name="chevron" size={12}/></div>
                      <div><span className="diff-new">{renderFieldValue(e, field, newVal, clients, servers)}</span></div>
                    </div>
                  ))}
                </>
              ) : (
                <>
                  <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 8 }}>
                    Full record being created
                  </div>
                  <div className="kv-grid">
                    {Object.entries(a.payload).filter(([k]) => FIELD_LABELS[k]).map(([k, v]) => (
                      <React.Fragment key={k}>
                        <div className="k">{FIELD_LABELS[k]}</div>
                        <div className="v">{renderFieldValue(null, k, v, clients, servers)}</div>
                      </React.Fragment>
                    ))}
                  </div>
                </>
              )}
              {a.note && (
                <div style={{ marginTop: 12, padding: '8px 10px', background: 'var(--bg-subtle)', borderRadius: 6, fontSize: 12, color: 'var(--text-secondary)' }}>
                  <strong style={{ color: 'var(--text)' }}>Note: </strong>{a.note}
                </div>
              )}
            </div>
            <div className="approval-foot">
              {role === 'admin' ? (
                <>
                  <button className="btn" onClick={() => onReject(a)}><Icon name="x" size={13}/> Reject</button>
                  <button className="btn brand" onClick={() => onApprove(a)}><Icon name="check" size={13}/> Approve & apply</button>
                </>
              ) : (
                <span className="badge amber"><Icon name="clock" size={11}/> Awaiting admin</span>
              )}
            </div>
          </div>
        );
      })}
    </>
  );
};

window.ApprovalsScreen = ApprovalsScreen;
