// Step 2 — Card history
function Step2({ history, setHistory, onNext, onBack }) {
  const [picking, setPicking] = useState(false);
  const [draft, setDraft] = useState({
    cardId: '',
    status: 'cancelled',
    cancelMonth: new Date().getMonth(),
    cancelYear: new Date().getFullYear() - 1,
  });

  const usedIds = new Set(history.map(h => h.cardId));
  const availableCards = window.CARD_DB.filter(c => !usedIds.has(c.id));

  function addDraft() {
    if (!draft.cardId) return;
    setHistory([...history, { ...draft, key: Date.now() + Math.random() }]);
    setPicking(false);
    setDraft({
      cardId: '',
      status: 'cancelled',
      cancelMonth: new Date().getMonth(),
      cancelYear: new Date().getFullYear() - 1,
    });
  }

  function removeItem(key) {
    setHistory(history.filter(h => h.key !== key));
  }

  const years = [];
  const currentYear = new Date().getFullYear();
  for (let y = currentYear; y >= currentYear - 6; y--) years.push(y);

  return (
    <div className="step-pane">
      <div className="step-header">
        <div className="step-eyebrow">Step two</div>
        <h1>Cards you've <span className="accent">already held.</span></h1>
        <p className="lede">
          Most issuers have a 12-month cooling-off — if you cancelled a card
          recently, you're blocked from its bonus. Tell us what's in your past
          and we'll route around it.
        </p>
      </div>

      {history.length === 0 && !picking && (
        <div className="history-empty">
          <p style={{ margin: 0 }}>
            No cards yet. Add what you've held in the last 12 months
            — or skip if you're starting fresh.
          </p>
        </div>
      )}

      <div className="history-list">
        {history.map(h => {
          const card = window.CARD_DB.find(c => c.id === h.cardId);
          if (!card) return null;
          const isHolding = h.status === 'holding';
          const cancelDate = !isHolding
            ? `${window.MONTHS[h.cancelMonth]} ${h.cancelYear}`
            : 'still holding';
          return (
            <div key={h.key} className="history-item">
              <IssuerSwatch issuer={card.issuer} />
              <div>
                <div className="hi-card">{card.name}</div>
                <div className="hi-meta">
                  <span className={'tag ' + (isHolding ? 'mint' : '')}>
                    {isHolding ? 'Currently holding' : 'Cancelled'}
                  </span>
                  &nbsp;&nbsp;{cancelDate}
                </div>
              </div>
              <button
                className="hi-remove"
                onClick={() => removeItem(h.key)}
                aria-label="Remove"
              >
                ×
              </button>
            </div>
          );
        })}
      </div>

      {picking ? (
        <div className="card-picker">
          <div className="picker-title">Add a card to your history</div>

          <div className="field" style={{ marginBottom: 16 }}>
            <label className="field-label" style={{ fontSize: '0.95rem' }}>
              Which card?
            </label>
            <select
              className="select"
              value={draft.cardId}
              onChange={(e) => setDraft({ ...draft, cardId: e.target.value })}
            >
              <option value="" disabled>Search the database…</option>
              {availableCards.map(c => (
                <option key={c.id} value={c.id}>
                  {c.name} — {c.currency}
                </option>
              ))}
            </select>
          </div>

          <div className="field" style={{ marginBottom: 16 }}>
            <label className="field-label" style={{ fontSize: '0.95rem' }}>
              Status
            </label>
            <div className="status-toggle">
              <button
                className={draft.status === 'holding' ? 'active' : ''}
                onClick={() => setDraft({ ...draft, status: 'holding' })}
              >
                Currently holding
              </button>
              <button
                className={draft.status === 'cancelled' ? 'active' : ''}
                onClick={() => setDraft({ ...draft, status: 'cancelled' })}
              >
                Cancelled
              </button>
            </div>
          </div>

          {draft.status === 'cancelled' && (
            <div className="row2">
              <div className="field" style={{ marginBottom: 0 }}>
                <label className="field-label" style={{ fontSize: '0.95rem' }}>
                  Cancellation month
                </label>
                <select
                  className="select"
                  value={draft.cancelMonth}
                  onChange={(e) => setDraft({ ...draft, cancelMonth: parseInt(e.target.value, 10) })}
                >
                  {window.MONTHS.map((m, i) => (
                    <option key={m} value={i}>{m}</option>
                  ))}
                </select>
              </div>
              <div className="field" style={{ marginBottom: 0 }}>
                <label className="field-label" style={{ fontSize: '0.95rem' }}>
                  Year
                </label>
                <select
                  className="select"
                  value={draft.cancelYear}
                  onChange={(e) => setDraft({ ...draft, cancelYear: parseInt(e.target.value, 10) })}
                >
                  {years.map(y => (
                    <option key={y} value={y}>{y}</option>
                  ))}
                </select>
              </div>
            </div>
          )}

          <div className="picker-actions">
            <button className="btn btn-ghost" onClick={() => setPicking(false)}>
              Cancel
            </button>
            <button
              className="btn btn-primary"
              onClick={addDraft}
              disabled={!draft.cardId}
            >
              Add to history
            </button>
          </div>
        </div>
      ) : (
        availableCards.length > 0 && (
          <button className="add-card-btn" onClick={() => setPicking(true)}>
            + Add a card you've held
          </button>
        )
      )}

      <div className="btn-row">
        <button className="btn btn-ghost" onClick={onBack}>← Back</button>
        <button className="btn btn-primary" onClick={onNext}>
          {history.length === 0 ? 'Skip — I have no history' : 'See my strategy →'}
        </button>
      </div>
    </div>
  );
}

window.Step2 = Step2;
