// Resources.jsx — Verigo Global: Articles, Free Downloads
// Article pages; gated PDF downloads
const { V: RV, MAXW: RMW, FONT: RFT } = window;

const ARTICLES = [
  { id: 'a1', cat: 'Strategy', title: 'SOC 2 vs ISO 27001: Which Certification Should You Pursue First?', excerpt: 'Both are widely recognized, but they answer different questions for different buyers. Here is how to read the signals in your contracts and prospect list to pick the right starting point.', read: '8 min', standard: 'soc2', date: 'June 12, 2026' },
  { id: 'a2', cat: 'CMMC 2.0', title: 'How to Scope a CUI Enclave — and Why It Changes Your Level 2 Cost', excerpt: 'The single highest-leverage decision in a CMMC 2.0 program is defining your CUI enclave. A well-scoped enclave can reduce the number of in-scope systems by 60–80%.', read: '6 min', standard: 'cmmc', date: 'June 3, 2026' },
  { id: 'a3', cat: 'SOC 2', title: 'The Evidence Engine: How to Make Your Type II Observation Window Routine', excerpt: 'The observation window is not the problem. The scramble before it is. Embed evidence-producing controls into daily workflows so evidence exists continuously.', read: '7 min', standard: 'soc2', date: 'May 22, 2026' },
  { id: 'a4', cat: 'HITRUST', title: 'HITRUST Made Legible: Understanding e1, i1, and r2 Without the Jargon', excerpt: 'HITRUST certifications come in three types with very different scope, cost, and assurance levels. This plain-language guide explains what each one tests.', read: '5 min', standard: 'hitrust', date: 'May 8, 2026' },
  { id: 'a5', cat: 'ISO 27001', title: "Why ISO 27001:2022's Four-Theme Annex A Changes Your Implementation Approach", excerpt: 'Moving from 114 controls across 14 domains to 93 controls across four themes changes more than the numbering — 11 new controls were added and several key expectations expanded.', read: '6 min', standard: 'iso27001', date: 'April 17, 2026' },
  { id: 'a6', cat: 'Risk Management', title: 'Risk Treatment in Practice: Accept, Mitigate, Transfer, or Avoid', excerpt: 'Every framework requires a risk treatment decision, but most documentation is vague. Learn how to make each option defensible under audit with worked examples.', read: '5 min', standard: null, date: 'April 2, 2026' },
  { id: 'a7', cat: 'NIST CSF', title: 'NIST CSF Tiers vs Profiles: A Practical Guide to Using Both', excerpt: 'Tiers describe how you manage cybersecurity. Profiles describe what you do. Used together, they create a gap roadmap and a measurable implementation path.', read: '7 min', standard: 'nist', date: 'March 19, 2026' },
  { id: 'a8', cat: 'Cross-framework', title: 'Certify Once, Reuse Everywhere: Multi-Framework Compliance Programs', excerpt: 'ISO 27001, SOC 2, CMMC 2.0, and NIST 800-171 share significant underlying controls. Learn how to sequence certifications for maximum evidence reuse.', read: '8 min', standard: null, date: 'March 5, 2026' },
];

