// screen-new.jsx — Create swap form.

const { useState: nU, useEffect: nE, useMemo: nM, useRef: nR } = React;

function NewSwapScreen({ onNav, prefillTournament }) {
  const { Field, Chip, Footer } = window.PJ_UI;

  const [handle, setHandle] = nU(window.pjGetHandle() || '');
  const [tournament, setTournament] = nU(prefillTournament || '');
  const [tournamentQuery, setTournamentQuery] = nU(prefillTournament || '');
  const [showSuggest, setShowSuggest] = nU(false);
  const [buyIn, setBuyIn] = nU('');
  const [yourPct, setYourPct] = nU(10);
  const [theirPct, setTheirPct] = nU(10);
  const [markup, setMarkup] = nU(1.0);
  const [terms, setTerms] = nU([]);
  const [notes, setNotes] = nU('');
  const [submitting, setSubmitting] = nU(false);
  const [err, setErr] = nU(null);

  // Prefill buy-in if tournament matches
  nE(() => {
    if (!tournamentQuery) return;
    const match = (window.WSOP_2026 || []).find(t => t.name === tournamentQuery);
    if (match && !buyIn) setBuyIn(String(match.buyIn));
  }, [tournamentQuery]);

  const suggestions = nM(() => {
    if (!tournamentQuery || tournamentQuery.length < 1) return [];
    const q = tournamentQuery.toLowerCase();
    return (window.WSOP_2026 || []).filter(t =>
      t.name.toLowerCase().includes(q) || String(t.buyIn).includes(q)
    ).slice(0, 6);
  }, [tournamentQuery]);

  const toggleTerm = (id) => {
    setTerms(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  };

  const canSubmit = handle.trim() && tournament.trim() && Number(buyIn) > 0 && !submitting;

  const submit = async () => {
    if (!canSubmit) return;
    setErr(null);
    setSubmitting(true);
    try {
      window.pjSetHandle(handle.trim());
      const swap = await window.pjCreateSwap({
        tournament_name: tournament.trim(),
        buy_in: Number(buyIn),
        originator_handle: handle.trim(),
        originator_pct: Number(yourPct),
        acceptor_pct: Number(theirPct),
        markup: Number(markup),
        terms,
        notes: notes.trim()
      });
      onNav(`/s/${swap.id}?role=originator&token=${swap.secret_token}`);
    } catch (e) {
      setErr(e.message || String(e));
      setSubmitting(false);
    }
  };

  return (
    <div className="page">
      <div className="eyebrow gold" style={{ marginBottom: 8 }}>◆ New swap</div>
      <h2 className="serif" style={{ fontSize: 40, lineHeight: 1, marginBottom: 6 }}>Set the terms.</h2>
      <p className="paper" style={{ marginBottom: 28 }}>Fill it once. Hand them the QR. Done.</p>

      <Field label="Your handle">
        <input
          className="input"
          placeholder="e.g. nutsoffour"
          value={handle}
          onChange={e => setHandle(e.target.value)}
          maxLength={32}
          autoCapitalize="off"
          autoCorrect="off"
          spellCheck={false}
        />
      </Field>

      <Field label="Tournament" help="Pick a WSOP 2026 event or type any tournament name.">
        <div style={{ position: 'relative' }}>
          <input
            className="input"
            placeholder="WSOP Main Event, $1,500 NLH, etc."
            value={tournamentQuery}
            onChange={e => { setTournamentQuery(e.target.value); setTournament(e.target.value); setShowSuggest(true); }}
            onFocus={() => setShowSuggest(true)}
            onBlur={() => setTimeout(() => setShowSuggest(false), 180)}
          />
          {showSuggest && suggestions.length > 0 && (
            <div style={{
              position: 'absolute', top: '100%', left: 0, right: 0,
              background: 'var(--felt-3)', border: '1px solid var(--line-gold)',
              maxHeight: 240, overflowY: 'auto', zIndex: 10
            }}>
              {suggestions.map(s => (
                <div
                  key={s.id}
                  onMouseDown={() => { setTournament(s.name); setTournamentQuery(s.name); setBuyIn(String(s.buyIn)); setShowSuggest(false); }}
                  style={{ padding: '10px 14px', cursor: 'pointer', borderBottom: '1px solid var(--line)' }}
                >
                  <div style={{ fontSize: 14, color: 'var(--ivory)' }}>{s.name}</div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--muted)', letterSpacing: '0.06em', marginTop: 2 }}>
                    {s.venue.toUpperCase()} · ${s.buyIn.toLocaleString()}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </Field>

      <Field label="Buy-in (USD)">
        <input
          className="input num"
          type="number"
          inputMode="numeric"
          placeholder="10000"
          value={buyIn}
          onChange={e => setBuyIn(e.target.value.replace(/[^0-9.]/g, ''))}
        />
      </Field>

      <Field label={`Your % offered — ${yourPct}%`} help="What you give them.">
        <input type="range" min={1} max={50} value={yourPct} onChange={e => setYourPct(Number(e.target.value))} />
      </Field>

      <Field label={`Their % offered — ${theirPct}%`} help="What you get back from them.">
        <input type="range" min={1} max={50} value={theirPct} onChange={e => setTheirPct(Number(e.target.value))} />
      </Field>

      <Field label={`Markup — ${Number(markup).toFixed(2)}x`} help="1.0 = flat. 1.2 = 20% over face.">
        <input type="range" min={1.0} max={2.0} step={0.05} value={markup} onChange={e => setMarkup(Number(e.target.value))} />
      </Field>

      <Field label="Terms" help="Tap to toggle.">
        <div className="row" style={{ flexWrap: 'wrap', gap: 8 }}>
          {(window.SWAP_TERMS || []).map(t => (
            <Chip key={t.id} on={terms.includes(t.id)} onClick={() => toggleTerm(t.id)}>
              {t.label}
            </Chip>
          ))}
        </div>
      </Field>

      <Field label="Notes (optional)">
        <textarea
          className="textarea"
          placeholder="Any other conditions, settlement method, Venmo handle, etc."
          value={notes}
          onChange={e => setNotes(e.target.value)}
          maxLength={500}
        />
      </Field>

      {err && (
        <div className="card" style={{ borderColor: 'rgba(231,76,60,0.5)', background: 'var(--red-tint)', marginBottom: 16 }}>
          <div className="mono" style={{ fontSize: 12, color: 'var(--red-bright)' }}>{err}</div>
        </div>
      )}

      <button
        className="btn btn-gold btn-block btn-xl"
        onClick={submit}
        disabled={!canSubmit}
      >
        {submitting ? 'Generating…' : 'Generate Lock QR'}
      </button>

      <p className="help" style={{ marginTop: 14, textAlign: 'center' }}>
        Nothing is final until they scan and you both sign.
      </p>

      <Footer />
    </div>
  );
}

window.NewSwapScreen = NewSwapScreen;
