// ResearchView — a blog where the research is explained in post form.
// List of posts -> click into a full post. Posts live in data.blog.
const RV = window.WINTELAcademicDesignSystem_045d4f;

// Newest publication year for a topic tag (used to date posts that cite a body of work).
function newestYearForTopic(topic) {
  const P = window.WINTEL_PUBLICATIONS;
  if (!P || !window.topicsFor) return null;
  const all = [...(P.inPress || []), ...(P.articles || []), ...(P.proceedings || []), ...(P.bookChapters || [])];
  const years = all.filter((p) => window.topicsFor(p).some((t) => t.label === topic)).map((p) => Number(p.y || 0));
  return years.length ? Math.max(...years) : null;
}

// Display date for a post — newest cited-reference year when it tracks a topic, else its own date.
function postDate(p) {
  if (p.refs) { const y = newestYearForTopic(p.refs); if (y) return String(y); }
  return p.date;
}

// First figure in a post body, resolved through the offline-resource map.
// A post may also declare an explicit `thumb` (used when its hero is an embed).
function postThumb(p) {
  if (p.thumb) return (p.thumbResId && window.__resources && window.__resources[p.thumbResId]) || p.thumb;
  const fig = (p.body || []).find((b) => b && b.fig);
  if (!fig) return null;
  return (fig.resId && window.__resources && window.__resources[fig.resId]) || fig.fig;
}

// Renders the references for a post: all publications carrying the given topic tag.
function PostReferences({ post }) {
  const prefix = (post.refs || 'post').toLowerCase();
  const venueOf = (p) => p.conf ? (p.v || '').split(',')[0] : p.v;
  let refs, tagObj = null;
  if (post.references && post.references.length) {
    refs = post.references; // explicit, in citation order
  } else {
    const P = window.WINTEL_PUBLICATIONS;
    if (!P || !window.topicsFor) return null;
    const all = [...(P.inPress || []), ...(P.articles || []), ...(P.proceedings || []), ...(P.bookChapters || [])];
    refs = all
      .filter((p) => window.topicsFor(p).some((t) => t.label === post.refs))
      .filter((p) => !/data[\s-]?cent(er|re)/i.test(p.t || ''))
      .filter((p) => !/abdelhad|ghadhban/i.test(((p.a && p.a[0] && p.a[0].name) || '')))
      .sort((a, b) => Number(b.y || 0) - Number(a.y || 0));
    tagObj = (window.TOPICS || []).find((t) => t.label === post.refs);
  }
  if (!refs.length) return null;
  return (
    <section style={{ display: 'flex', flexDirection: 'column', gap: '1rem', marginTop: '1rem', paddingTop: '1.5rem', borderTop: '1px solid var(--border-default)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
        <h2 style={{ margin: 0, fontSize: 'var(--text-xl)', fontWeight: 'var(--weight-semibold)', letterSpacing: 'var(--tracking-tight)', color: 'var(--text-primary)' }}>References</h2>
        {tagObj && window.TopicTag ? <window.TopicTag topic={tagObj} /> : null}
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 'var(--text-xs)', color: 'var(--text-muted)' }}>{refs.length}</span>
      </div>
      <ol style={{ margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: '0.85rem' }}>
        {refs.map((p, i) => (
          <li key={i} id={prefix + '-ref-' + (i + 1)} style={{ listStyle: 'none', display: 'flex', gap: '0.7rem', scrollMarginTop: '90px' }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 'var(--text-sm)', color: 'var(--text-muted)', flexShrink: 0, minWidth: '1.9rem', textAlign: 'right', paddingTop: '0.1rem' }}>{i + 1}.</span>
            <p style={{ margin: 0, fontSize: 'var(--text-base)', lineHeight: 'var(--leading-snug)', color: 'var(--text-body)', fontWeight: 'var(--weight-light)', textWrap: 'pretty' }}>
              {(p.a || []).map((au, j, arr) => (
                <React.Fragment key={j}>
                  {j > 0 ? (j === arr.length - 1 ? (arr.length > 2 ? ', and ' : ' and ') : ', ') : ''}
                  <span style={{ fontWeight: au.owner ? 'var(--weight-semibold)' : 'var(--weight-light)', color: au.owner ? 'var(--text-primary)' : undefined }}>{au.name}</span>
                </React.Fragment>
              ))}
              {', \u201C'}<span style={{ color: 'var(--text-primary)' }}>{p.t}</span>{',\u201D '}
              <em>{p.conf ? 'Proc. ' : ''}{venueOf(p)}</em>{p.vol ? <span>, vol. {p.vol}</span> : null}{p.no ? <span>, no. {p.no}</span> : null}{p.p ? <span>, pp. {p.p}</span> : null}{p.y ? <span>, {p.y}</span> : null}.
              {p.u ? <a href={p.u} target="_blank" rel="noopener noreferrer" style={{ marginLeft: '0.4rem', color: 'var(--accent)', textDecoration: 'none', fontFamily: 'var(--font-mono)', fontSize: 'var(--text-xs)', whiteSpace: 'nowrap' }}>DOI</a> : null}
            </p>
          </li>
        ))}
      </ol>
    </section>
  );
}