const DOWNLOADS = [
  { id: 'd1', title: 'SOC 2 Readiness Checklist', format: 'PDF', desc: 'A structured pre-assessment checklist across all five Trust Services categories. Identify gaps before the observation window opens.', icon: 'clipboard', toolkit: 'soc2', tkLabel: 'SOC 2 Toolkit', tags: ['SOC 2', 'Type I & II'] },
  { id: 'd2', title: 'CMMC 2.0 Level 2 Self-Assessment Scorecard', format: 'PDF', desc: 'A domain-by-domain scorecard across all 110 NIST SP 800-171 practices with a gap summary that feeds directly into your POA&M.', icon: 'layers', toolkit: 'cmmc', tkLabel: 'CMMC 2.0 Toolkit', tags: ['CMMC', 'Level 2', '800-171'] },
  { id: 'd3', title: 'ISO 27001:2022 Gap Analysis Template', format: 'PDF', desc: 'Map your current state against all 93 Annex A:2022 controls across four themes. Includes applicability, implementation status, and evidence fields.', icon: 'doc', toolkit: 'iso27001', tkLabel: 'ISO 27001 Toolkit', tags: ['ISO 27001', '2022', 'Annex A'] },
  { id: 'd4', title: 'Cross-Framework Control Mapping Guide', format: 'PDF', desc: 'A master cross-reference mapping ISO 27001 Annex A, the SOC 2 Common Criteria, NIST SP 800-171, and the NIST CSF functions.', icon: 'network', toolkit: null, tkLabel: null, tags: ['ISO 27001', 'SOC 2', 'CMMC', 'NIST'] },
  { id: 'd5', title: 'NIST CSF v2.0 Profile Template', format: 'PDF', desc: 'Build your Current Profile and Target Profile across all six CSF v2.0 functions with a gap summary and prioritization column.', icon: 'target', toolkit: 'nist', tkLabel: 'NIST CSF Toolkit', tags: ['NIST CSF', 'v2.0', 'Profile'] },
  { id: 'd6', title: 'HITRUST CSF Quick-Start Guide', format: 'PDF', desc: 'Plain-language guide to the HITRUST assessment process — selecting your type (e1/i1/r2), setting factors, and working with an External Assessor.', icon: 'heart', toolkit: 'hitrust', tkLabel: 'HITRUST Toolkit', tags: ['HITRUST', 'e1', 'i1', 'r2'] },
];

const STD_MAP = { iso27001: '#4B4FD9', soc2: '#4B4FD9', cmmc: '#E8622A', hitrust: '#E8622A', nist: '#6B7280' };

/* ── LEAD CAPTURE ─────────────────────────────────────────── */
const RC_LEAD_KEY = 'verigo_toolkit_leads';
const RC_USER_KEY = 'verigo_toolkit_user';
function rcGetUser() { try { return JSON.parse(localStorage.getItem(RC_USER_KEY) || 'null'); } catch (e) { return null; } }
function rcStoreLead(lead) {
  try { const rec = { ...lead, ts: new Date().toISOString() }; const all = JSON.parse(localStorage.getItem(RC_LEAD_KEY) || '[]'); all.push(rec); localStorage.setItem(RC_LEAD_KEY, JSON.stringify(all)); const prev = rcGetUser() || {}; const merged = { ...prev }; Object.keys(lead).forEach((k) => { if (k !== 'source' && lead[k]) merged[k] = lead[k]; }); localStorage.setItem(RC_USER_KEY, JSON.stringify(merged)); } catch (e) {}
  window.submitInquiry && window.submitInquiry({
    form_type: lead.source || 'resources',
    name: lead.name, email: lead.email, company: lead.company, phone: lead.phone,
    metadata: lead,
  });
}

/* ── HERO ─────────────────────────────────────────────────── */
const RcHero = () => (
  <section style={{ background:RV.g50, padding:'64px 0', borderBottom:`1px solid ${RV.g200}`, position:'relative', overflow:'hidden' }}>
    <window.HeroWatermark variant="hex" color={RV.purpleDark} opacity={0.12} style={{ top:-40, right:-20, width:520, height:480 }} />
    <div style={{ maxWidth:RMW, margin:'0 auto', padding:'0 32px', position:'relative', zIndex:1 }}>
      <window.Overline style={{ marginBottom:16 }}>Resources</window.Overline>
      <h1 className="vg-hero-title" style={{ fontSize:56, fontWeight:800, letterSpacing:'-0.035em', color:RV.black, margin:'0 0 18px', lineHeight:1.04, fontFamily:RFT, maxWidth:740 }}>Knowledge that accelerates compliance.</h1>
      <p style={{ fontSize:19, color:RV.g600, lineHeight:1.6, margin:'0 0 36px', maxWidth:640 }}>Practical guides and free tools — built by the practitioners who run compliance programs every day.</p>
      <div style={{ display:'flex', gap:12, flexWrap:'wrap' }}>
        {[['Articles','#articles','file'],['Free Downloads','#downloads','arrow']].map(([label,href,icon],i)=>(
          <a key={i} href={href} style={{ display:'inline-flex', alignItems:'center', gap:8, fontSize:14.5, fontWeight:700, color:i===0?'#fff':RV.purple, background:i===0?RV.purple:RV.purpleSubtle, padding:'11px 20px', textDecoration:'none', transition:'opacity 150ms' }}
            onMouseEnter={e=>e.currentTarget.style.opacity='0.85'} onMouseLeave={e=>e.currentTarget.style.opacity='1'}>
            <window.Icon name={icon} size={16} color={i===0?'#fff':RV.purple} />{label}
          </a>
        ))}
      </div>
    </div>
  </section>
);

