// screen-list.jsx — Post your action publicly (or to your stable).
// MARKETPLACE v2 — sits on top of the existing peer-to-peer swap product.

const { useState: lU, useEffect: lE, useMemo: lM } = React;

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

  const [handle, setHandle] = lU(window.pjGetHandle() || '');
  const [tournament, setTournament] = lU('');
  const [tournamentQuery, setTournamentQuery] = lU('');
  const [tournamentId, setTournamentId] = lU(null);
  const [showSuggest, setShowSuggest] = lU(false);
  const [buyIn, setBuyIn] = lU('');
  const [pct, setPct] = lU(10);
  const [markup, setMarkup] = lU(1.0);
  const [notes, setNotes] = lU('');
  const [visibility, setVisibility] = lU('public');
  const [submitting, setSubmitting] = lU(false);
  const [err, setErr] = lU(null);
  const [done, setDone] = lU(null);
  const [tournDb, setTournDb] = lU(window.WSOP_2026 || []);

  // Fetch tournaments from Supabase, fall back to bundled
  lE(() => {
    let cancelled = false;
    (async () => {
      try {
        const list = await window.pjListTournaments('wsop_2026');
        if (!cancelled && list && list.length > 0) setTournDb(list);
      } catch (_) { /* keep bundled */ }
    })();
    return () => { cancelled = true; };
  }, []);

  lE(() => {
    if (!tournamentQuery) return;
    const match = tournDb.find(t => t.name === tournamentQuery);
    if (match && !buyIn) setBuyIn(String(match.buyIn));
  }, [tournamentQuery, tournDb]);

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

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

  const submit = async () => {
    if (!canSubmit) return;
    setErr(null);
    setSubmitting(true);
    try {
      window.pjSetHandle(handle.trim());
      const listing = await window.pjCreateListing({
        player_handle: handle.trim(),
        tournament_name: tournament.trim(),
        tournament_id: tournamentId,
        buy_in: buyIn ? Number(buyIn) : null,
        pct_available: Number(pct),
        markup: Number(markup),
        notes: notes.trim(),
        visibility
      });
      setDone(listing);
    } catch (e) {
      setErr(e.message || String(e));
      setSubmitting(false);
    }
  };

  if (done) {
    return (
      <div className="page">
        <div style={{ maxWidth: 480, margin: '40px auto 0', textAlign: 'center' }}>
          <div className="mono" style={{
            fontSize: 11, letterSpacing: '0.18em', color: 'var(--green)',
            textTransform: 'uppercase', marginBottom: 12
          }}>◆ Listed</div>
          <h2 style={{
            fontFamily: 'var(--font-display)', fontSize: 36, fontWeight: 800,
            letterSpacing: '-0.025em', margin: '0 0 12px', color: 'var(--text)'
          }}>
            Your action is <span style={{ color: 'var(--green)', textShadow: '0 0 24px var(--green-glow)' }}>live</span>.
          </h2>
          <p style={{ color: 'var(--text-3)', fontSize: 15, marginBottom: 32 }}>
            {done.visibility === 'public'
              ? 'Backers can see it on the marketplace now.'
              : 'Sent to your stable only.'}
          </p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxWidth: 360, margin: '0 auto' }}>
            <button className="btn btn-primary btn-block btn-xl" onClick={() => onNav('/browse')}>
              View marketplace
            </button>
            <button className="btn btn-ghost btn-block" onClick={() => onNav('/p/' + encodeURIComponent(done.player_handle))}>
              My profile
            </button>
            <button className="btn btn-ghost btn-block" onClick={() => { setDone(null); setPct(10); setMarkup(1.0); setNotes(''); }}>
              List another
            </button>
          </div>
        </div>
      </div>
    );
  }

  const togglePill = (val, active, onClick, label, sub) => (
    <button
      type="button"
      onClick={onClick}
      style={{
        all: 'unset', cursor: 'pointer', flex: 1, textAlign: 'center',
        padding: '14px 16px', borderRadius: 12,
        background: active ? 'var(--green-soft)' : '#151A20',
        border: '1px solid ' + (active ? 'var(--green-line)' : 'rgba(255,255,255,0.06)'),
        boxShadow: active ? '0 0 18px var(--green-glow-2)' : 'none',
        transition: 'all 180ms ease'
      }}
    >
      <div style={{
        fontFamily: 'var(--font-display)', fontSize: 14, fontWeight: 700,
        color: active ? 'var(--green)' : 'var(--text)', letterSpacing: '-0.01em'
      }}>{label}</div>
      <div className="mono" style={{
        fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase',
        marginTop: 4, color: active ? 'var(--green)' : 'var(--text-3)'
      }}>{sub}</div>
    </button>
  );

  return (
    <div className="page">
      <div className="eyebrow" style={{ marginBottom: 8, color: 'var(--green)' }}>◆ Sell action</div>
      <h2 style={{
        fontFamily: 'var(--font-display)', fontSize: 40, fontWeight: 800,
        letterSpacing: '-0.025em', lineHeight: 1.02, margin: '0 0 8px', color: 'var(--text)'
      }}>List your action.</h2>
      <p style={{ color: 'var(--text-3)', marginBottom: 28, fontSize: 15 }}>
        Send to your stable, or put it up on the open marketplace.
      </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);
              setTournamentId(null);
              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(--bg-2)', border: '1px solid rgba(255,255,255,0.08)',
              borderRadius: 10, marginTop: 4,
              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 rgba(255,255,255,0.04)' }}
                >
                  <div style={{ fontSize: 14, color: 'var(--text)' }}>{s.name}</div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--text-3)', 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={`% of action for sale — ${pct}%`} help="How much of your action you're willing to sell.">
        <input type="range" min={1} max={100} value={pct} onChange={e => setPct(Number(e.target.value))} />
      </Field>

      <Field label={`Markup — ${Number(markup).toFixed(2)}x`} help="1.00 = flat. 1.20 = 20% premium 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="Notes (optional)" help="Rebuys included? Satellites count? Settlement method?">
        <textarea
          className="textarea"
          placeholder="Anything backers should know."
          value={notes}
          onChange={e => setNotes(e.target.value)}
          maxLength={500}
        />
      </Field>

      <Field label="Send it to">
        <div style={{ display: 'flex', gap: 10 }}>
          {togglePill('stable', visibility === 'stable', () => setVisibility('stable'), 'Your stable', 'Private')}
          {togglePill('public', visibility === 'public', () => setVisibility('public'), 'Marketplace', 'Public')}
        </div>
      </Field>

      {err && (
        <div className="card" style={{
          borderColor: 'rgba(255,77,94,0.5)', background: 'var(--red-soft)',
          marginBottom: 16, padding: 14, borderRadius: 10
        }}>
          <div className="mono" style={{ fontSize: 12, color: '#ff8a9c' }}>{err}</div>
        </div>
      )}

      <button
        className="btn btn-primary btn-block btn-xl"
        onClick={submit}
        disabled={!canSubmit}
      >
        {submitting ? 'Posting…' : (visibility === 'public' ? 'Post to marketplace' : 'Send to stable')}
      </button>

      <p className="help" style={{ marginTop: 14, textAlign: 'center', color: 'var(--text-3)', fontSize: 12 }}>
        Backers tap your listing → you both tap accept. Geo-stamped from each phone.
      </p>

      <Footer />
    </div>
  );
}

window.ListScreen = ListScreen;
