// pns-case-page.jsx — case study detail page + structured data
const { useState: useCaseState, useEffect: useCaseEffect } = React;
const CT = window.PNST;
const CASES_DB = window.PNS_CASES || {};
const CASE_ORDER = window.PNS_CASE_ORDER || Object.keys(CASES_DB);
const C_SITE = (window.pnsWP && window.pnsWP.siteUrl) || '';
const cImg = (id, w) => (window.pnsWP?.images?.[id]) || `https://images.unsplash.com/photo-${id}?w=${w}&auto=format&fit=crop&q=80`;
const cUrl = (slug) => C_SITE ? `${C_SITE}case-studies/${slug}/` : `case-study.html?id=${slug}`;
const cPage = (slug) => C_SITE ? `${C_SITE}${slug}/` : ({services:'Services.html',portfolio:'Portfolio.html',contact:'Contact.html',pricing:'Pricing.html'})[slug];
const cService = (id) => (window.pnsWP?.serviceUrls?.[id]) || ((window.pnsWP?.serviceUrl || 'service.html') + '?id=' + id);

const CASE_SLUG = (() => {
  if (window.PNS_CASE_SLUG && CASES_DB[window.PNS_CASE_SLUG]) return window.PNS_CASE_SLUG;
  const q = new URLSearchParams(window.location.search).get('id');
  if (q && CASES_DB[q]) return q;
  const seg = window.location.pathname.split('/').filter(Boolean).pop();
  if (seg && CASES_DB[seg]) return seg;
  return CASE_ORDER[0];
})();

/* ── Structured data: Article + FAQPage + BreadcrumbList ────────── */
function injectCaseSchema(slug, cs) {
  const url = cUrl(slug);
  const base = C_SITE || '';
  const graph = [
    { '@type':'Article', headline: cs.title, description: cs.metaDesc,
      image: cImg(cs.heroImg, 1600), mainEntityOfPage: url, inLanguage:'en-US',
      keywords: cs.keywords, articleSection: cs.cat,
      author:{ '@type':'Organization', name:'Premier Network Solutions' },
      publisher:{ '@type':'Organization', name:'Premier Network Solutions', url: base || undefined } },
    { '@type':'BreadcrumbList', itemListElement:[
      { '@type':'ListItem', position:1, name:'Home', item: base || '/' },
      { '@type':'ListItem', position:2, name:'Case Studies', item: cPage('portfolio') },
      { '@type':'ListItem', position:3, name: cs.title, item: url },
    ]},
    { '@type':'FAQPage', mainEntity: cs.faqs.map(f => ({
      '@type':'Question', name: f.q,
      acceptedAnswer:{ '@type':'Answer', text: f.a } })) },
  ];
  const prev = document.getElementById('pns-case-schema');
  if (prev) prev.remove();
  const el = document.createElement('script');
  el.type = 'application/ld+json';
  el.id = 'pns-case-schema';
  el.textContent = JSON.stringify({ '@context':'https://schema.org', '@graph': graph });
  document.head.appendChild(el);
}
function setMeta(name, content, attr) {
  if (!content) return;
  let el = document.head.querySelector(`meta[${attr||'name'}="${name}"]`);
  if (!el) { el = document.createElement('meta'); el.setAttribute(attr||'name', name); document.head.appendChild(el); }
  el.setAttribute('content', content);
}

/* ── Pieces ─────────────────────────────────────────────────────── */
function CaseBreadcrumb({ cs }) {
  const link = { fontFamily:CT.bd, fontSize:12.5, color:'rgba(255,255,255,0.55)', textDecoration:'none', whiteSpace:'nowrap' };
  return (
    <nav aria-label="Breadcrumb" style={{ display:'flex', flexWrap:'wrap', alignItems:'center', gap:8, marginBottom:22 }}>
      <a href={C_SITE || 'Premier%20Network%20Solutions.html'} style={link}>Home</a>
      <span aria-hidden="true" style={{ color:'rgba(255,255,255,0.28)', fontSize:12 }}>/</span>
      <a href={cPage('portfolio')} style={link}>Case Studies</a>
      <span aria-hidden="true" style={{ color:'rgba(255,255,255,0.28)', fontSize:12 }}>/</span>
      <span style={{ ...link, color:CT.teal }}>{cs.cat}</span>
    </nav>
  );
}