/* ── ARTICLES ─────────────────────────────────────────────── */
const RcArticles = ({ onNav }) => (
  <window.Section bg={RV.g50} pad="80px 0" id="articles">
    <window.SectionHeader overline="Articles" title="In-depth guides from practitioners" sub="Authoritative analysis on compliance strategy, framework implementation, and evidence management." maxSub={600} />
    <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:16 }}>
      {ARTICLES.map((a) => (
        <div key={a.id} style={{ background:'#fff', border:`1px solid ${RV.g200}`, padding:'24px', display:'flex', flexDirection:'column', cursor:'pointer', transition:'all 150ms' }}
          onMouseEnter={e=>{ e.currentTarget.style.borderColor=RV.purple; e.currentTarget.style.transform='translateY(-2px)'; e.currentTarget.style.boxShadow='0 8px 24px rgba(0,0,0,0.07)'; }}
          onMouseLeave={e=>{ e.currentTarget.style.borderColor=RV.g200; e.currentTarget.style.transform='none'; e.currentTarget.style.boxShadow='none'; }}
          onClick={()=>{ window.location.href='Article.html?id='+a.id; }}>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:12 }}>
            <span style={{ fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:a.standard?STD_MAP[a.standard]:RV.g500, background:a.standard?(STD_MAP[a.standard]+'18'):RV.g100, padding:'3px 9px' }}>{a.cat}</span>
            <span style={{ fontSize:12, color:RV.g400, fontFamily:"'JetBrains Mono',monospace", fontWeight:600 }}>{a.read}</span>
          </div>
          <h3 style={{ fontSize:16, fontWeight:700, color:RV.black, margin:'0 0 10px', fontFamily:RFT, letterSpacing:'-0.01em', lineHeight:1.3, flex:1 }}>{a.title}</h3>
          <p style={{ fontSize:13, color:RV.g500, lineHeight:1.6, margin:'0 0 16px' }}>{a.excerpt.slice(0,100)}…</p>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
            <span style={{ fontSize:12, color:RV.g400 }}>{a.date}</span>
            <span style={{ fontSize:13, fontWeight:700, color:RV.purple, display:'flex', alignItems:'center', gap:5 }}>Read <window.Icon name="arrow" size={14} color={RV.purple} /></span>
          </div>
        </div>
      ))}
    </div>
  </window.Section>
);

