// Promo code input — collapsible "Got a discount code?" with live validation
// Posts to /api/validate-promo to check Stripe Promotion Codes
// On success, calls onApply({code, discountAmount, ...})

const { useState: usePromoState } = React;

function PromoInput({ totalAmount, onApply, applied, onClear }) {
  const [expanded, setExpanded] = usePromoState(false);
  const [code, setCode] = usePromoState('');
  const [status, setStatus] = usePromoState('idle'); // idle | validating | error
  const [error, setError] = usePromoState(null);

  const validate = async () => {
    const trimmed = code.trim();
    if (!trimmed) return;
    setStatus('validating');
    setError(null);
    try {
      const res = await fetch('/api/validate-promo', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ code: trimmed, totalAmount }),
      });
      const data = await res.json();
      if (data.valid) {
        onApply(data);
        setStatus('idle');
        setCode('');
      } else {
        setError(data.error || "Sorry, that code isn't valid.");
        setStatus('error');
      }
    } catch (e) {
      setError('Could not validate right now. Try again?');
      setStatus('error');
    }
  };

  const clear = () => {
    onClear();
    setCode('');
    setStatus('idle');
    setError(null);
    setExpanded(false);
  };

  // ── Applied state ──
  if (applied) {
    return (
      <div className="promo-applied" role="status">
        <span className="promo-applied-check" aria-hidden="true">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="20 6 9 17 4 12"/>
          </svg>
        </span>
        <span className="promo-applied-text">
          <strong>{applied.code}</strong> applied — you save ${applied.discountAmount}
        </span>
        <button type="button" onClick={clear} className="promo-remove" aria-label="Remove discount code">
          Remove
        </button>
      </div>
    );
  }

  // ── Collapsed state ──
  if (!expanded) {
    return (
      <button type="button" className="promo-toggle" onClick={() => setExpanded(true)}>
        + Got a discount code?
      </button>
    );
  }

  // ── Expanded entry state ──
  return (
    <div className="promo-input-wrap">
      <div className="promo-input-row">
        <input
          type="text"
          value={code}
          onChange={(e) => {
            setCode(e.target.value.toUpperCase().replace(/[^A-Z0-9_-]/g, ''));
            if (status === 'error') { setStatus('idle'); setError(null); }
          }}
          onKeyDown={(e) => {
            if (e.key === 'Enter') { e.preventDefault(); validate(); }
            if (e.key === 'Escape') { setExpanded(false); setCode(''); setStatus('idle'); setError(null); }
          }}
          placeholder="ENTER CODE"
          className={'promo-input' + (status === 'error' ? ' error' : '')}
          disabled={status === 'validating'}
          aria-label="Discount code"
          autoFocus
        />
        <button
          type="button"
          onClick={validate}
          className="promo-apply"
          disabled={status === 'validating' || !code.trim()}
        >
          {status === 'validating' ? '…' : 'Apply'}
        </button>
      </div>
      {status === 'error' && error && (
        <div className="promo-error" role="alert">{error}</div>
      )}
    </div>
  );
}

Object.assign(window, { PromoInput });
