// Dashboard tab — stats overview, ticker hero, Teach-me CTA.
const { useState: useStateD, useMemo: useMemoD } = React;

function StatBlock({ label, value, sub, accent }) {
  return (
    <div className="stat-block">
      <div className="stat-label eyebrow"><span className="rule"></span>{label}</div>
      <div className={`stat-value serif ${accent ? 'accent' : ''}`}>{value}</div>
      {sub ? <div className="stat-sub">{sub}</div> : null}
    </div>
  );
}

function ConfBar({ entries }) {
  const counts = CONF_ORDER.map(c => ({
    conf: c,
    n: (entries || []).filter(e => e.confidence === c).length,
  }));
  return (
    <div className="confbar">
      <div className="confbar-track">
        {counts.map(c => (
          c.n > 0 ? (
            <div
              key={c.conf}
              className={`confbar-seg conf-${c.conf}`}
              style={{ flex: c.n }}
              title={`${c.conf}: ${c.n}`}
            />
          ) : null
        ))}
      </div>
      <div className="confbar-legend">
        {counts.filter(c => c.n > 0).map(c => (
          <span key={c.conf} className="confbar-legend-item">
            <span className={`confbar-dot conf-${c.conf}`}></span>
            <span className="mono" style={{ fontSize: 11, color: 'var(--fg-mute)' }}>{c.conf}</span>
            <span className="mono tnum" style={{ fontSize: 11, color: 'var(--paper)' }}>{c.n}</span>
          </span>
        ))}
      </div>
    </div>
  );
}

function pickWordOfMoment(entries) {
  const good = (entries || []).filter(e => e.confidence === 'confirmed' || e.confidence === 'high');
  if (good.length === 0) return (entries || [])[0] || null;
  const day = Math.floor(Date.now() / 86400000);
  return good[day % good.length];
}

function DashboardView({ data, onGoTeach, onGoDictionary }) {
  const m = data.meta || {};
  const wotm = useMemoD(() => pickWordOfMoment(data.entries), [data.entries]);

  const irregularCount = useMemoD(() => {
    return Object.values(data.conjugations || {}).filter(
      c => c.notes && c.notes.toLowerCase().includes('irregular')
    ).length;
  }, [data.conjugations]);

  const exForWotm = useMemoD(() => {
    if (!wotm) return null;
    const matches = (data.example_sentences || []).filter(
      s => s.conlang && s.conlang.toLowerCase().includes(wotm.word.toLowerCase())
    );
    if (!matches.length) return null;
    matches.sort((a, b) => {
      const ca = CONF_ORDER.indexOf(b.confidence) - CONF_ORDER.indexOf(a.confidence);
      if (ca !== 0) return ca;
      return new Date(b.timestamp || 0).getTime() - new Date(a.timestamp || 0).getTime();
    });
    return matches[0];
  }, [wotm, data.example_sentences]);

  return (
    <div className="dash-grid">
      <section className="dash-hero panel">
        <div className="eyebrow"><span className="rule"></span>From the editors</div>
        <h2 className="serif dash-hero-title">
          A field guide to a language being invented in&nbsp;real&nbsp;time, mostly after midnight.
        </h2>
        <p className="dash-hero-lede">
          Seamenese is what happens when friends in a Discord channel start coining words faster than they can
          remember them. This dictionary is the bot's best attempt to keep up. Entries are tagged with confidence
          because at least some of the words below are probably made up.
        </p>
        <div className="dash-hero-actions">
          <button className="btn btn-primary" onClick={onGoDictionary}>
            Browse {(data.entries || []).length} entries →
          </button>
          <span className="hand" style={{ fontSize: 20, color: 'var(--accent-warm)', transform: 'rotate(-3deg)', display: 'inline-block', marginLeft: 8 }}>
            half of these are jorn's fault
          </span>
        </div>
      </section>

      <section className="teach-cta" onClick={onGoTeach}>
        <div className="teach-cta-bg" aria-hidden="true">
          <span className="teach-cta-glyph serif">¿</span>
        </div>
        <div className="teach-cta-inner">
          <div className="eyebrow" style={{ color: 'var(--paper-mute)' }}><span className="rule" style={{ background: 'var(--paper-mute)' }}></span>Teach me</div>
          <h3 className="serif teach-cta-title">Teach me to say something.</h3>
          <p className="teach-cta-lede">
            Type an English sentence. Get a step-by-step Seamenese translation: word choices, grammar applied,
            conjugations used, and exactly which parts we made up.
          </p>
          <div className="teach-cta-row">
            <span className="teach-cta-input mono">"How do I say <em>I love your friend</em>?"</span>
            <span className="teach-cta-arrow">→</span>
          </div>
          <span className="hand teach-cta-margin">try it →</span>
        </div>
      </section>

      <section className="dash-stats panel">
        <div className="stats-grid">
          <StatBlock label="Total entries" value={(data.entries || []).length} sub={`${(data.entries || []).filter(e => e.confidence === 'confirmed').length} confirmed`} />
          <StatBlock label="Grammar rules" value={(data.grammar_rules || []).length} sub="ordered by confidence" />
          <StatBlock label="Conjugations" value={Object.keys(data.conjugations || {}).length} sub={`${irregularCount} irregular`} />
          <StatBlock label="Examples" value={(data.example_sentences || []).length} sub="parallel sentences" />
          <StatBlock label="Schema" value={`v${m.schema_version || 1}`} sub={`auto-sync ${m.auto_sync_enabled ? 'on' : 'off'}`} accent />
        </div>
        <div className="confbar-wrap">
          <div className="eyebrow" style={{ marginBottom: 10 }}><span className="rule"></span>Confidence distribution</div>
          <ConfBar entries={data.entries} />
        </div>
      </section>

      <section className="dash-recent panel">
        <div className="eyebrow"><span className="rule"></span>The wire · recent</div>
        <h3 className="serif dash-recent-title">Recently in the channel</h3>
        <ul className="recent-list">
          {(data.ticker || []).slice(0, 6).map((it, i) => (
            <li key={i} className="recent-row">
              <span className={`recent-glyph kind-${it.kind}`}>{TICKER_GLYPH[it.kind] || '·'}</span>
              <span className="mono recent-word">{it.word}</span>
              <span className="recent-note">{it.note}</span>
              <span className="mono tnum recent-time">{relTime(it.ts)}</span>
            </li>
          ))}
          {(!data.ticker || data.ticker.length === 0) && (
            <li className="recent-row">
              <span className="recent-note" style={{ gridColumn: '1 / -1' }}>No recent activity yet.</span>
            </li>
          )}
        </ul>
      </section>

      <section className="dash-wotm panel">
        <div className="eyebrow"><span className="rule"></span>Word of the moment</div>
        {wotm ? (
          <>
            <div className="wotm-word mono serif">{wotm.word}</div>
            <div className="wotm-pron mono">{wotm.pronunciation || ''} · {wotm.category}</div>
            <p className="wotm-def">{wotm.meaning}</p>
            {exForWotm && (
              <div className="wotm-ex">
                <div className="wotm-ex-conlang mono">{exForWotm.conlang}</div>
                <div className="wotm-ex-en">"{exForWotm.english}"</div>
              </div>
            )}
            <span className={confChipClass(wotm.confidence)}>{wotm.confidence}</span>
          </>
        ) : (
          <p className="wotm-def">No entries yet.</p>
        )}
      </section>
    </div>
  );
}

Object.assign(window, { DashboardView });
