// ─── Detail Modal ─────────────────────────────────────────────────────────────

function RequestDetailModal({ request: r, onClose, onStatusChange }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);

  return (
    <div
      className="detail-modal-overlay"
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div className="detail-modal" role="dialog" aria-modal="true">

        <div className="detail-modal__head">
          <div>
            <div className="detail-modal__title">{r.name}</div>
            {r.service && <div className="detail-modal__sub">{r.service}</div>}
          </div>
          <button className="icon-btn" onClick={onClose} aria-label="Close">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M2 2l10 10M12 2L2 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
            </svg>
          </button>
        </div>

        <div className="detail-modal__body">
          <div className="detail-modal__row">
            <span className="detail-field__label">Email</span>
            <span className="detail-field__value">{r.email}</span>
          </div>
          {r.company && (
            <div className="detail-modal__row">
              <span className="detail-field__label">Company</span>
              <span className="detail-field__value">{r.company}</span>
            </div>
          )}
          {r.timeline && (
            <div className="detail-modal__row">
              <span className="detail-field__label">Timeline</span>
              <span className="detail-field__value">{r.timeline}</span>
            </div>
          )}
          {r.submitted_from && (
            <div className="detail-modal__row">
              <span className="detail-field__label">Source</span>
              <span className="detail-field__value">{r.submitted_from}</span>
            </div>
          )}
          <div className="detail-modal__row">
            <span className="detail-field__label">Date</span>
            <span className="detail-field__value">{new Date(r.created_at || r.createdAt).toLocaleString()}</span>
          </div>
          {r.description && (
            <div className="detail-modal__desc">
              <div className="detail-field__label" style={{ marginBottom: 'var(--space-1)' }}>Description</div>
              <div className="detail-field__value" style={{ whiteSpace: 'pre-wrap', lineHeight: 'var(--lh-normal)' }}>{r.description}</div>
            </div>
          )}
        </div>

        <div className="detail-modal__actions">
          <div className="detail-field__label" style={{ flexShrink: 0 }}>Status</div>
          <select
            value={r.status}
            onChange={(e) => onStatusChange(r.id, e.target.value)}
            className={`status-select pill pill--${r.status}`}
            style={{ flex: 1 }}
          >
            {['new', 'in_progress', 'completed'].map(s => (
              <option key={s} value={s}>{s.replace('_', ' ')}</option>
            ))}
          </select>
          <button className="btn btn--ghost" style={{ fontSize: 'var(--fs-caption)', padding: '5px var(--space-4)' }} onClick={onClose}>
            Done
          </button>
        </div>

      </div>
    </div>
  );
}

// ─── Requests ─────────────────────────────────────────────────────────────────

function Requests({ requests, onStatusChange }) {
  const [filter,   setFilter]   = React.useState('all');
  const [detailId, setDetailId] = React.useState(null);

  const statuses = ['all', 'new', 'in_progress', 'completed'];

  const filtered = filter === 'all'
    ? requests
    : requests.filter((r) => r.status === filter);

  const detail = requests.find(r => r.id === detailId);

  return (
    <div>
      <h1 className="page-title">Requests</h1>
      <p className="page-subtitle">All client design requests</p>

      <div style={{ display: 'flex', gap: 'var(--space-2)', marginBottom: 'var(--space-5)', flexWrap: 'wrap' }}>
        {statuses.map((s) => (
          <button
            key={s}
            className={`btn ${filter === s ? 'btn--primary' : 'btn--ghost'}`}
            onClick={() => setFilter(s)}
            style={{ fontSize: 'var(--fs-caption)', padding: '5px var(--space-4)' }}
          >
            {s.replace('_', ' ')}
          </button>
        ))}
        <span style={{ marginLeft: 'auto', fontSize: 'var(--fs-caption)', color: 'var(--fg-secondary)', lineHeight: '30px' }}>
          {filtered.length} result{filtered.length !== 1 ? 's' : ''}
        </span>
      </div>

      <div className="table-wrap">
        <table>
          <thead>
            <tr>
              <th>Client</th>
              <th>Status</th>
              <th className="td-hide-mobile">Date</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {filtered.length === 0 && (
              <tr>
                <td colSpan="4" className="td-muted" style={{ textAlign: 'center', padding: 'var(--space-8)' }}>
                  No requests
                </td>
              </tr>
            )}
            {filtered.map((r) => (
              <tr key={r.id} style={{ cursor: 'pointer' }} onClick={() => setDetailId(r.id)}>
                <td data-label="Client">
                  <div>
                    <div style={{ fontWeight: 'var(--fw-medium)' }}>{r.name}</div>
                    <div className="td-muted" style={{ fontSize: 'var(--fs-caption)' }}>{r.service}</div>
                  </div>
                </td>
                <td data-label="Status">
                  <span className={`pill pill--${r.status}`}>{r.status.replace('_', ' ')}</span>
                </td>
                <td data-label="Date" className="td-muted td-hide-mobile">
                  {new Date(r.created_at || r.createdAt).toLocaleDateString()}
                </td>
                <td className="td-action-col" onClick={(e) => { e.stopPropagation(); setDetailId(r.id); }}>
                  <button className="icon-btn" title="View details" tabIndex={-1}>
                    <svg width="15" height="15" viewBox="0 0 15 15" fill="none">
                      <circle cx="7.5" cy="7.5" r="6" stroke="currentColor" strokeWidth="1.3"/>
                      <path d="M7.5 5v.5M7.5 7v4" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
                    </svg>
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {detail && (
        <RequestDetailModal
          request={detail}
          onClose={() => setDetailId(null)}
          onStatusChange={onStatusChange}
        />
      )}
    </div>
  );
}