// Renders a body paragraph, turning [n] or [n, m] citation markers into
// superscript links to the numbered reference list (id="<refPrefix>-ref-n").
function CitedText({ text, refPrefix }) {
  const parts = String(text).split(/(\[\d+(?:\s*,\s*\d+)*\])/g);
  return (
    <React.Fragment>
      {parts.map((seg, i) => {
        const m = seg.match(/^\[(\d+(?:\s*,\s*\d+)*)\]$/);
        if (!m) return <React.Fragment key={i}>{seg}</React.Fragment>;
        const nums = m[1].split(',').map((s) => s.trim());
        return (
          <sup key={i} style={{ fontFamily: 'var(--font-mono)', fontSize: '0.7em', lineHeight: 0, whiteSpace: 'nowrap' }}>
            [{nums.map((n, j) => (
              <React.Fragment key={n}>
                {j > 0 ? ', ' : ''}
                <a href={'#' + refPrefix + '-ref-' + n} style={{ color: 'var(--accent)', textDecoration: 'none' }}
                   onClick={(e) => { e.preventDefault(); const el = document.getElementById(refPrefix + '-ref-' + n); if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' }); }}>{n}</a>
              </React.Fragment>
            ))}]
          </sup>
        );
      })}
    </React.Fragment>
  );
}

function ResearchView({ data }) {
  const posts = (data.blog || []).filter((p) => !p.draft);
  const [open, setOpen] = React.useState(() => {
    const t = window.__researchOpen;
    if (t != null) {
      window.__researchOpen = null;
      const idx = (data.blog || []).filter((x) => !x.draft).findIndex((x) => x.title === t);
      return idx >= 0 ? idx : null;
    }
    return null;
  }); // index of open post, or null

  if (open !== null) {
    const p = posts[open];
    const leadFig = (p.body || []).find((b) => b && b.fig);
    const leadSrc = leadFig ? ((leadFig.resId && window.__resources && window.__resources[leadFig.resId]) || leadFig.fig) : null;
    let leadShown = false;
    return (
      <main style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
        <RV.Button variant="ghost" size="sm" onClick={() => setOpen(null)}
          style={{ alignSelf: 'flex-start', paddingLeft: 0, color: 'var(--text-muted)' }}>
          <i className="ri-arrow-left-line" style={{ fontSize: 16 }} /> All posts
        </RV.Button>
        {p.heroEmbed ? (
          <figure style={{ margin: 0, display: 'flex', flexDirection: 'column', gap: '0.6rem' }}>
            <iframe src={p.heroEmbed} title={p.title} loading="lazy" style={{ width: '100%', height: '420px', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)', display: 'block', background: '#002E3B' }} />
            {p.heroCap ? <figcaption style={{ margin: 0, fontSize: 'var(--text-sm)', color: 'var(--text-muted)', lineHeight: 'var(--leading-snug)', textWrap: 'pretty' }}>{p.heroCap}</figcaption> : null}
          </figure>
        ) : null}
        {leadSrc ? (
          <figure style={{ margin: 0, display: 'flex', flexDirection: 'column', gap: '0.6rem' }}>
            <img src={leadSrc} alt={leadFig.cap || p.title} loading="lazy" decoding="async" style={{ width: '100%', height: 'auto', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-default)', display: 'block' }} />
            {leadFig.cap ? <figcaption style={{ margin: 0, fontSize: 'var(--text-sm)', color: 'var(--text-muted)', lineHeight: 'var(--leading-snug)', textWrap: 'pretty' }}>{leadFig.cap}</figcaption> : null}
          </figure>
        ) : null}
        <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem', flexWrap: 'wrap' }}>
          <RV.Badge tone="accent">{p.tag}</RV.Badge>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 'var(--text-xs)', color: 'var(--text-muted)' }}>{postDate(p)}</span>
          {p.draft ? <RV.Badge tone="muted" variant="outline">draft</RV.Badge> : null}
        </div>
        <h1 style={{ margin: 0, fontSize: 'var(--text-3xl)', fontWeight: 'var(--weight-semibold)', letterSpacing: 'var(--tracking-tight)', color: 'var(--text-primary)', lineHeight: 'var(--leading-tight)' }}>{p.title}</h1>
        <article style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
          {p.body.map((block, i) => {
            if (typeof block === 'string') {
              return <p key={i} style={{ margin: 0, fontSize: 'var(--text-lg)', lineHeight: 'var(--leading-relaxed)', color: 'var(--text-body)', textWrap: 'pretty' }}><CitedText text={block} refPrefix={(p.refs || 'post').toLowerCase()} /></p>;
            }
            if (block.h) {
              return <h2 key={i} style={{ margin: '0.75rem 0 0', fontSize: 'var(--text-xl)', fontWeight: 'var(--weight-semibold)', letterSpacing: 'var(--tracking-tight)', color: 'var(--text-primary)' }}>{block.h}</h2>;
            }
            if (block.fig) {
              if (block === leadFig && !leadShown) { leadShown = true; return null; } // already shown at top
              const src = (block.resId && window.__resources && window.__resources[block.resId]) || block.fig;
              return (
                <figure key={i} style={{ margin: '0.5rem 0', display: 'flex', flexDirection: 'column', gap: '0.6rem' }}>
                  <img src={src} alt={block.cap || ''} loading="lazy" decoding="async" style={{ width: '100%', height: 'auto', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-default)', display: 'block' }} />
                  {block.cap ? <figcaption style={{ margin: 0, fontSize: 'var(--text-sm)', color: 'var(--text-muted)', lineHeight: 'var(--leading-snug)', textWrap: 'pretty' }}>{block.cap}</figcaption> : null}
                </figure>
              );
            }
            return null;
          })}
        </article>
        {(p.refs || p.references) ? <PostReferences post={p} /> : null}
      </main>
    );
  }

  return (
    <main style={{ display: 'flex', flexDirection: 'column', gap: '1.5rem' }}>
      <RV.SectionHeading title="Research" />
      <p style={{ margin: 0, color: 'var(--text-body)', fontWeight: 'var(--weight-light)', fontSize: 'var(--text-base)', textWrap: 'pretty' }}>
        This research blog is written for a general audience. The style is deliberately closer to popular science than to a technical paper as the goal is to make the ideas behind our cutting edge wireless communication and networking research accessible and intuitive, without compromising scientific accuracy. For the full technical detail, methods, and results, see the bibliography provided at the end of each post.
      </p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
        {posts.map((p, i) => {
          const thumb = postThumb(p);
          return (
          <RV.Card key={i} interactive onClick={() => setOpen(i)} style={{ cursor: 'pointer' }}>
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              {thumb ? (
                <img src={thumb} alt="" loading="lazy" decoding="async" style={{ width: '100%', height: 'auto', display: 'block', borderBottom: '1px solid var(--border-default)' }} />
              ) : null}
              <div style={{ padding: '1.25rem 1.5rem', display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem', flexWrap: 'wrap' }}>
                  <RV.Badge tone="accent">{p.tag}</RV.Badge>
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 'var(--text-xs)', color: 'var(--text-muted)' }}>{postDate(p)}</span>
                  {p.draft ? <RV.Badge tone="muted" variant="outline">draft</RV.Badge> : null}
                </div>
                <h3 style={{ margin: 0, fontSize: 'var(--text-xl)', fontWeight: 'var(--weight-semibold)', color: 'var(--text-primary)', lineHeight: 'var(--leading-snug)' }}>{p.title}</h3>
                <p style={{ margin: 0, fontSize: 'var(--text-base)', color: 'var(--text-body)', fontWeight: 'var(--weight-light)', lineHeight: 'var(--leading-snug)', textWrap: 'pretty' }}>{p.excerpt}</p>
                <span style={{ fontSize: 'var(--text-sm)', color: 'var(--text-muted)', marginTop: '0.15rem' }}>Read more →</span>
              </div>
            </div>
          </RV.Card>
          );
        })}
      </div>
    </main>
  );
}

Object.assign(window, { ResearchView });
