/* global React, useApi, useMeta, useAuth, Loading, ApiError, Tag, formatMoney */

// =========================================================================
// SUGGEST — community suggestions for new models to add to the predictor,
// or new markets we should be tracking. Anonymous submissions allowed;
// authenticated users get their handle attached. Each suggestion can be
// upvoted once per IP. Newest / Top sort tabs.
// =========================================================================
function SuggestPage({ navigate }) {
  const [kindTab, setKindTab] = React.useState('model'); // 'model' | 'market'
  const [sort, setSort] = React.useState('top');         // 'top' | 'recent'

  const list = useApi(
    () => window.CloudLayerAPI.listSuggestions({ kind: kindTab, sort, limit: 80 }),
    [kindTab, sort],
  );

  return (
    <div data-screen-label="08 Suggest">
      <div className="page-head">
        <div className="container">
          <div className="crumb">
            <span style={{ cursor: 'pointer' }} onClick={() => navigate('home')}>Benchmark</span>
            <span style={{ margin: '0 8px' }}>/</span>
            <span>Suggest</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 32 }}>
            <h1 style={{ flex: 1, margin: 0, fontSize: 64, fontFamily: 'var(--ff-display)', fontWeight: 300, letterSpacing: '-0.025em' }}>
              Suggest a <em style={{ fontStyle: 'italic', color: 'var(--accent)' }}>model</em> or <em style={{ fontStyle: 'italic', color: 'var(--accent)' }}>market</em>
            </h1>
          </div>
          <div className="dim" style={{ marginTop: 16, fontSize: 15, lineHeight: 1.55, maxWidth: 720 }}>
            Think a model should be on the leaderboard? A market we're not tracking? Drop it here. We'll review and ship the ones that get traction.
          </div>
        </div>
      </div>

      <section className="container" style={{ padding: '40px 32px 0' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '420px minmax(0,1fr)', gap: 48, alignItems: 'start' }}>
          {/* Form on the left */}
          <SuggestionForm
            defaultKind={kindTab}
            onSubmitted={() => { list.refresh(); }}
          />

          {/* Feed on the right */}
          <div>
            <div className="tabs">
              <button className={`tab ${kindTab === 'model' ? 'active' : ''}`} onClick={() => setKindTab('model')}>
                Models
              </button>
              <button className={`tab ${kindTab === 'market' ? 'active' : ''}`} onClick={() => setKindTab('market')}>
                Markets
              </button>
              <div style={{ marginLeft: 'auto', display: 'flex', gap: 4, padding: '6px 0' }}>
                <button className={`fchip ${sort === 'top' ? 'active' : ''}`} onClick={() => setSort('top')}>Top</button>
                <button className={`fchip ${sort === 'recent' ? 'active' : ''}`} onClick={() => setSort('recent')}>Recent</button>
              </div>
            </div>

            {list.error
              ? <ApiError error={list.error} />
              : list.loading && !list.data
              ? <Loading label="Loading suggestions…" />
              : (list.data?.items || []).length === 0
                ? <div className="panel" style={{ padding: 28, textAlign: 'center' }}>
                    <div className="dim">No {kindTab} suggestions yet. Be the first.</div>
                  </div>
                : <div className="col gap-12">
                    {(list.data.items).map((s) => (
                      <SuggestionRow key={s._id} s={s} onUpvote={(newCount) => {
                        // optimistic — bump the local count without a full refetch
                        s.upvotes = newCount;
                        list.refresh();
                      }} />
                    ))}
                  </div>}
          </div>
        </div>
      </section>
      <div style={{ height: 96 }} />
    </div>
  );
}

