/* global React, Icon, SHASTE_API */

function normalizeCodes(payload) {
  if (Array.isArray(payload)) return payload;
  if (payload && Array.isArray(payload.codes)) return payload.codes;
  if (payload && Array.isArray(payload.items)) return payload.items;
  return [];
}

function readCodeEntry(raw) {
  if (!raw || typeof raw !== 'object') return null;
  return {
    id: String(raw.id || raw.code_id || raw.codeId || raw.code || Math.random()),
    code: String(raw.code || raw.redeem_code || raw.redeemCode || ''),
    status: String(raw.status || raw.state || 'Redeemed'),
    reward: String(raw.reward || raw.reward_text || raw.rewardText || raw.outcome || ''),
    redeemedAt: String(raw.redeemed_at || raw.redeemedAt || raw.created_at || raw.createdAt || ''),
  };
}

function formatDate(value) {
  if (!value) return '—';
  var when = new Date(value);
  if (!Number.isFinite(when.getTime())) return value;
  return when.toLocaleString();
}

function CodesPage({ setPage }) {
  var [loading, setLoading] = React.useState(true);
  var [submitting, setSubmitting] = React.useState(false);
  var [codeInput, setCodeInput] = React.useState('');
  var [codes, setCodes] = React.useState([]);
  var [message, setMessage] = React.useState({ error: '', success: '' });

  var loadCodes = React.useCallback(async function loadCodes() {
    if (!SHASTE_API || typeof SHASTE_API.getUserCodes !== 'function') {
      setCodes([]);
      setMessage({ error: 'Code history is unavailable right now.', success: '' });
      setLoading(false);
      return;
    }

    setLoading(true);
    try {
      var payload = await SHASTE_API.getUserCodes();
      var nextCodes = normalizeCodes(payload).map(readCodeEntry).filter(Boolean);
      setCodes(nextCodes);
      setMessage(function (prev) { return { error: '', success: prev.success }; });
    } catch (err) {
      setMessage({ error: (err && err.message) || 'Failed to load code history.', success: '' });
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(function () {
    loadCodes();
  }, [loadCodes]);

  async function onSubmit(e) {
    e.preventDefault();
    var trimmed = codeInput.trim();
    if (!trimmed || submitting) return;
    if (!SHASTE_API || typeof SHASTE_API.redeemCode !== 'function') {
      setMessage({ error: 'Code redemption is unavailable right now.', success: '' });
      return;
    }

    setSubmitting(true);
    setMessage({ error: '', success: '' });
    try {
      await SHASTE_API.redeemCode(trimmed);
      setCodeInput('');
      setMessage({ error: '', success: 'Code redeemed successfully.' });
      await loadCodes();
    } catch (err) {
      setMessage({ error: (err && err.message) || 'Could not redeem this code.', success: '' });
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="container fade-in" style={{ maxWidth: 980 }}>
      <div style={{ marginTop: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
        <div>
          <div className="eyebrow">Profile</div>
          <h1 className="h-display" style={{ fontSize: 'clamp(30px, 4vw, 42px)', marginTop: 6 }}>Codes</h1>
          <p style={{ color: 'var(--muted)', margin: '8px 0 0' }}>Redeem a code and review your redemption history.</p>
        </div>
        <button className="btn btn--ghost" onClick={function () { setPage('profile'); }}>
          <Icon name="arrow" size={12} /> Back to profile
        </button>
      </div>

      <div className="card" style={{ marginTop: 16 }}>
        <form onSubmit={onSubmit} style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 10 }}>
          <input
            className="input"
            placeholder="Enter code"
            value={codeInput}
            onChange={function (e) { setCodeInput(e.target.value); }}
            autoComplete="off"
            spellCheck={false}
          />
          <button className="btn btn--primary" type="submit" disabled={submitting || !codeInput.trim()}>
            {submitting ? 'Redeeming…' : 'Redeem code'} <Icon name="arrow" size={12} />
          </button>
        </form>
      </div>

      {message.error && <div className="card" style={{ marginTop: 14, borderColor: 'rgba(255,92,169,.5)', color: '#ffc4de' }}>{message.error}</div>}
      {message.success && <div className="card" style={{ marginTop: 14, borderColor: 'rgba(96,220,140,.5)', color: '#ccffd9' }}>{message.success}</div>}

      <div className="card" style={{ marginTop: 14, overflowX: 'auto' }}>
        <h3 className="h-section" style={{ marginBottom: 12 }}>Past redemptions</h3>
        {loading ? (
          <p style={{ margin: 0, color: 'var(--muted)' }}>Loading code history…</p>
        ) : !codes.length ? (
          <p style={{ margin: 0, color: 'var(--muted)' }}>No codes redeemed yet.</p>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 560 }}>
            <thead>
              <tr style={{ textAlign: 'left', color: 'var(--subtle)', fontSize: 12 }}>
                <th style={{ padding: '0 0 10px' }}>Code</th>
                <th style={{ padding: '0 0 10px' }}>Status</th>
                <th style={{ padding: '0 0 10px' }}>Reward</th>
                <th style={{ padding: '0 0 10px' }}>Redeemed</th>
              </tr>
            </thead>
            <tbody>
              {codes.map(function (entry) {
                return (
                  <tr key={entry.id} style={{ borderTop: '1px solid var(--hairline)' }}>
                    <td style={{ padding: '10px 0', fontWeight: 600 }}>{entry.code || '—'}</td>
                    <td style={{ padding: '10px 0', color: 'var(--muted)' }}>{entry.status || '—'}</td>
                    <td style={{ padding: '10px 0', color: 'var(--muted)' }}>{entry.reward || '—'}</td>
                    <td style={{ padding: '10px 0', color: 'var(--muted)' }}>{formatDate(entry.redeemedAt)}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { CodesPage });
