/* GCCReady — Resources Library (301 articles) + Article reader */

const TOPIC_META = {
  'US CPA':            { icon:'file-check',     tone:'navy' },
  'US CMA':            { icon:'calculator',     tone:'gold' },
  'ACCA':              { icon:'globe',          tone:'teal' },
  'CFA':               { icon:'chart-pie',      tone:'navy' },
  'CFA / FRM':         { icon:'chart-pie',      tone:'navy' },
  'EA':                { icon:'file-text',      tone:'gold' },
  'GCC Job Readiness': { icon:'briefcase',      tone:'gold' },
  'India Compliance':  { icon:'shield-check',   tone:'green' },
  'AI & Tech':         { icon:'sparkles',       tone:'teal' },
  'Career Strategy':   { icon:'rocket',         tone:'gold' },
};

function ResourcesLibraryPage() {
  const [data, setData] = React.useState(null);
  const [query, setQuery] = React.useState('');
  const [topic, setTopic] = React.useState('All');

  React.useEffect(() => {
    fetch('./articles.json')
      .then((r) => r.json())
      .then(setData)
      .catch((err) => setData({ error: String(err) }));
  }, []);

  if (!data) return <LibraryLoading/>;
  if (data.error) return <LibraryError msg={data.error}/>;

  const all = data.articles || [];
  const topics = ['All', ...Object.keys(data.topics || {}).sort((a, b) => (data.topics[b] - data.topics[a]))];

  const filtered = all.filter((a) => {
    if (topic !== 'All' && a.topic !== topic) return false;
    if (!query) return true;
    const q = query.toLowerCase();
    return (a.title || '').toLowerCase().includes(q)
        || (a.description || '').toLowerCase().includes(q)
        || (a.keywords || '').toLowerCase().includes(q);
  });

  return (
    <>
      <PageHead
        title="The Library — 301 deep-dive guides on US CPA, CMA, EA, CFA, ACCA"
        description="1.1 million words on the credentials, tools and playbooks GCCs hire for. CPA, CMA, EA, CFA, ACCA pathways, AI for finance, India compliance, placement loops. Free to read."
        canonical="/resources/library"
        schema={[
          schemaCollection({ name:'GCCReady Library', description:'301 deep-dive guides on GCC-readiness', url:'/resources/library', items: (data.articles || []).slice(0, 30).map((a) => ({ name: a.title, url: `/article/${a.slug}` })) }),
          schemaBreadcrumb([{label:'Home',href:'/'},{label:'Library',href:'/resources/library'}]),
        ]}
      />
      <HeroDark>
        <div style={{maxWidth:980}}>
          <Pill tone="dark" icon="book-open">The Library</Pill>
          <h1 className="gr-h1" style={{color:'#fff', marginTop:18, fontSize:60, lineHeight:1.04}}>
            Your degree got you in the room.<br/>
            The <span style={{color:'#F59E0B'}}>Library</span> gets you the offer.
          </h1>
          <p className="gr-lead" style={{color:'rgba(255,255,255,.78)', marginTop:18, maxWidth:720}}>
            Long-form answers to every question Bharat's finance, accounting and AI-curious students Google before a GCC interview. CPA, CMA, EA, CFA, ACCA pathways · AI for finance · India compliance · placement loops · interview prep.
          </p>
          <div style={{display:'flex', gap:10, flexWrap:'wrap', marginTop:24}}>
            {[
              [`${data.count} deep-dives`, 'book'],
              ['1.1M words', 'file-text'],
              [`${Object.keys(data.topics||{}).length} topic clusters`, 'layers'],
              ['Free to read', 'gift'],
            ].map(([t, ic], i) => (
              <span key={i} style={{
                display:'inline-flex', alignItems:'center', gap:7,
                padding:'8px 13px', borderRadius:999,
                background:'rgba(255,255,255,.08)', color:'#fff',
                border:'1px solid rgba(255,255,255,.14)',
                font:'700 12.5px/1 Inter',
              }}>
                <Icon name={ic} size={13} style={{color:'#FBBF24'}}/>{t}
              </span>
            ))}
          </div>
        </div>
      </HeroDark>

      <section className="gr-section">
        <div className="gr-container">
          <div style={{
            display:'grid', gridTemplateColumns:'1fr', gap:18,
            position:'sticky', top:74, zIndex:20,
            background:'var(--gr-bg-page)', padding:'14px 0',
            borderBottom:'1px solid var(--gr-border-soft)',
          }}>
            <div style={{position:'relative'}}>
              <div style={{
                position:'absolute', left:18, top:'50%', transform:'translateY(-50%)',
                color:'var(--gr-fg-4)', pointerEvents:'none',
              }}><Icon name="search" size={18}/></div>
              <input
                type="search"
                placeholder={`Search ${data.count} articles…`}
                value={query}
                onChange={(e)=>setQuery(e.target.value)}
                style={{
                  width:'100%', padding:'14px 18px 14px 50px',
                  font:'500 15px/1.4 Inter',
                  border:'1.5px solid var(--gr-border)', borderRadius:14,
                  background:'#fff', color:'var(--gr-fg-1)',
                }}
              />
            </div>
            <div style={{display:'flex', gap:8, flexWrap:'wrap'}}>
              {topics.map((t) => {
                const active = t === topic;
                const count = t === 'All' ? data.count : data.topics[t];
                return (
                  <button key={t} onClick={()=>setTopic(t)} style={{
                    padding:'9px 14px', borderRadius:999,
                    border: active ? '1.5px solid var(--gr-navy)' : '1.5px solid var(--gr-border)',
                    background: active ? 'var(--gr-navy)' : '#fff',
                    color: active ? '#fff' : 'var(--gr-fg-1)',
                    font:'700 12.5px/1 Inter',
                    cursor:'pointer',
                    display:'inline-flex', alignItems:'center', gap:6,
                  }}>
                    {t}
                    <span style={{
                      padding:'2px 7px', borderRadius:999,
                      background: active ? 'rgba(255,255,255,.18)' : 'var(--gr-bg-tint)',
                      color: active ? 'rgba(255,255,255,.85)' : 'var(--gr-fg-3)',
                      font:'700 11px/1 "DM Sans"',
                    }}>{count}</span>
                  </button>
                );
              })}
            </div>
          </div>

          <div style={{marginTop:24, font:'500 13.5px/1 Inter', color:'var(--gr-fg-3)'}}>
            Showing <strong style={{color:'var(--gr-navy)'}}>{filtered.length}</strong> of {data.count} {topic !== 'All' && `· ${topic}`} {query && `· "${query}"`}
          </div>

          <div style={{
            marginTop:18,
            display:'grid',
            gridTemplateColumns:'repeat(auto-fill, minmax(320px, 1fr))',
            gap:16,
          }}>
            {filtered.map((a) => <ArticleCard key={a.slug} a={a}/>)}
          </div>

          {filtered.length === 0 && (
            <div style={{
              marginTop:36, padding:36, textAlign:'center',
              border:'1px dashed var(--gr-border)', borderRadius:18,
              color:'var(--gr-fg-3)', font:'500 14.5px/1.5 Inter',
            }}>
              No matches. Try a different topic or clear your search.
            </div>
          )}
        </div>
      </section>

      <CTABand title="Need a personal pathway, not just an article?" sub="Send your degree, target role, and timeline. We come back with a 1-pager mapping the right cert, role pod, and named GCCs to target." primaryLabel="Get your Skill Badge" primaryHref="#/skill-badge"/>
    </>
  );
}