function CaseHero({ cs }) {
  return (
    <section data-screen-label="Case Hero" className="pns-page-hero"
      style={{ background:CT.n900, padding:'142px 48px 80px', position:'relative', overflow:'hidden' }}>
      <div aria-hidden="true" style={{ position:'absolute', inset:0, backgroundImage:`url('${cImg(cs.heroImg,1600)}')`,
        backgroundSize:'cover', backgroundPosition:'center', opacity:0.16 }}/>
      <div aria-hidden="true" style={{ position:'absolute', top:'-24%', right:'-8%', width:480, height:480,
        background:'radial-gradient(circle, rgba(43,181,160,0.2) 0%, transparent 65%)', pointerEvents:'none' }}/>
      <div style={{ maxWidth:1240, margin:'0 auto', position:'relative' }}>
        <CaseBreadcrumb cs={cs}/>
        <div style={{ maxWidth:840 }}>
          <span style={{ display:'inline-flex', alignItems:'center', gap:8, fontFamily:CT.bd, fontSize:11.5,
            fontWeight:700, letterSpacing:'0.12em', textTransform:'uppercase', color:'#fff',
            background:cs.catColor, padding:'6px 14px', borderRadius:30, marginBottom:20 }}>{cs.cat}</span>
          <h1 style={{ fontFamily:CT.hd, fontWeight:900, fontSize:'clamp(29px,4.4vw,54px)', color:'#fff',
            lineHeight:1.07, letterSpacing:'-0.035em', margin:'0 0 22px', textWrap:'balance' }}>{cs.title}</h1>
          <p style={{ fontFamily:CT.bd, fontSize:16.5, color:'rgba(255,255,255,0.66)', lineHeight:1.78,
            margin:'0 0 32px', maxWidth:720, textWrap:'pretty' }}>{cs.summary}</p>
          <a href={cPage('contact')} style={{ background:CT.coral, color:'#fff', padding:'14px 28px', borderRadius:10,
            fontSize:14.5, fontWeight:700, textDecoration:'none', fontFamily:CT.bd, display:'inline-flex',
            alignItems:'center', minHeight:48, transition:'all 0.25s ease' }}
            onMouseEnter={e=>{e.currentTarget.style.background=CT.coralL; e.currentTarget.style.transform='translateY(-2px)';}}
            onMouseLeave={e=>{e.currentTarget.style.background=CT.coral; e.currentTarget.style.transform='translateY(0)';}}>
            Discuss a Similar Project →
          </a>
        </div>
      </div>
    </section>
  );
}

function CaseFacts({ cs }) {
  const rows = [
    ['Industry', cs.client.industry], ['Scale', cs.client.size],
    ['Region', cs.client.region], ['Engagement', cs.client.engagement],
  ];
  return (
    <section style={{ background:CT.n800, padding:'0 48px' }}>
      <div style={{ maxWidth:1240, margin:'0 auto' }}>
        <dl style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:0, margin:0,
          borderTop:'1px solid rgba(255,255,255,0.08)' }} className="pns-grid-resp">
          {rows.map(([k,v]) => (
            <div key={k} style={{ padding:'26px 24px 28px', borderRight:'1px solid rgba(255,255,255,0.08)' }}>
              <dt style={{ fontFamily:CT.bd, fontSize:10.5, fontWeight:700, letterSpacing:'0.12em',
                textTransform:'uppercase', color:CT.teal, marginBottom:9 }}>{k}</dt>
              <dd style={{ fontFamily:CT.bd, fontSize:14, color:'rgba(255,255,255,0.8)', lineHeight:1.55, margin:0 }}>{v}</dd>
            </div>
          ))}
        </dl>
      </div>
    </section>
  );
}