// =========================================================================
// SuggestionForm — anonymous or auth'd.
// =========================================================================
function SuggestionForm({ defaultKind, onSubmitted }) {
  const { user, signedIn } = useAuth();
  const [kind, setKind] = React.useState(defaultKind);
  const [title, setTitle] = React.useState('');
  const [body, setBody] = React.useState('');
  const [metaUrl, setMetaUrl] = React.useState('');
  const [submitterName, setSubmitterName] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const [ok, setOk] = React.useState(false);

  // Re-sync if the parent flips the tab.
  React.useEffect(() => { setKind(defaultKind); }, [defaultKind]);

  async function submit(e) {
    e.preventDefault();
    setSubmitting(true); setErr(null); setOk(false);
    try {
      await window.CloudLayerAPI.createSuggestion({
        kind,
        title: title.trim(),
        body: body.trim(),
        meta: metaUrl.trim() ? { url: metaUrl.trim() } : {},
        submitterName: signedIn ? '' : submitterName.trim(),
      });
      setOk(true);
      setTitle(''); setBody(''); setMetaUrl('');
      onSubmitted && onSubmitted();
    } catch (e) {
      setErr(e);
    } finally {
      setSubmitting(false);
    }
  }

  const titlePlaceholder = kind === 'model'
    ? 'e.g. Mistral Large 2'
    : 'e.g. Will the Fed cut rates 50bp in June?';
  const bodyPlaceholder = kind === 'model'
    ? 'Why this model is worth adding — provider, intended strength, anything we should know.'
    : 'Why this market matters — where you saw it, why it would be interesting to forecast.';
  const urlPlaceholder = kind === 'model'
    ? 'Optional link (model card, docs, blog post)'
    : 'Optional Polymarket / Kalshi / source URL';

  return (
    <form className="panel" onSubmit={submit}>
      <div className="panel-header">
        <h3>New suggestion</h3>
        {signedIn
          ? <span className="mono faint" style={{ fontSize: 11 }}>as @{user.handle}</span>
          : <span className="mono faint" style={{ fontSize: 11 }}>anonymous</span>}
      </div>
      <div className="panel-body" style={{ display: 'grid', gap: 14 }}>
        <div className="filter-row">
          <button type="button" className={`fchip ${kind === 'model' ? 'active' : ''}`} onClick={() => setKind('model')}>Model</button>
          <button type="button" className={`fchip ${kind === 'market' ? 'active' : ''}`} onClick={() => setKind('market')}>Market</button>
        </div>

        <div className="field">
          <label>{kind === 'model' ? 'Model name' : 'Market question'}</label>
          <input
            type="text"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            placeholder={titlePlaceholder}
            maxLength={200}
            required
          />
        </div>

        <div className="field">
          <label>Why</label>
          <textarea
            value={body}
            onChange={(e) => setBody(e.target.value)}
            placeholder={bodyPlaceholder}
            rows={4}
            maxLength={2000}
            style={{ minHeight: 100 }}
          />
          <div className="help"><span className="mono faint">{body.length}/2000</span></div>
        </div>

        <div className="field">
          <label>Link (optional)</label>
          <input
            type="text"
            value={metaUrl}
            onChange={(e) => setMetaUrl(e.target.value)}
            placeholder={urlPlaceholder}
            maxLength={500}
          />
        </div>

        {!signedIn && (
          <div className="field">
            <label>Your name (optional)</label>
            <input
              type="text"
              value={submitterName}
              onChange={(e) => setSubmitterName(e.target.value)}
              placeholder="Anonymous"
              maxLength={80}
            />
            <div className="help">Sign in to claim your suggestion under your handle.</div>
          </div>
        )}

        {err && <ApiError error={err} />}
        {ok && (
          <div className="mono pos" style={{ fontSize: 12 }}>
            Submitted. Thanks — it's in the queue.
          </div>
        )}

        <button className="btn btn-accent" type="submit" disabled={submitting || !title.trim()}>
          {submitting ? 'Submitting…' : 'Submit suggestion →'}
        </button>
      </div>
    </form>
  );
}

// =========================================================================
// SuggestionRow — one suggestion line with upvote.
// =========================================================================
function SuggestionRow({ s, onUpvote }) {
  const [voting, setVoting] = React.useState(false);
  const [voted, setVoted] = React.useState(false);
  const [err, setErr] = React.useState(null);

  async function upvote() {
    setVoting(true); setErr(null);
    try {
      const r = await window.CloudLayerAPI.upvoteSuggestion(s._id);
      setVoted(true);
      onUpvote && onUpvote(r.upvotes);
    } catch (e) {
      // 409 = already voted from this IP; still a "vote acknowledged" signal
      if (e.status === 409) setVoted(true);
      else setErr(e);
    } finally {
      setVoting(false);
    }
  }

  const statusColor = {
    pending:   'var(--fg-faint)',
    reviewing: 'var(--blue)',
    accepted:  'var(--pos)',
    rejected:  'var(--neg)',
  }[s.status] || 'var(--fg-faint)';

  return (
    <div className="panel" style={{ display: 'grid', gridTemplateColumns: '70px minmax(0,1fr)', gap: 16, padding: '14px 18px', alignItems: 'start' }}>
      {/* Upvote pillar */}
      <button
        type="button"
        onClick={upvote}
        disabled={voting || voted}
        className="btn"
        style={{
          display: 'flex', flexDirection: 'column', alignItems: 'center',
          gap: 2, padding: '8px 0',
          background: voted ? 'var(--accent-soft)' : 'transparent',
          borderColor: voted ? 'rgba(212,174,90,0.4)' : undefined,
          color: voted ? 'var(--accent)' : 'var(--fg)',
        }}
        title={voted ? 'Voted' : 'Upvote'}
      >
        <span style={{ fontSize: 14, lineHeight: 1 }}>{voted ? '★' : '▲'}</span>
        <span className="mono tnum" style={{ fontSize: 13 }}>{s.upvotes || 0}</span>
      </button>

      {/* Body */}
      <div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, flexWrap: 'wrap' }}>
          <span style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 400, color: 'var(--fg)' }}>
            {s.title}
          </span>
          <span className="mono faint" style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em', color: statusColor }}>
            {s.status}
          </span>
        </div>
        {s.body && (
          <div className="dim" style={{ fontSize: 13, lineHeight: 1.5, marginTop: 6, whiteSpace: 'pre-wrap' }}>
            {s.body}
          </div>
        )}
        <div className="row gap-12" style={{ marginTop: 8, flexWrap: 'wrap' }}>
          <span className="mono faint" style={{ fontSize: 11 }}>
            {s.submitterName || '@anonymous'} · {new Date(s.createdAt).toLocaleDateString()}
          </span>
          {s.meta?.url && (
            <a href={s.meta.url} target="_blank" rel="noopener noreferrer"
               className="mono" style={{ fontSize: 11, color: 'var(--accent)' }}>
              link ↗
            </a>
          )}
          {err && <span className="mono neg" style={{ fontSize: 11 }}>{err.message}</span>}
        </div>
      </div>
    </div>
  );
}

window.SuggestPage = SuggestPage;