function ArticleCard({ a }) {
  const meta = TOPIC_META[a.topic] || TOPIC_META['Career Strategy'];
  return (
    <a href={`#/article/${a.slug}`} className="gr-card" style={{
      padding:22, textDecoration:'none', color:'var(--gr-fg-1)',
      display:'flex', flexDirection:'column', gap:12,
      transition:'all .2s ease',
    }}
    onMouseEnter={(ev)=>{ ev.currentTarget.style.borderColor='var(--gr-gold-200)'; ev.currentTarget.style.boxShadow='var(--gr-shadow-md)'; ev.currentTarget.style.transform='translateY(-2px)'; }}
    onMouseLeave={(ev)=>{ ev.currentTarget.style.borderColor='var(--gr-border)'; ev.currentTarget.style.boxShadow='var(--gr-shadow-xs)'; ev.currentTarget.style.transform='none'; }}
    >
      <div style={{display:'flex', alignItems:'center', gap:10}}>
        <div style={{
          width:36, height:36, borderRadius:10,
          background:'var(--gr-gold-50)', color:'var(--gr-gold-700)',
          display:'grid', placeItems:'center',
        }}><Icon name={meta.icon} size={16}/></div>
        <Pill tone={meta.tone}>{a.topic}</Pill>
      </div>
      <h3 style={{
        font:'700 16px/1.35 "DM Sans"', letterSpacing:'-0.005em',
        color:'var(--gr-navy)', margin:0,
      }}>{a.title || a.slug}</h3>
      {a.description && (
        <p style={{
          font:'400 13.5px/1.55 Inter', color:'var(--gr-fg-2)',
          margin:0,
          display:'-webkit-box', WebkitLineClamp:3, WebkitBoxOrient:'vertical',
          overflow:'hidden',
        }}>{a.description}</p>
      )}
      <div style={{
        marginTop:'auto', display:'flex', alignItems:'center', justifyContent:'space-between',
        font:'600 12px/1 Inter', color:'var(--gr-fg-3)',
      }}>
        <span><Icon name="clock" size={12} style={{verticalAlign:'-2px', marginRight:5, opacity:.7}}/>{a.reading_time_min} min read</span>
        <span style={{color:'var(--gr-gold-700)', fontWeight:700, display:'inline-flex', alignItems:'center', gap:4}}>
          Read <Icon name="arrow-right" size={12}/>
        </span>
      </div>
    </a>
  );
}

