/* GCCReady — NextReadRail
 * "What to read next" engine. Loads articles.json once + builds personalised
 * cards for: 1 article (same topic, not yet read this session) + 1 cert + 1 role + 1 tool.
 * Mount on Article, RoleDetail, PillarCert, Hub pages.
 *
 * Reads/writes localStorage('gr_read_history') so we don't repeat articles.
 */

const _grReadHistKey = 'gr_read_history';
function _grHistory() {
  try { return JSON.parse(localStorage.getItem(_grReadHistKey) || '[]'); } catch { return []; }
}
function _grRecord(slug) {
  if (!slug) return;
  try {
    const h = _grHistory();
    const next = [slug, ...h.filter((s) => s !== slug)].slice(0, 50);
    localStorage.setItem(_grReadHistKey, JSON.stringify(next));
  } catch (_) {}
}

function NextReadRail({ topic, currentArticleSlug, certSlug, roleSlug, employerSlug }) {
  const [articles, setArticles] = React.useState([]);
  React.useEffect(() => {
    if (currentArticleSlug) _grRecord(currentArticleSlug);
    fetch('./articles.json').then((r) => r.json()).then((m) => setArticles(m.articles || [])).catch(() => {});
  }, [currentArticleSlug]);

  const hist = _grHistory();
  const candidate =
    (topic && articles.filter((a) => a.topic === topic && a.slug !== currentArticleSlug && !hist.includes(a.slug))[0]) ||
    (topic && articles.filter((a) => a.topic === topic && a.slug !== currentArticleSlug)[0]) ||
    articles.filter((a) => a.slug !== currentArticleSlug)[0];

  // Cert pick
  let certPick = certSlug && CERT_PILLAR && CERT_PILLAR[certSlug];
  if (!certPick && topic) {
    const map = { 'US CPA':'us-cpa','US CMA':'us-cma','EA':'ea','CFA':'cfa','ACCA':'acca' };
    const cs = map[topic];
    if (cs && CERT_PILLAR && CERT_PILLAR[cs]) certPick = { ...CERT_PILLAR[cs], slug: cs };
    else if (cs) certPick = { name: cs.toUpperCase().replace(/-/g,' '), slug: cs, tagline:'Pathway, fees, salary, GCCs hiring.' };
  }
  if (certPick && !certPick.slug) {
    const cs = Object.keys(CERT_PILLAR || {}).find((k) => CERT_PILLAR[k] === certPick);
    certPick = { ...certPick, slug: cs };
  }

  // Role pick — match topic to role family or tools
  const role = (roleSlug && GR_ROLES.find((r) => r.slug === roleSlug))
    || (topic === 'AI & Tech' && GR_ROLES.find((r) => r.slug === 'data-analytics'))
    || (topic === 'India Compliance' && GR_ROLES.find((r) => r.slug === 'tax'))
    || GR_ROLES.find((r) => r.certs.some((c) => c.includes(topic || '')))
    || GR_ROLES[0];

  // Tool pick
  const toolByTopic = {
    'US CPA': { name:'CPA ROI Calculator', icon:'trending-up', href:'/tools-static/cpa-roi-calculator.html' },
    'US CMA': { name:'CPA Salary Benchmark', icon:'bar-chart', href:'/tools-static/cpa-salary-benchmark.html' },
    'EA':     { name:'CPA Eligibility Checker', icon:'shield-check', href:'/tools-static/cpa-eligibility-checker.html' },
    'CFA':    { name:'Career Path Simulator', icon:'rocket', href:'/tools-static/career-path-simulator.html' },
    'ACCA':   { name:'Credential Selector Quiz', icon:'help-circle', href:'/tools-static/credential-selector-quiz.html' },
    'AI & Tech': { name:'Resume Score Checker', icon:'file-check', href:'/tools-static/resume-scorer.html' },
    'India Compliance': { name:'GST Computation Tool', icon:'calculator', href:'/tools-static/gst-computation-tool.html' },
    'GCC Job Readiness': { name:'Interview Readiness Assessment', icon:'users', href:'/tools-static/interview-prep-assessment.html' },
  };
  const tool = toolByTopic[topic] || { name:'CPA ROI Calculator', icon:'trending-up', href:'/tools-static/cpa-roi-calculator.html' };

  if (articles.length === 0) return null;

  return (
    <section className="gr-section" style={{background:'var(--gr-bg-cream)', padding:'56px 0'}}>
      <div className="gr-container">
        <SectionTitle eyebrow="What's next for someone like you" title="Pick up where you left off" sub="Personalised — one article you haven't read yet, the matching cert, the role pod, and a tool to put it to use."/>
        <div style={{display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:16}}>
          {/* Article */}
          {candidate && (
            <a href={`#/article/${candidate.slug}`} className="gr-card" style={{
              padding:22, textDecoration:'none', color:'var(--gr-fg-1)',
              display:'flex', flexDirection:'column', gap:10,
            }}>
              <div style={{font:'700 11px/1 Inter', color:'var(--gr-gold-700)', letterSpacing:'.14em', textTransform:'uppercase'}}>Read next</div>
              <h4 style={{font:'700 16px/1.3 "DM Sans"', color:'var(--gr-navy)', margin:0}}>{candidate.title}</h4>
              <p style={{font:'500 12.5px/1.5 Inter', color:'var(--gr-fg-3)', margin:0,
                display:'-webkit-box', WebkitLineClamp:3, WebkitBoxOrient:'vertical', overflow:'hidden'}}>{candidate.description}</p>
              <div style={{marginTop:'auto', font:'600 12px/1 Inter', color:'var(--gr-fg-3)'}}>
                <Icon name="clock" size={11} style={{verticalAlign:'-1px', marginRight:4}}/>{candidate.reading_time_min} min · {candidate.topic}
              </div>
            </a>
          )}
          {/* Cert */}
          {certPick && (
            <a href={`#/certifications/${certPick.slug}`} className="gr-card" style={{
              padding:22, textDecoration:'none', color:'var(--gr-fg-1)',
              display:'flex', flexDirection:'column', gap:10,
            }}>
              <div style={{font:'700 11px/1 Inter', color:'var(--gr-gold-700)', letterSpacing:'.14em', textTransform:'uppercase'}}>Pathway</div>
              <div style={{
                width:38, height:38, borderRadius:11, background:'var(--gr-gold-50)', color:'var(--gr-gold-700)',
                display:'grid', placeItems:'center',
              }}><Icon name="award" size={18}/></div>
              <h4 style={{font:'700 17px/1.3 "DM Sans"', color:'var(--gr-navy)', margin:0}}>{certPick.name}</h4>
              <p style={{font:'500 12.5px/1.5 Inter', color:'var(--gr-fg-3)', margin:0,
                display:'-webkit-box', WebkitLineClamp:3, WebkitBoxOrient:'vertical', overflow:'hidden'}}>{certPick.tagline || certPick.hero_sub || ''}</p>
              <div style={{marginTop:'auto', font:'700 12px/1 Inter', color:'var(--gr-gold-700)'}}>See pathway →</div>
            </a>
          )}
          {/* Role */}
          {role && (
            <a href={`#/role/${role.slug}`} className="gr-card" style={{
              padding:22, textDecoration:'none', color:'var(--gr-fg-1)',
              display:'flex', flexDirection:'column', gap:10,
            }}>
              <div style={{font:'700 11px/1 Inter', color:'var(--gr-gold-700)', letterSpacing:'.14em', textTransform:'uppercase'}}>Role pod</div>
              <div style={{
                width:38, height:38, borderRadius:11, background:'var(--gr-gold-50)', color:'var(--gr-gold-700)',
                display:'grid', placeItems:'center',
              }}><Icon name={role.icon} size={18}/></div>
              <h4 style={{font:'700 17px/1.3 "DM Sans"', color:'var(--gr-navy)', margin:0}}>{role.title}</h4>
              <div style={{font:'500 12.5px/1.5 Inter', color:'var(--gr-fg-3)'}}>{role.salary} · {role.family}</div>
              <div style={{marginTop:'auto', font:'700 12px/1 Inter', color:'var(--gr-gold-700)'}}>See role pod →</div>
            </a>
          )}
          {/* Tool */}
          <a href={tool.href} className="gr-card" style={{
            padding:22, textDecoration:'none', color:'var(--gr-fg-1)',
            display:'flex', flexDirection:'column', gap:10,
          }}>
            <div style={{font:'700 11px/1 Inter', color:'var(--gr-gold-700)', letterSpacing:'.14em', textTransform:'uppercase'}}>Try the tool</div>
            <div style={{
              width:38, height:38, borderRadius:11, background:'var(--gr-gold-50)', color:'var(--gr-gold-700)',
              display:'grid', placeItems:'center',
            }}><Icon name={tool.icon} size={18}/></div>
            <h4 style={{font:'700 17px/1.3 "DM Sans"', color:'var(--gr-navy)', margin:0}}>{tool.name}</h4>
            <p style={{font:'500 12.5px/1.5 Inter', color:'var(--gr-fg-3)', margin:0}}>Free, interactive, no login.</p>
            <div style={{marginTop:'auto', font:'700 12px/1 Inter', color:'var(--gr-gold-700)'}}>Open tool →</div>
          </a>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { NextReadRail });