/* ── FREE DOWNLOADS ───────────────────────────────────────── */
const RcDownloads = ({ onNav, onDownload }) => (
  <window.Section bg="#fff" pad="80px 0 0" id="downloads">
    <window.SectionHeader overline="Free Downloads" title="Templates, checklists & guides — no charge" sub="Production-ready tools you can use immediately. We'll ask for your name and email before generating your PDF." maxSub={620} />
    <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:20, marginBottom:48 }}>
      {DOWNLOADS.map((d) => (
        <div key={d.id} style={{ display:'flex', flexDirection:'column', border:`1px solid ${RV.g200}`, padding:'28px 26px', background:'#fff' }}>
          <div style={{ display:'flex', alignItems:'flex-start', gap:14, marginBottom:16 }}>
            <div style={{ width:48, height:48, background:RV.purpleSubtle, color:RV.purple, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><window.Icon name={d.icon} size={24} /></div>
            <div>
              <span style={{ fontSize:10.5, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:RV.orange, background:RV.orangeSubtle, padding:'2px 8px', display:'inline-block', marginBottom:6 }}>{d.format}</span>
              <h3 style={{ fontSize:17, fontWeight:700, color:RV.black, margin:0, fontFamily:RFT, letterSpacing:'-0.01em', lineHeight:1.25 }}>{d.title}</h3>
            </div>
          </div>
          <p style={{ fontSize:13.5, color:RV.g600, lineHeight:1.65, margin:'0 0 16px', flex:1 }}>{d.desc}</p>
          <div style={{ display:'flex', flexWrap:'wrap', gap:6, marginBottom:18 }}>
            {d.tags.map((t,i)=><span key={i} style={{ fontSize:11.5, fontWeight:700, color:RV.g600, background:RV.g100, padding:'3px 9px' }}>{t}</span>)}
          </div>
          <div style={{ display:'flex', gap:10 }}>
            <window.Btn kind="primary" onClick={()=>onDownload(d)} style={{ flex:1, justifyContent:'center', fontSize:13.5, padding:'10px 16px' }}>
              <window.Icon name="arrow" size={15} color="#fff" /> Download free PDF
            </window.Btn>
            {d.toolkit && <window.Btn kind="ghostBrand" onClick={()=>onNav('toolkit:'+d.toolkit)} style={{ fontSize:13, padding:'10px 13px' }}>Full toolkit <window.Icon name="arrow" size={14} color={RV.purple} /></window.Btn>}
          </div>
        </div>
      ))}
    </div>
    <window.CTABand overline="Need more than a template?" title="Get the full practitioner-maintained toolkit for your framework." body="Every free download is a sample of what our full toolkit contains — policies, procedures, control templates, and evidence checklists tailored to your scope." primary="Explore the toolkits" onNav={onNav} dest="toolkits" />
  </window.Section>
);

/* ── NEWSLETTER ───────────────────────────────────────────── */
const RcNewsletter = ({ onNav }) => (
  <window.Section bg={RV.g50} pad="72px 0">
    <div style={{ maxWidth:760, margin:'0 auto', textAlign:'center' }}>
      <window.Overline style={{ marginBottom:14, justifyContent:'center', display:'flex' }}>Stay current</window.Overline>
      <h2 className="vg-section-title" style={{ fontSize: 36, fontWeight:800, letterSpacing:'-0.03em', color:RV.black, margin:'0 0 14px', fontFamily:RFT, lineHeight:1.1 }}>Compliance intelligence, delivered monthly.</h2>
      <p style={{ fontSize:17, color:RV.g600, lineHeight:1.65, margin:'0 0 28px' }}>Regulatory updates and practitioner notes — no marketing noise.</p>
      <window.Btn kind="primary" onClick={()=>onNav('contact')}>Subscribe to the newsletter <window.Icon name="arrow" size={16} color="#fff" /></window.Btn>
    </div>
  </window.Section>
);

/* ── PAGE ─────────────────────────────────────────────────── */
const ResourcesPage = ({ onNav }) => {
  const [downloadModal, setDownloadModal] = React.useState(null);
  const contactOk = () => { try { return !!sessionStorage.getItem('verigo_contact_ok'); } catch (e) { return false; } };

  const onDownload = (item) => {
    if (contactOk()) { window.RC_PDF.generate(item); }
    else { setDownloadModal(item); }
  };
  const onDownloadModalSubmit = (form) => {
    rcStoreLead({ ...form, source: 'resource-download', resource: downloadModal.title });
    try { sessionStorage.setItem('verigo_contact_ok', '1'); } catch (e) {}
    const item = downloadModal;
    setDownloadModal(null);
    setTimeout(() => window.RC_PDF.generate(item), 60);
  };

  return (
    <div>
      <RcHero />
      <RcArticles onNav={onNav} />
      <RcDownloads onNav={onNav} onDownload={onDownload} />
      <RcNewsletter onNav={onNav} />

      {/* Download gate modal */}
      {downloadModal && (
        <window.LeadCaptureModal
          icon={downloadModal.icon}
          eyebrow={`Free Download · ${downloadModal.format}`}
          heading={downloadModal.title}
          intro="Tell us where to send it and a practitioner will follow up with tailored guidance. Your PDF generates immediately."
          cta="Download free PDF"
          note="We'll only use your details to share the resource and follow up."
          onClose={() => setDownloadModal(null)}
          onSubmit={onDownloadModalSubmit} />
      )}
    </div>
  );
};

Object.assign(window, { ResourcesPage });