function LibraryLoading() {
  return (
    <section style={{padding:'120px 0', textAlign:'center', color:'var(--gr-fg-3)'}}>
      <div style={{font:'600 14px/1 Inter', letterSpacing:'.12em', textTransform:'uppercase'}}>Loading library…</div>
    </section>
  );
}
function LibraryError({ msg }) {
  return (
    <section style={{padding:'120px 0', textAlign:'center', color:'var(--gr-red)'}}>
      <div style={{font:'700 14px/1 Inter'}}>Failed to load articles.json — {msg}</div>
    </section>
  );
}

/* ============================================================================
 * Article reader — fetches the converted fragment and renders inside chrome
 * ========================================================================== */
function ArticlePage({ slug }) {
  const [state, setState] = React.useState({ status:'loading' });
  const [manifest, setManifest] = React.useState(null);

  React.useEffect(() => {
    let cancelled = false;
    Promise.all([
      fetch(`./articles/${slug}.html`).then((r) => r.ok ? r.text() : Promise.reject(new Error('not found'))),
      fetch('./articles.json').then((r) => r.json()).catch(() => null),
    ]).then(([html, m]) => {
      if (cancelled) return;
      setState({ status:'ok', html });
      setManifest(m);
    }).catch((err) => {
      if (cancelled) return;
      setState({ status:'error', msg: String(err) });
    });
    return () => { cancelled = true; };
  }, [slug]);

  const meta = manifest && manifest.articles ? manifest.articles.find((a) => a.slug === slug) : null;
  const topicMeta = (meta && TOPIC_META[meta.topic]) || TOPIC_META['Career Strategy'];

  // Related articles: same topic, exclude self, max 3
  const related = (meta && manifest)
    ? manifest.articles.filter((a) => a.topic === meta.topic && a.slug !== slug).slice(0, 3)
    : [];

  if (state.status === 'loading') return <LibraryLoading/>;
  if (state.status === 'error') return (
    <>
      <HeroDark>
        <div>
          <Crumbs items={[{ label:'Library', href:'#/resources/library' }, { label:'Not found' }]}/>
          <h1 className="gr-h1" style={{color:'#fff', marginTop:14, fontSize:48}}>Article not found.</h1>
          <p style={{color:'rgba(255,255,255,.72)', font:'500 16px/1.5 Inter', marginTop:10}}>{state.msg}</p>
          <a href="#/resources/library" className="gr-btn gr-btn-gold gr-btn-lg" style={{marginTop:20}}>Back to library <Icon name="arrow-right" size={14}/></a>
        </div>
      </HeroDark>
    </>
  );

  return (
    <>
      {meta && <PageHead
        title={meta.title}
        description={meta.description}
        canonical={`/article/${slug}`}
        ogType="article"
        schema={[
          { '@context':'https://schema.org','@type':'Article','headline': meta.title,'description': meta.description,'author':{'@type':'Organization','name': SITE_NAME,'url': SITE_ORIGIN},'publisher':{'@type':'Organization','name': SITE_NAME,'url': SITE_ORIGIN},'datePublished':'2026-03-28','dateModified':'2026-03-28','mainEntityOfPage':`${SITE_ORIGIN}/article/${slug}`,'wordCount': meta.word_count,'articleSection': meta.topic,'keywords': meta.keywords ? meta.keywords.split(',').map((s)=>s.trim()) : undefined },
          schemaBreadcrumb([{label:'Home',href:'/'},{label:'Library',href:'/resources/library'},{label: meta.topic, href:`/resources/library?topic=${encodeURIComponent(meta.topic)}`},{label: meta.title, href:`/article/${slug}`}]),
        ]}
      />}
      <HeroDark>
        <div style={{maxWidth:760, margin:'0 auto'}}>
          <Crumbs items={[
            { label:'Library', href:'#/resources/library' },
            meta ? { label: meta.topic, href:`#/resources/library?topic=${encodeURIComponent(meta.topic)}` } : null,
            { label: meta ? meta.title : slug },
          ].filter(Boolean)}/>
          <div style={{marginTop:18}}>
            <Pill tone="dark" icon={topicMeta.icon}>{meta ? meta.topic : 'Article'}</Pill>
          </div>
          <h1 style={{
            font:'800 48px/1.1 "DM Sans"', color:'#fff',
            margin:'18px 0 12px', letterSpacing:'-0.025em',
          }}>{meta ? meta.title : slug}</h1>
          {meta && meta.description && (
            <p style={{font:'400 18px/1.6 Inter', color:'rgba(255,255,255,.78)', maxWidth:680, margin:0}}>{meta.description}</p>
          )}
          {meta && (
            <div style={{display:'flex', gap:14, marginTop:20, color:'rgba(255,255,255,.65)', font:'600 13px/1 Inter'}}>
              <span><Icon name="clock" size={13} style={{verticalAlign:'-2px', marginRight:6, opacity:.7}}/>{meta.reading_time_min} min read</span>
              <span style={{opacity:.4}}>·</span>
              <span>{meta.word_count.toLocaleString()} words</span>
            </div>
          )}
        </div>
      </HeroDark>

      <section className="gr-section" style={{padding:'56px 0 80px'}}>
        <div className="gr-container">
          <div className="gr-prose" dangerouslySetInnerHTML={{ __html: state.html }}/>
        </div>
      </section>

      {meta && <ArticleEnhancements topic={meta.topic} articleSlug={slug}/>}
      {meta && <NextReadRail topic={meta.topic} currentArticleSlug={slug}/>}

      {related.length > 0 && (
        <section className="gr-section">
          <div className="gr-container">
            <SectionTitle eyebrow="More from the same cluster" title={`More on ${meta.topic}`}/>
            <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:16}}>
              {related.map((a) => <ArticleCard key={a.slug} a={a}/>)}
            </div>
          </div>
        </section>
      )}

      <CTABand title="Reading is the easy part. Hiring is the goal." sub="Take your Skill Badge — we map your degree and target role to the certs and named GCCs hiring for your profile." primaryLabel="Get your Skill Badge" primaryHref="#/skill-badge"/>
    </>
  );
}

Object.assign(window, { ResourcesLibraryPage, ArticlePage, ArticleCard });
