// StatsImportSection.jsx — paste a KCBS results block, map to an event, save.
//
// Parser accepts a loose per-meat block. Each meat line is:
//   "<Meat>  <Place>  <Score>  [<extra cols ignored>]"
// Place is a bare integer or "11th" etc. Score is a decimal like 168.4000.
// Blank lines, header lines (e.g. "Category Place Score"), and unknown meats are ignored.

const MEATS = ['chicken', 'ribs', 'pork', 'brisket'];

function parseKcbs(raw) {
  if (!raw) return { results: {}, overall: null, warnings: ['Empty input.'] };
  const results = {};
  const warnings = [];
  let overall = null;

  const lines = raw.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
  lines.forEach(line => {
    const lower = line.toLowerCase();
    // Try a simple "Meat  Place  Score" row. Tolerate tabs, multiple spaces.
    const tokens = line.split(/\s{2,}|\t+|\s+/).filter(Boolean);
    if (tokens.length < 3) return;
    const meatTok = tokens[0].toLowerCase();
    const meat = MEATS.find(m => meatTok.startsWith(m));
    // Overall row: "Overall 7 672.4000  33"
    if (!meat && (meatTok === 'overall' || meatTok === 'total' || meatTok === 'gc')) {
      const place = String(tokens[1] || '').replace(/\D+$/, '');
      const score = (tokens[2] || '').match(/\d+\.?\d*/);
      overall = {
        place: place || '',
        score: score ? score[0] : '',
        teams: tokens[3] ? String(tokens[3]).replace(/\D+$/, '') : '',
      };
      return;
    }
    if (!meat) return;
    const place = String(tokens[1] || '').replace(/\D+$/, '');
    const scoreMatch = (tokens[2] || '').match(/\d+\.?\d*/);
    if (!place || !scoreMatch) {
      warnings.push(`Could not parse ${meat} line: "${line}"`);
      return;
    }
    results[meat] = { place, score: scoreMatch[0] };
  });

  return { results, overall, warnings };
}
window.__parseKcbs = parseKcbs;

const StatsImportSection = ({ onBanner }) => {
  const eventsStore = useEventsStore();
  const [text, setText] = useState('');
  const [eventId, setEventId] = useState('');
  const [saving, setSaving] = useState(false);

  const eligible = eventsStore.events.filter(e => !e.done || (e.done && !e.place));
  const parsed = parseKcbs(text);

  const apply = async () => {
    const ev = eventsStore.events.find(e => e.id === eventId);
    if (!ev) { onBanner({ kind: 'err', msg: 'Pick an event first.' }); return; }
    if (!Object.keys(parsed.results).length && !parsed.overall) {
      onBanner({ kind: 'err', msg: 'Nothing to save — parser found no meats.' });
      return;
    }
    const next = {
      ...ev,
      done: true,
      status: 'DONE',
      results: { ...(ev.results || {}), ...parsed.results },
    };
    if (parsed.overall) {
      if (parsed.overall.place)  next.place = parsed.overall.place;
      if (parsed.overall.score)  next.score = parsed.overall.score;
      if (parsed.overall.teams)  next.teams = parsed.overall.teams;
    }
    setSaving(true);
    try {
      await window.EventsStore.update(next);
      onBanner({ kind: 'ok', msg: `Updated "${ev.name}". See ${Object.keys(parsed.results).length} meats.` });
      setText('');
    } catch (e) {
      onBanner({ kind: 'err', msg: String(e.message || e) });
    } finally {
      setSaving(false);
    }
  };

  return (
    <>
      <PageHero eyebrow="Admin · Stats Import" title={<>Paste <span style={{ color: 'var(--wbbq-flame)' }}>Results.</span></>} subtitle="Dump the KCBS lines in. Pick the event. Save." mascot="flame.svg" />
      <div style={{ marginTop: 28 }}>
        {!eventsStore.connected && (
          <div style={{ padding: 16, background: 'var(--wbbq-ink)', border: '2px dashed var(--wbbq-flame)', color: 'var(--fg2)', marginBottom: 20 }}>
            Events backend not connected — results will only apply in memory. Go to the Events tab to connect first.
          </div>
        )}

        <div style={{ marginBottom: 20 }}>
          <AdminLabel>Pick an event</AdminLabel>
          <select value={eventId} onChange={(e) => setEventId(e.target.value)} style={editorInputStyle()}>
            <option value="">— select event —</option>
            {eligible.map(e => (
              <option key={e.id} value={e.id}>{e.date} {e.year} · {e.name}</option>
            ))}
          </select>
        </div>

        <AdminLabel>Paste KCBS block</AdminLabel>
        <textarea
          rows={10}
          value={text}
          onChange={(e) => setText(e.target.value)}
          placeholder={'Chicken   12   168.4000\nRibs       5   170.8000\nPork       9   166.2000\nBrisket    3   167.0000\nOverall    7   672.4000   33'}
          style={{ ...editorInputStyle(), fontFamily: 'var(--font-mono)', fontSize: 13 }}
        />

        <div style={{ marginTop: 16, padding: 16, background: 'var(--wbbq-black)', border: '2px solid var(--border)' }}>
          <div className="eyebrow" style={{ color: 'var(--wbbq-slime)' }}>◉ Preview</div>
          {parsed.warnings.length > 0 && parsed.warnings.map((w, i) => (
            <div key={i} style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--wbbq-flame)', marginTop: 6 }}>⚠ {w}</div>
          ))}
          {parsed.overall && (
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--fg1)', marginTop: 10 }}>
              overall: place {parsed.overall.place} · score {parsed.overall.score} · teams {parsed.overall.teams || '—'}
            </div>
          )}
          {MEATS.map(meat => {
            const r = parsed.results[meat];
            return (
              <div key={meat} style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: r ? 'var(--fg1)' : 'var(--fg3)', marginTop: 4 }}>
                {meat}: {r ? `place ${r.place} · score ${r.score}` : '—'}
              </div>
            );
          })}
        </div>

        <div style={{ display: 'flex', gap: 10, marginTop: 20, flexWrap: 'wrap' }}>
          <button onClick={apply} disabled={!eventId || saving} className="btn btn-primary" style={{ fontSize: 13, opacity: (eventId && !saving) ? 1 : 0.4 }}>
            {saving ? 'Saving…' : 'Apply to event →'}
          </button>
          <button onClick={() => setText('')} className="btn btn-ghost" style={{ fontSize: 13 }}>Clear</button>
        </div>
      </div>
    </>
  );
};
window.StatsImportSection = StatsImportSection;