function CaseProse({ cs }) {
  const h2 = { fontFamily:CT.hd, fontWeight:800, fontSize:'clamp(25px,3vw,38px)', color:CT.g900,
    letterSpacing:'-0.03em', lineHeight:1.14, margin:'0 0 22px', textWrap:'balance' };
  const p = { fontFamily:CT.bd, fontSize:16, color:CT.g500, lineHeight:1.82, margin:'0 0 18px', textWrap:'pretty' };
  return (
    <section style={{ background:CT.white, padding:'96px 48px' }}>
      <div style={{ maxWidth:1240, margin:'0 auto', display:'grid', gridTemplateColumns:'1fr 1fr',
        gap:72, alignItems:'start' }} className="pns-split">
        <div className="pns-fade-up">
          <h2 style={h2}>The Challenge</h2>
          {cs.challenge.map((t,i) => <p key={i} style={p}>{t}</p>)}
        </div>
        <div className="pns-slide-right">
          <div style={{ borderRadius:20, overflow:'hidden', boxShadow:'0 20px 60px rgba(12,30,50,0.14)' }}>
            <img src={cImg(cs.bodyImg,900)} alt={cs.bodyAlt} loading="lazy" width="900" height="600"
              style={{ width:'100%', height:400, objectFit:'cover', display:'block' }}/>
          </div>
        </div>
      </div>
      <div style={{ maxWidth:900, margin:'88px auto 0' }} className="pns-fade-up">
        <h2 style={h2}>The Solution</h2>
        <div style={{ display:'flex', flexDirection:'column', gap:34, marginTop:34 }}>
          {cs.solution.map((s,i) => (
            <article key={i} style={{ display:'grid', gridTemplateColumns:'46px 1fr', gap:20, alignItems:'start' }}>
              <span aria-hidden="true" style={{ fontFamily:CT.hd, fontWeight:800, fontSize:15, color:'#fff',
                background:CT.n800, width:46, height:46, borderRadius:12, display:'flex',
                alignItems:'center', justifyContent:'center' }}>{String(i+1).padStart(2,'0')}</span>
              <div>
                <h3 style={{ fontFamily:CT.hd, fontWeight:700, fontSize:19, color:CT.g900,
                  letterSpacing:'-0.015em', margin:'8px 0 10px' }}>{s.h}</h3>
                <p style={{ ...p, margin:0, fontSize:15.5 }}>{s.p}</p>
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

function CaseResults({ cs }) {
  return (
    <section style={{ background:CT.n900, padding:'92px 48px', position:'relative', overflow:'hidden' }}>
      <div aria-hidden="true" style={{ position:'absolute', top:'-18%', left:'-6%', width:420, height:420,
        background:'radial-gradient(circle, rgba(232,113,74,0.13) 0%, transparent 65%)', pointerEvents:'none' }}/>
      <div style={{ maxWidth:1240, margin:'0 auto', position:'relative' }}>
        <div className="pns-fade-up" style={{ marginBottom:48, maxWidth:640 }}>
          <span style={{ display:'inline-flex', fontFamily:CT.bd, fontSize:11.5, fontWeight:700,
            letterSpacing:'0.12em', textTransform:'uppercase', color:CT.teal, whiteSpace:'nowrap',
            background:'rgba(43,181,160,0.12)', border:'1px solid rgba(43,181,160,0.32)',
            padding:'6px 14px', borderRadius:30, marginBottom:18 }}>Measured Outcomes</span>
          <h2 style={{ fontFamily:CT.hd, fontWeight:800, fontSize:'clamp(25px,3vw,38px)', color:'#fff',
            letterSpacing:'-0.03em', lineHeight:1.14, margin:0, textWrap:'balance' }}>The Results</h2>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:18 }} className="pns-grid-resp">
          {cs.results.map((r,i) => (
            <div key={i} className={`pns-fade-up pns-d${i%3+1}`}
              style={{ background:'rgba(255,255,255,0.045)', border:'1px solid rgba(255,255,255,0.09)',
                borderRadius:16, padding:'28px 24px 26px' }}>
              <div style={{ fontFamily:CT.hd, fontWeight:900, fontSize:'clamp(32px,3.2vw,46px)', color:'#fff',
                lineHeight:1, letterSpacing:'-0.04em', marginBottom:10 }}>
                {r.n}<span style={{ fontSize:'0.5em', color:CT.teal }}>{r.s}</span>
              </div>
              <div style={{ fontFamily:CT.hd, fontWeight:700, fontSize:13.5, color:'#fff', marginBottom:8 }}>{r.l}</div>
              <p style={{ fontFamily:CT.bd, fontSize:12.5, color:'rgba(255,255,255,0.42)', lineHeight:1.6, margin:0 }}>{r.d}</p>
            </div>
          ))}
        </div>
        <figure style={{ margin:'56px 0 0', maxWidth:820 }} className="pns-fade-up">
          <blockquote style={{ margin:0, fontFamily:CT.hd, fontWeight:600, fontSize:'clamp(18px,2.1vw,25px)',
            color:'#fff', lineHeight:1.5, letterSpacing:'-0.02em', textWrap:'pretty',
            borderLeft:`3px solid ${CT.coral}`, paddingLeft:26 }}>“{cs.quote.t}”</blockquote>
          <figcaption style={{ fontFamily:CT.bd, fontSize:13, color:'rgba(255,255,255,0.45)',
            marginTop:18, paddingLeft:29 }}>{cs.quote.a} · {cs.quote.c}</figcaption>
        </figure>
      </div>
    </section>
  );
}

function CaseTech({ cs }) {
  return (
    <section style={{ background:CT.g50, padding:'80px 48px' }}>
      <div style={{ maxWidth:1000, margin:'0 auto' }} className="pns-fade-up">
        <h2 style={{ fontFamily:CT.hd, fontWeight:800, fontSize:'clamp(23px,2.6vw,32px)', color:CT.g900,
          letterSpacing:'-0.03em', margin:'0 0 26px' }}>Technologies Deployed</h2>
        <ul style={{ display:'flex', flexWrap:'wrap', gap:10, listStyle:'none', padding:0, margin:0 }}>
          {cs.tech.map(t => (
            <li key={t} style={{ fontFamily:CT.bd, fontSize:13.5, color:CT.g700, background:CT.white,
              border:`1px solid ${CT.g200}`, borderRadius:30, padding:'9px 18px' }}>{t}</li>
          ))}
        </ul>
      </div>
    </section>
  );
}

function CaseFaqs({ cs }) {
  const [open, setOpen] = useCaseState(0);
  return (
    <section style={{ background:CT.white, padding:'92px 48px' }}>
      <div style={{ maxWidth:880, margin:'0 auto' }}>
        <h2 className="pns-fade-up" style={{ fontFamily:CT.hd, fontWeight:800, fontSize:'clamp(25px,3vw,38px)',
          color:CT.g900, letterSpacing:'-0.03em', margin:'0 0 34px', textWrap:'balance' }}>
          Questions About This Project
        </h2>
        <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
          {cs.faqs.map((f,i) => {
            const isOpen = open === i;
            return (
              <div key={i} style={{ border:`1px solid ${isOpen?CT.teal:CT.g200}`, borderRadius:12,
                background:isOpen?'rgba(43,181,160,0.035)':CT.white, transition:'border-color 0.2s ease' }}>
                <button onClick={()=>setOpen(isOpen?null:i)} aria-expanded={isOpen}
                  style={{ width:'100%', display:'flex', alignItems:'center', gap:14, background:'none',
                    border:'none', cursor:'pointer', padding:'20px 22px', textAlign:'left', minHeight:44 }}>
                  <span aria-hidden="true" style={{ flexShrink:0, width:24, height:24, borderRadius:'50%',
                    background:isOpen?CT.teal:CT.g200, color:isOpen?'#fff':CT.g700, display:'flex',
                    alignItems:'center', justifyContent:'center', fontSize:15, fontFamily:CT.bd,
                    fontWeight:700, lineHeight:1, transition:'all 0.2s ease' }}>{isOpen?'−':'+'}</span>
                  <h3 style={{ fontFamily:CT.hd, fontWeight:600, fontSize:16, color:CT.g900,
                    margin:0, letterSpacing:'-0.01em', lineHeight:1.4 }}>{f.q}</h3>
                </button>
                {isOpen && (
                  <p className="pns-faq-answer" style={{ fontFamily:CT.bd, fontSize:15, lineHeight:1.78,
                    color:CT.g500, margin:0, padding:'0 22px 22px 60px', textWrap:'pretty' }}>{f.a}</p>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

const SERVICE_LABELS = {
  'managed-it':'Managed IT Services','cybersecurity':'Cybersecurity','microsoft-365':'Microsoft 365',
  'network-infrastructure':'Network Infrastructure','ai-solutions':'AI Solutions',
  'backup-monitoring':'Backup & Monitoring','it-consulting':'IT Consulting',
  'web-development':'Web Development','seo-services':'SEO Services',
};

function CaseNext({ slug, cs }) {
  const others = CASE_ORDER.filter(s => s !== slug).slice(0,3);
  return (
    <section style={{ background:CT.g50, padding:'88px 48px' }}>
      <div style={{ maxWidth:1240, margin:'0 auto' }}>
        <div className="pns-fade-up" style={{ marginBottom:30 }}>
          <h2 style={{ fontFamily:CT.hd, fontWeight:800, fontSize:'clamp(22px,2.5vw,30px)', color:CT.g900,
            letterSpacing:'-0.03em', margin:'0 0 10px' }}>Services Behind This Project</h2>
        </div>
        <ul style={{ display:'flex', flexWrap:'wrap', gap:10, listStyle:'none', padding:0, margin:'0 0 64px' }}>
          {cs.related.map(id => (
            <li key={id}>
              <a href={cService(id)} style={{ display:'inline-flex', alignItems:'center', minHeight:44,
                fontFamily:CT.bd, fontSize:14, fontWeight:600, color:CT.g700, background:CT.white,
                border:`1px solid ${CT.g200}`, borderRadius:10, padding:'12px 20px', textDecoration:'none',
                transition:'all 0.2s ease' }}
                onMouseEnter={e=>{e.currentTarget.style.borderColor=CT.coral; e.currentTarget.style.color=CT.coral;}}
                onMouseLeave={e=>{e.currentTarget.style.borderColor=CT.g200; e.currentTarget.style.color=CT.g700;}}>
                {SERVICE_LABELS[id] || id} →
              </a>
            </li>
          ))}
        </ul>
        <h2 className="pns-fade-up" style={{ fontFamily:CT.hd, fontWeight:800, fontSize:'clamp(22px,2.5vw,30px)',
          color:CT.g900, letterSpacing:'-0.03em', margin:'0 0 26px' }}>More Case Studies</h2>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:20 }} className="pns-grid-resp">
          {others.map(s => {
            const o = CASES_DB[s];
            return (
              <a key={s} href={cUrl(s)} className="pns-fade-up"
                style={{ background:CT.white, border:`1px solid ${CT.g200}`, borderRadius:16,
                  overflow:'hidden', textDecoration:'none', display:'block', transition:'all 0.28s ease' }}
                onMouseEnter={e=>{e.currentTarget.style.transform='translateY(-5px)'; e.currentTarget.style.boxShadow='0 18px 44px rgba(12,30,50,0.13)';}}
                onMouseLeave={e=>{e.currentTarget.style.transform='translateY(0)'; e.currentTarget.style.boxShadow='none';}}>
                <img src={cImg(o.heroImg,600)} alt={o.heroAlt} loading="lazy" width="600" height="400"
                  style={{ width:'100%', height:170, objectFit:'cover', display:'block' }}/>
                <div style={{ padding:'20px 22px 24px' }}>
                  <span style={{ fontFamily:CT.bd, fontSize:10.5, fontWeight:700, letterSpacing:'0.1em',
                    textTransform:'uppercase', color:o.catColor }}>{o.cat}</span>
                  <h3 style={{ fontFamily:CT.hd, fontWeight:700, fontSize:16.5, color:CT.g900,
                    letterSpacing:'-0.02em', lineHeight:1.34, margin:'10px 0 0', textWrap:'pretty' }}>{o.title}</h3>
                </div>
              </a>
            );
          })}
        </div>
      </div>
    </section>
  );
}

function CaseCTA() {
  return (
    <section style={{ background:CT.n800, padding:'84px 48px', textAlign:'center' }}>
      <div style={{ maxWidth:660, margin:'0 auto' }} className="pns-fade-up">
        <h2 style={{ fontFamily:CT.hd, fontWeight:800, fontSize:'clamp(24px,3vw,38px)', color:'#fff',
          letterSpacing:'-0.03em', lineHeight:1.16, margin:'0 0 16px', textWrap:'balance' }}>
          Facing something similar?
        </h2>
        <p style={{ fontFamily:CT.bd, fontSize:16, color:'rgba(255,255,255,0.6)', lineHeight:1.75,
          margin:'0 0 30px', textWrap:'pretty' }}>
          Tell us where your technology stands today. A senior engineer will walk through the options with you — no sales script.
        </p>
        <div style={{ display:'flex', gap:12, justifyContent:'center', flexWrap:'wrap' }}>
          <a href={cPage('contact')} style={{ background:CT.coral, color:'#fff', padding:'14px 28px',
            borderRadius:10, fontSize:14.5, fontWeight:700, textDecoration:'none', fontFamily:CT.bd,
            display:'inline-flex', alignItems:'center', minHeight:48 }}>Book a Consultation →</a>
          <a href={cPage('services')} style={{ background:'transparent', color:'#fff', padding:'13px 26px',
            borderRadius:10, fontSize:14.5, fontWeight:600, textDecoration:'none', fontFamily:CT.bd,
            border:'1.5px solid rgba(255,255,255,0.22)', display:'inline-flex', alignItems:'center', minHeight:48 }}>
            Explore Our Services
          </a>
        </div>
      </div>
    </section>
  );
}

/* ── Page ───────────────────────────────────────────────────────── */
function PNSCasePage() {
  const cs = CASES_DB[CASE_SLUG];
  useCaseEffect(() => {
    if (!cs) return;
    document.title = cs.metaTitle;
    setMeta('description', cs.metaDesc);
    setMeta('keywords', cs.keywords);
    setMeta('og:title', cs.metaTitle, 'property');
    setMeta('og:description', cs.metaDesc, 'property');
    setMeta('og:type', 'article', 'property');
    setMeta('og:image', cImg(cs.heroImg,1600), 'property');
    setMeta('twitter:card', 'summary_large_image');
    let link = document.head.querySelector('link[rel="canonical"]');
    if (!link) { link = document.createElement('link'); link.rel = 'canonical'; document.head.appendChild(link); }
    link.href = cUrl(CASE_SLUG);
    injectCaseSchema(CASE_SLUG, cs);
    const timer = setTimeout(() => {
      const ob = new IntersectionObserver(es => es.forEach(e => {
        if (e.isIntersecting) { e.target.classList.add('visible'); ob.unobserve(e.target); }
      }), { threshold:0.12, rootMargin:'0px 0px -50px 0px' });
      document.querySelectorAll('.pns-fade-up,.pns-slide-left,.pns-slide-right,.pns-zoom-in').forEach(el => ob.observe(el));
    }, 250);
    return () => clearTimeout(timer);
  }, [cs]);

  const Nav = window.PNSNav, Footer = window.PNSFooter;
  if (!cs) return <div style={{ padding:'160px 48px', textAlign:'center', fontFamily:CT.bd }}>Case study not found.</div>;
  return (
    <div style={{ overflowX:'hidden' }}>
      {Nav ? <Nav/> : null}
      <main>
        <CaseHero cs={cs}/>
        <CaseFacts cs={cs}/>
        <CaseProse cs={cs}/>
        <CaseResults cs={cs}/>
        <CaseTech cs={cs}/>
        <CaseFaqs cs={cs}/>
        <CaseNext slug={CASE_SLUG} cs={cs}/>
        <CaseCTA/>
      </main>
      {Footer ? <Footer/> : null}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('app')).render(<PNSCasePage/>);
