/* GCCReady — Skill Badge product (interactive 10-Q assessment + shareable credential)
 * Route: /skill-badge/take
 *
 * Flow:
 *   1. Hero + name input (no signup wall)
 *   2. 10 branching questions with progress bar
 *   3. Score + Level (L1/L2/L3) + recommended Cert + recommended Role + matched GCCs
 *   4. Credential card with PNG download (canvas) + LinkedIn / WhatsApp / Email share
 *   5. Email-my-plan form (writes to gr_user_ctx so static tools auto-prefill)
 */

const SB_QUESTIONS = [
  { id:'name',    type:'text',
    title:"Let's get you a Skill Badge.",
    sub:'Your name goes on the credential — make it the one you use professionally.',
    label:'Your full name',
  },
  { id:'degree',  type:'choice',
    title:'Where are you in your degree?',
    sub:'Used to calibrate cohort + cert recommendations.',
    options: [
      { v:'12th',     l:'Class 12 / PUC',                   wt:0 },
      { v:'ug-12',    l:'UG year 1–2',                      wt:1 },
      { v:'ug-final', l:'UG final year',                    wt:2 },
      { v:'graduated',l:'Graduated',                        wt:2 },
      { v:'pg',       l:'PG / MBA',                         wt:2 },
      { v:'ca',       l:'CA / CA Inter (ICAI)',             wt:3 },
    ],
  },
  { id:'stream', type:'choice',
    title:'Your degree stream',
    sub:'',
    options: [
      { v:'commerce', l:'Commerce · BCom · BBA · MCom', wt:2 },
      { v:'ca',       l:'CA / Accountancy',             wt:3 },
      { v:'eng',      l:'Engineering · CS / IT',        wt:2 },
      { v:'science',  l:'Science · Statistics · Maths', wt:1 },
      { v:'arts',     l:'Arts / Humanities (other)',    wt:0 },
    ],
  },
  { id:'target', type:'choice',
    title:'What kind of GCC role do you want?',
    sub:'Pick what excites you, not what you\'ve done before.',
    options: [
      { v:'fa',     l:'Finance ops · FP&A · accounting', wt:2 },
      { v:'tax',    l:'US tax / India tax',               wt:2 },
      { v:'risk',   l:'Risk · audit · compliance',        wt:2 },
      { v:'data',   l:'Data · analytics · AI',            wt:2 },
      { v:'ops',    l:'Marketing · CX · general ops',     wt:1 },
      { v:'unsure', l:'Unsure — help me pick',            wt:1 },
    ],
  },
  { id:'timeline', type:'choice',
    title:'How soon do you need a job?',
    sub:'',
    options: [
      { v:'3',  l:'Within 3 months', wt:0 },
      { v:'6',  l:'3–6 months',      wt:1 },
      { v:'12', l:'6–12 months',     wt:2 },
      { v:'24', l:'12+ months — happy to invest in a cert first', wt:3 },
    ],
  },
  { id:'tools', type:'choice',
    title:'Which tools have you used?',
    sub:'Pick the deepest level you\'re comfortable with.',
    options: [
      { v:'none',  l:'None / basic Office',              wt:0 },
      { v:'excel', l:'Advanced Excel',                    wt:1 },
      { v:'bi',    l:'Power BI / Tableau / SQL',          wt:2 },
      { v:'py',    l:'Python / R',                        wt:3 },
      { v:'ai',    l:'Gen AI (Copilot / ChatGPT) regularly', wt:3 },
    ],
  },
  { id:'english', type:'choice',
    title:'English fluency at work',
    sub:'GCCs work primarily in English. Be honest — we calibrate the role pod accordingly.',
    options: [
      { v:'limited',     l:'Limited — better at writing than speaking',  wt:0 },
      { v:'comfortable', l:'Comfortable in 1:1 conversations',           wt:1 },
      { v:'fluent',      l:'Fluent — can present + write at work level', wt:2 },
      { v:'native',      l:'Near-native — used English through schooling', wt:3 },
    ],
  },
  { id:'experience', type:'choice',
    title:'Any internship or work experience?',
    sub:'',
    options: [
      { v:'none',     l:'No — first job hunt',           wt:0 },
      { v:'1-3',      l:'1–3 months internship',         wt:1 },
      { v:'6+',       l:'6+ months internship / articleship', wt:2 },
      { v:'fulltime', l:'1+ years full-time elsewhere',  wt:3 },
    ],
  },
  { id:'city', type:'choice',
    title:'Preferred work city',
    sub:'',
    options: [
      { v:'bengaluru', l:'Bengaluru', wt:1 },
      { v:'hyderabad', l:'Hyderabad', wt:1 },
      { v:'mumbai',    l:'Mumbai',    wt:1 },
      { v:'pune',      l:'Pune',      wt:1 },
      { v:'gurgaon',   l:'Gurgaon / Delhi NCR', wt:1 },
      { v:'chennai',   l:'Chennai',   wt:1 },
      { v:'kolkata',   l:'Kolkata',   wt:1 },
      { v:'flexible',  l:'Flexible — pick what gets me hired fastest', wt:2 },
    ],
  },
  { id:'commit', type:'choice',
    title:'Hours per week you can study',
    sub:'',
    options: [
      { v:'5',   l:'≤ 5 hours',  wt:0 },
      { v:'10',  l:'6–10 hours', wt:1 },
      { v:'15',  l:'11–15 hours',wt:2 },
      { v:'20',  l:'16–20 hours',wt:3 },
      { v:'25',  l:'20+ hours — I\'m committing seriously', wt:3 },
    ],
  },
];

function _grBadgeId() {
  return 'GR-' + Math.random().toString(36).slice(2, 8).toUpperCase() + '-' + Date.now().toString(36).slice(-4).toUpperCase();
}

function _grRecommend(answers) {
  const { degree, stream, target, timeline, tools, english, experience, city, commit } = answers;

  // Score → level
  let score = 0;
  const tally = (key) => {
    const q = SB_QUESTIONS.find((x) => x.id === key);
    if (!q || !q.options) return 0;
    const opt = q.options.find((o) => o.v === answers[key]);
    return opt ? opt.wt : 0;
  };
  ['degree','stream','tools','english','experience','commit','timeline','target'].forEach((k) => { score += tally(k); });
  let level = 'L1';
  let levelBlurb = 'Foundations — bridge gaps before interviewing. Start with the Crash Course or Skill Readiness.';
  if (score >= 14) { level = 'L3'; levelBlurb = 'Interview-ready. Apply to Sprint placement track + start cert prep in parallel.'; }
  else if (score >= 8) { level = 'L2'; levelBlurb = 'Bridge gap with a 6-week role pod + tool stack, then interview.'; }

  // Cert recommendation
  let cert = 'us-cma';
  if (target === 'tax')        cert = 'ea';
  else if (target === 'risk')  cert = stream === 'ca' ? 'us-cpa' : 'us-cma';
  else if (target === 'fa')    cert = stream === 'ca' ? 'us-cpa' : 'us-cma';
  else if (target === 'data')  cert = 'power-bi';
  else if (target === 'ops')   cert = 'us-cma';
  else cert = 'us-cma';
  if (stream === 'eng' && target === 'data') cert = 'power-bi';
  if (stream === 'eng' && target !== 'data') cert = 'us-cma'; // pivot path

  // Role pod
  let role = 'fa-ops';
  if (target === 'tax') role = 'tax';
  else if (target === 'risk') role = 'audit-sox';
  else if (target === 'fa') role = 'fpa';
  else if (target === 'data') role = 'data-analytics';
  else if (target === 'ops') role = 'ai-marketing';

  // Salary band by level + city
  const cityMult = { 'bengaluru':1.05, 'mumbai':1.10, 'hyderabad':1.00, 'pune':0.95, 'chennai':0.95, 'gurgaon':1.05, 'kolkata':0.85, 'flexible':1.0 }[city] || 1.0;
  const baseLow = level === 'L3' ? 7 : level === 'L2' ? 5 : 3.5;
  const baseHigh = level === 'L3' ? 14 : level === 'L2' ? 9 : 6;
  const ctcLow = (baseLow * cityMult).toFixed(1);
  const ctcHigh = (baseHigh * cityMult).toFixed(1);

  // Matched GCCs
  const r = (typeof GR_ROLES !== 'undefined') ? GR_ROLES.find((x) => x.slug === role) : null;
  const employerSlugs = (r && r.employers ? r.employers : ['amazon','microsoft','deloitte','ey','jpmorganchase']).slice(0, 5);

  return {
    score, level, levelBlurb, cert, role,
    ctcLow, ctcHigh,
    employerSlugs,
    badgeId: _grBadgeId(),
    issuedDate: new Date().toLocaleDateString('en-IN', { day:'2-digit', month:'short', year:'numeric' }),
  };
}

function SkillBadgeAssessPage() {
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({});
  const [name, setName] = React.useState('');
  const [result, setResult] = React.useState(null);

  const total = SB_QUESTIONS.length;
  const progress = Math.min(100, Math.round((step / total) * 100));

  const onAnswer = (id, val) => {
    const next = { ...answers, [id]: val };
    setAnswers(next);
    if (step < total - 1) setStep(step + 1);
    else {
      const r = _grRecommend(next);
      setResult(r);
      // Persist for the value-cascade bridge
      try {
        localStorage.setItem('gr_user_ctx', JSON.stringify({
          name: name || 'Candidate',
          ...next,
          ...r,
          ts_completed: new Date().toISOString(),
        }));
      } catch (_) {}
    }
  };

  const handleNameNext = () => {
    if (!name.trim()) return;
    setAnswers({ ...answers, name });
    setStep(1);
  };

  return (
    <>
      <PageHead
        title="Skill Badge — Free 5-minute GCC Readiness Assessment"
        description="Free Skill Badge assessment: 10 questions → L1/L2/L3 readiness + recommended cert (CPA/CMA/EA/CFA/ACCA) + role pod + named GCCs hiring + a shareable credential card you can post on LinkedIn."
        canonical="/skill-badge/take"
        schema={[
          schemaService({ name:'GCCReady Skill Badge', description:'Free interactive readiness assessment with shareable credential.', slug:'/skill-badge/take', serviceType:'EducationalAssessment' }),
          schemaBreadcrumb([{label:'Home',href:'/'},{label:'Skill Badge',href:'/skill-badge'},{label:'Take',href:'/skill-badge/take'}]),
        ]}
      />
      <HeroDark>
        <div style={{maxWidth:780}}>
          <Crumbs items={[{label:'Skill Badge',href:'#/skill-badge'},{label:'Take the assessment'}]}/>
          <h1 className="gr-h1" style={{color:'#fff', marginTop:18, fontSize:54}}>Your Skill Badge.</h1>
          <p className="gr-lead" style={{color:'rgba(255,255,255,.78)', marginTop:14, maxWidth:680}}>
            10 questions · 5 minutes. You'll get a verified L1/L2/L3 readiness level, a recommended certification path, a role pod, named GCCs hiring for your profile, and a shareable credential card.
          </p>
        </div>
      </HeroDark>

      <section className="gr-section" style={{padding:'56px 0 80px'}}>
        <div className="gr-container" style={{maxWidth:780}}>
          {result ? (
            <SkillBadgeResult name={name || 'Candidate'} answers={answers} result={result}/>
          ) : step === 0 ? (
            <div className="gr-card" style={{padding:36}}>
              <div style={{font:'700 11.5px/1 Inter', color:'var(--gr-gold-700)', letterSpacing:'.14em', textTransform:'uppercase'}}>Step 1 of {total}</div>
              <h2 className="gr-h2" style={{fontSize:28, marginTop:8}}>{SB_QUESTIONS[0].title}</h2>
              <p className="gr-p" style={{marginTop:8}}>{SB_QUESTIONS[0].sub}</p>
              <label style={{display:'block', marginTop:18, font:'700 12.5px/1 Inter', color:'var(--gr-fg-1)'}}>{SB_QUESTIONS[0].label}</label>
              <input value={name} onChange={(e)=>setName(e.target.value)}
                placeholder="e.g. Aarti Krishnan"
                onKeyDown={(e)=>{ if (e.key === 'Enter') handleNameNext(); }}
                style={{
                  width:'100%', marginTop:10, padding:'14px 16px',
                  font:'500 16px/1.4 Inter',
                  border:'1.5px solid var(--gr-border)', borderRadius:12, background:'#fff',
                }}/>
              <button onClick={handleNameNext} className="gr-btn gr-btn-gold gr-btn-lg" style={{marginTop:18}} disabled={!name.trim()}>
                Continue <Icon name="arrow-right" size={16}/>
              </button>
            </div>
          ) : (
            <>
              <div style={{height:6, background:'var(--gr-bg-tint)', borderRadius:999, overflow:'hidden', marginBottom:24}}>
                <div style={{width:`${progress}%`, height:'100%', background:'var(--gr-grad-gold)', transition:'width .3s ease'}}/>
              </div>
              <SBQuestionCard
                q={SB_QUESTIONS[step]}
                step={step + 1}
                total={total}
                onPick={(v) => onAnswer(SB_QUESTIONS[step].id, v)}
                onBack={() => step > 1 && setStep(step - 1)}
              />
            </>
          )}
        </div>
      </section>
    </>
  );
}

function SBQuestionCard({ q, step, total, onPick, onBack }) {
  return (
    <div className="gr-card" style={{padding:36}}>
      <div style={{display:'flex', alignItems:'center', justifyContent:'space-between'}}>
        <div style={{font:'700 11.5px/1 Inter', color:'var(--gr-gold-700)', letterSpacing:'.14em', textTransform:'uppercase'}}>Step {step} of {total}</div>
        {onBack && step > 1 && (
          <button onClick={onBack} style={{background:'none', border:'none', cursor:'pointer', font:'600 12.5px/1 Inter', color:'var(--gr-fg-3)'}}>
            <Icon name="chevron-right" size={12} style={{transform:'rotate(180deg)', verticalAlign:'-2px', marginRight:4}}/> Back
          </button>
        )}
      </div>
      <h2 className="gr-h2" style={{fontSize:28, marginTop:8}}>{q.title}</h2>
      {q.sub && <p className="gr-p" style={{marginTop:8}}>{q.sub}</p>}
      <div style={{marginTop:22, display:'flex', flexDirection:'column', gap:10}}>
        {q.options.map((o) => (
          <button key={o.v} onClick={()=>onPick(o.v)} style={{
            padding:'18px 22px', textAlign:'left', cursor:'pointer',
            border:'1.5px solid var(--gr-border)', borderRadius:14,
            background:'#fff', font:'600 15.5px/1.4 Inter', color:'var(--gr-navy)',
            display:'flex', justifyContent:'space-between', alignItems:'center',
            transition:'all .15s ease',
          }}
          onMouseEnter={(ev)=>{ ev.currentTarget.style.borderColor='var(--gr-gold)'; ev.currentTarget.style.background='var(--gr-gold-50)'; }}
          onMouseLeave={(ev)=>{ ev.currentTarget.style.borderColor='var(--gr-border)'; ev.currentTarget.style.background='#fff'; }}>
            <span>{o.l}</span>
            <Icon name="arrow-right" size={16} style={{color:'var(--gr-gold-700)'}}/>
          </button>
        ))}
      </div>
    </div>
  );
}

/* ============================================================================
 * Result UI — credential card + share + email-my-plan
 * ========================================================================== */
function SkillBadgeResult({ name, answers, result }) {
  const cert = (typeof CERT_PILLAR !== 'undefined' && CERT_PILLAR[result.cert]) || { name: result.cert.toUpperCase(), tagline:'Pathway, fees, salary, GCCs hiring.' };
  const role = (typeof GR_ROLES !== 'undefined' ? GR_ROLES.find((r) => r.slug === result.role) : null) || { title: result.role, salary: '—', does:'' };
  const employers = result.employerSlugs.map((s) => (typeof GR_EMPLOYERS !== 'undefined' ? GR_EMPLOYERS[s] : null)).filter(Boolean);

  return (
    <>
      <BadgeCard name={name} result={result} cert={cert} role={role}/>
      <BadgeShareRow name={name} result={result}/>
      <div className="gr-card" style={{padding:28, marginTop:20, display:'grid', gridTemplateColumns:'1fr 1fr', gap:18}}>
        <a href={`#/certifications/${result.cert}`} style={resultPanel}>
          <div className="gr-eyebrow" style={{color:'var(--gr-gold-700)'}}>Recommended cert</div>
          <h3 className="gr-h3" style={{fontSize:22, marginTop:6}}>{cert.name}</h3>
          <p className="gr-p" style={{marginTop:8, fontSize:13.5}}>{cert.tagline || cert.hero_sub || ''}</p>
          <div style={{font:'700 13px/1 Inter', color:'var(--gr-gold-700)', marginTop:10}}>See pathway →</div>
        </a>
        <a href={`#/role/${result.role}`} style={resultPanel}>
          <div className="gr-eyebrow" style={{color:'var(--gr-gold-700)'}}>Recommended role pod</div>
          <h3 className="gr-h3" style={{fontSize:22, marginTop:6}}>{role.title}</h3>
          <p className="gr-p" style={{marginTop:8, fontSize:13.5}}>{role.does}</p>
          <div style={{font:'700 13px/1 "DM Sans"', color:'var(--gr-navy)', marginTop:6}}>{role.salary}</div>
          <div style={{font:'700 13px/1 Inter', color:'var(--gr-gold-700)', marginTop:10}}>See role pod →</div>
        </a>
      </div>

      {employers.length > 0 && (
        <div className="gr-card" style={{padding:28, marginTop:18}}>
          <div className="gr-eyebrow" style={{color:'var(--gr-gold-700)'}}>5 GCCs hiring for your profile</div>
          <div style={{marginTop:14, display:'grid', gridTemplateColumns:'repeat(5, 1fr)', gap:12}}>
            {employers.map((e, i) => {
              const slug = result.employerSlugs[i];
              return (
                <a key={slug} href={`#/gcc/${slug}`} style={{textDecoration:'none', color:'var(--gr-fg-1)', textAlign:'center', display:'flex', flexDirection:'column', alignItems:'center', gap:8}}>
                  <div style={{width:64, height:64, borderRadius:14, background:'#fff', border:'1px solid var(--gr-border-soft)', display:'grid', placeItems:'center', padding:8, overflow:'hidden'}}>
                    <img src={grLogoUrl(e.domain, 128)} alt={e.name}
                      onError={(ev)=>{ ev.target.src = grLogoFallback(e.domain, 128); ev.target.onerror = null; }}
                      style={{maxWidth:'100%', maxHeight:'100%', objectFit:'contain'}}/>
                  </div>
                  <div style={{font:'700 12px/1.2 "DM Sans"', color:'var(--gr-navy)'}}>{e.name}</div>
                </a>
              );
            })}
          </div>
        </div>
      )}

      <EmailMyPlan name={name} result={result}/>

      <div style={{marginTop:24, display:'flex', gap:12, flexWrap:'wrap', justifyContent:'center'}}>
        <a href="#/sprint" className="gr-btn gr-btn-gold gr-btn-lg">Apply to Sprint <Icon name="arrow-right" size={14}/></a>
        <a href={`#/contact?intent=skill-badge&cert=${result.cert}&role=${result.role}&level=${result.level}`} className="gr-btn gr-btn-ghost gr-btn-lg">Talk to an advisor</a>
      </div>
    </>
  );
}

const resultPanel = {
  display:'block', padding:22, borderRadius:16,
  background:'var(--gr-bg-cream)', border:'1px solid var(--gr-border-soft)',
  textDecoration:'none', color:'var(--gr-fg-1)',
};

/* ============================================================================
 * BadgeCard — visual credential, also rendered to a downloadable PNG
 * ========================================================================== */
function BadgeCard({ name, result, cert, role }) {
  const cardRef = React.useRef(null);
  return (
    <>
      <div ref={cardRef}
        style={{
          background:'var(--gr-grad-skillbadge, linear-gradient(135deg, #0D1B2A 0%, #1E3551 60%, #0D1B2A 100%))',
          color:'#fff', borderRadius:24, padding:36,
          boxShadow:'0 36px 80px -24px rgba(0,0,0,.45)',
          position:'relative', overflow:'hidden',
        }}>
        <div style={{position:'absolute', right:-80, top:-80, width:300, height:300,
          background:'radial-gradient(circle, rgba(245,158,11,.28) 0%, transparent 65%)'}}/>
        <div style={{position:'relative', display:'grid', gridTemplateColumns:'1.4fr 1fr', gap:30}}>
          <div>
            <div style={{display:'flex', alignItems:'center', gap:10, color:'rgba(255,255,255,.6)', font:'700 11px/1 Inter', letterSpacing:'.16em', textTransform:'uppercase'}}>
              <span style={{
                width:7, height:7, borderRadius:'50%', background:'#FBBF24',
                boxShadow:'0 0 12px #FBBF24',
              }}/>
              GCC Skill Badge · Verified
            </div>
            <div style={{font:'500 14px/1 Inter', color:'rgba(255,255,255,.55)', marginTop:18, letterSpacing:'.04em'}}>Awarded to</div>
            <h2 style={{font:'800 38px/1.1 "DM Sans"', color:'#fff', margin:'4px 0 10px', letterSpacing:'-0.02em'}}>{name}</h2>
            <div style={{font:'500 13px/1.5 Inter', color:'rgba(255,255,255,.55)'}}>Issued {result.issuedDate} · ID {result.badgeId}</div>
            <div style={{
              marginTop:22, display:'inline-flex', flexDirection:'column', gap:6,
              padding:'16px 20px', borderRadius:14,
              background:'rgba(245,158,11,.12)', border:'1px solid rgba(245,158,11,.35)',
            }}>
              <div style={{font:'700 11px/1 Inter', color:'rgba(255,255,255,.75)', letterSpacing:'.14em', textTransform:'uppercase'}}>Readiness</div>
              <div style={{font:'800 64px/1 "DM Sans"', color:'#FBBF24', letterSpacing:'-0.04em'}}>{result.level}</div>
              <div style={{font:'500 13px/1.5 Inter', color:'rgba(255,255,255,.85)', maxWidth:280}}>{result.levelBlurb}</div>
            </div>
          </div>
          <div style={{display:'flex', flexDirection:'column', gap:14, justifyContent:'flex-end'}}>
            <BadgeStat label="Recommended cert"     value={cert.name}/>
            <BadgeStat label="Recommended role pod" value={role.title}/>
            <BadgeStat label={`India CTC band — ${result.level}`} value={`₹${result.ctcLow}–${result.ctcHigh} L`}/>
            <div style={{marginTop:8, font:'500 11px/1.4 Inter', color:'rgba(255,255,255,.45)'}}>
              Verify at gccready.com/verify/{result.badgeId}
            </div>
          </div>
        </div>
      </div>
      <div style={{marginTop:14, textAlign:'center', font:'500 12.5px/1.5 Inter', color:'var(--gr-fg-3)'}}>
        Save this credential. Share it on LinkedIn. Recruiters at 41 GCC hiring partners can verify it via the URL.
      </div>
    </>
  );
}

function BadgeStat({ label, value }) {
  return (
    <div style={{padding:'14px 16px', background:'rgba(255,255,255,.06)', border:'1px solid rgba(255,255,255,.10)', borderRadius:12}}>
      <div style={{font:'700 10px/1 Inter', color:'rgba(255,255,255,.55)', letterSpacing:'.14em', textTransform:'uppercase'}}>{label}</div>
      <div style={{font:'700 16.5px/1.25 "DM Sans"', color:'#fff', marginTop:6, letterSpacing:'-0.005em'}}>{value}</div>
    </div>
  );
}

/* ============================================================================
 * Share row — LinkedIn / WhatsApp / Email / Copy / Download PNG
 * ========================================================================== */
function BadgeShareRow({ name, result }) {
  const baseUrl = (typeof SITE_ORIGIN !== 'undefined' ? SITE_ORIGIN : 'https://gccready.com');
  const verifyUrl = `${baseUrl}/verify/${result.badgeId}`;
  const lnPost = encodeURIComponent(
`I just earned the GCCReady Skill Badge — verified ${result.level} readiness for India's GCCs.

· Recommended cert: ${result.cert.toUpperCase().replace(/-/g,' ')}
· Role pod: ${(typeof GR_ROLES !== 'undefined' ? (GR_ROLES.find((r)=>r.slug===result.role)||{}).title : '') || result.role}
· India CTC band: ₹${result.ctcLow}–${result.ctcHigh} LPA

If you're a college student or early-career professional in commerce, finance or analytics — take the free Skill Badge:

`);
  const liUrl = `https://www.linkedin.com/feed/?shareActive=true&text=${lnPost}${encodeURIComponent(verifyUrl)}`;
  const waMsg = encodeURIComponent(`Hi! I just took the GCCReady Skill Badge and got ${result.level}. They recommend ${result.cert.toUpperCase().replace(/-/g,' ')} for me. Could you take a look at this with me? ${verifyUrl}`);
  const waUrl = `https://wa.me/?text=${waMsg}`;
  const mailUrl = `mailto:?subject=${encodeURIComponent('My GCCReady Skill Badge — '+result.level)}&body=${encodeURIComponent('I earned a '+result.level+' GCCReady Skill Badge. Recommended cert: '+result.cert.toUpperCase().replace(/-/g,' ')+'. Verify: '+verifyUrl)}`;

  const copyLink = () => {
    navigator.clipboard?.writeText(verifyUrl).then(() => {
      const btn = document.getElementById('sb-copy-btn');
      if (btn) { const old = btn.textContent; btn.textContent = 'Copied ✓'; setTimeout(()=>{ btn.textContent = old; }, 1500); }
    });
  };

  const downloadPNG = () => {
    // SVG → PNG via canvas. We rebuild the badge in SVG so it can be exported clean.
    const svg = `<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630">
  <defs>
    <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
      <stop offset="0%" stop-color="#0D1B2A"/>
      <stop offset="60%" stop-color="#1E3551"/>
      <stop offset="100%" stop-color="#0D1B2A"/>
    </linearGradient>
    <radialGradient id="glow" cx="0.85" cy="0.15" r="0.6">
      <stop offset="0%" stop-color="#F59E0B" stop-opacity="0.35"/>
      <stop offset="65%" stop-color="#F59E0B" stop-opacity="0"/>
    </radialGradient>
  </defs>
  <rect width="1200" height="630" fill="url(#bg)"/>
  <rect width="1200" height="630" fill="url(#glow)"/>
  <text x="60" y="80" fill="#FBBF24" font-family="DM Sans, Inter, sans-serif" font-size="20" font-weight="800" letter-spacing="3">GCC SKILL BADGE · VERIFIED</text>
  <text x="60" y="160" fill="rgba(255,255,255,0.55)" font-family="Inter, sans-serif" font-size="22" font-weight="500">Awarded to</text>
  <text x="60" y="230" fill="#ffffff" font-family="DM Sans, sans-serif" font-size="64" font-weight="800" letter-spacing="-1.5">${escSvg(name)}</text>
  <text x="60" y="270" fill="rgba(255,255,255,0.55)" font-family="Inter, sans-serif" font-size="18" font-weight="500">Issued ${escSvg(result.issuedDate)}  ·  ID ${escSvg(result.badgeId)}</text>

  <rect x="60" y="320" width="540" height="200" rx="16" fill="rgba(245,158,11,0.12)" stroke="#F59E0B" stroke-opacity="0.35"/>
  <text x="86" y="360" fill="rgba(255,255,255,0.75)" font-family="Inter, sans-serif" font-size="16" font-weight="700" letter-spacing="3">READINESS</text>
  <text x="86" y="460" fill="#FBBF24" font-family="DM Sans, sans-serif" font-size="120" font-weight="800" letter-spacing="-3">${escSvg(result.level)}</text>
  <text x="86" y="500" fill="rgba(255,255,255,0.85)" font-family="Inter, sans-serif" font-size="18" font-weight="500">${escSvg((result.levelBlurb || '').slice(0, 80))}</text>

  <rect x="640" y="320" width="500" height="60" rx="12" fill="rgba(255,255,255,0.06)" stroke="rgba(255,255,255,0.10)"/>
  <text x="660" y="345" fill="rgba(255,255,255,0.55)" font-family="Inter, sans-serif" font-size="13" font-weight="700" letter-spacing="2">RECOMMENDED CERT</text>
  <text x="660" y="370" fill="#fff" font-family="DM Sans, sans-serif" font-size="22" font-weight="700">${escSvg(result.cert.toUpperCase().replace(/-/g,' '))}</text>

  <rect x="640" y="395" width="500" height="60" rx="12" fill="rgba(255,255,255,0.06)" stroke="rgba(255,255,255,0.10)"/>
  <text x="660" y="420" fill="rgba(255,255,255,0.55)" font-family="Inter, sans-serif" font-size="13" font-weight="700" letter-spacing="2">RECOMMENDED ROLE POD</text>
  <text x="660" y="445" fill="#fff" font-family="DM Sans, sans-serif" font-size="22" font-weight="700">${escSvg((typeof GR_ROLES !== 'undefined' ? (GR_ROLES.find((r)=>r.slug===result.role)||{}).title : '') || result.role)}</text>

  <rect x="640" y="470" width="500" height="60" rx="12" fill="rgba(255,255,255,0.06)" stroke="rgba(255,255,255,0.10)"/>
  <text x="660" y="495" fill="rgba(255,255,255,0.55)" font-family="Inter, sans-serif" font-size="13" font-weight="700" letter-spacing="2">INDIA CTC BAND</text>
  <text x="660" y="520" fill="#FBBF24" font-family="DM Sans, sans-serif" font-size="22" font-weight="800">₹${escSvg(result.ctcLow)}–${escSvg(result.ctcHigh)} LPA</text>

  <text x="60" y="585" fill="rgba(255,255,255,0.45)" font-family="Inter, sans-serif" font-size="14" font-weight="500">Verify at gccready.com/verify/${escSvg(result.badgeId)}</text>
  <text x="1140" y="585" fill="#FBBF24" font-family="DM Sans, sans-serif" font-size="22" font-weight="800" letter-spacing="-1" text-anchor="end">GCCReady</text>
</svg>`;
    const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const img = new Image();
    img.onload = function () {
      const canvas = document.createElement('canvas');
      canvas.width = 1200; canvas.height = 630;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0);
      canvas.toBlob((b) => {
        const a = document.createElement('a');
        a.href = URL.createObjectURL(b);
        a.download = `gccready-skill-badge-${result.badgeId}.png`;
        a.click();
        URL.revokeObjectURL(url);
      }, 'image/png');
    };
    img.src = url;
  };

  return (
    <div style={{marginTop:18, display:'grid', gridTemplateColumns:'repeat(5, 1fr)', gap:10}}>
      <ShareIconBtn icon="download" label="Download PNG" onClick={downloadPNG} color="#F59E0B"/>
      <ShareIconBtn icon="linkedin"  label="LinkedIn"     href={liUrl} color="#0A66C2"/>
      <ShareIconBtn icon="whatsapp"  label="WhatsApp"     href={waUrl} color="#25D366"/>
      <ShareIconBtn icon="mail"      label="Email"        href={mailUrl} color="#0D1B2A"/>
      <ShareIconBtn icon="globe"     label="Copy link"    onClick={copyLink} color="#7E22CE" id="sb-copy-btn"/>
    </div>
  );
}

function ShareIconBtn({ icon, label, href, onClick, color, id }) {
  const Comp = href ? 'a' : 'button';
  const props = href ? { href, target:'_blank', rel:'noopener noreferrer' } : { onClick, type:'button' };
  return (
    <Comp {...props} id={id} style={{
      padding:'14px 12px', borderRadius:14,
      background:'#fff', border:`1.5px solid ${color}33`,
      color, font:'700 12.5px/1 Inter', cursor:'pointer',
      display:'flex', flexDirection:'column', alignItems:'center', gap:8,
      textDecoration:'none', transition:'all .15s ease',
    }}
    onMouseEnter={(ev)=>{ ev.currentTarget.style.borderColor=color; ev.currentTarget.style.background=color+'10'; }}
    onMouseLeave={(ev)=>{ ev.currentTarget.style.borderColor=color+'33'; ev.currentTarget.style.background='#fff'; }}>
      <Icon name={icon} size={22}/>
      <span>{label}</span>
    </Comp>
  );
}

function escSvg(s) {
  return String(s == null ? '' : s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

/* ============================================================================
 * EmailMyPlan — capture email, write back to ctx
 * ========================================================================== */
function EmailMyPlan({ name, result }) {
  const [status, setStatus] = React.useState({ kind:'idle', msg:'' });
  const ref = React.useRef(null);
  const onSubmit = async (e) => {
    e.preventDefault();
    const fd = new FormData(ref.current);
    const data = {
      form_type:'skill_badge_email_plan',
      name, email: fd.get('email'), whatsapp: fd.get('whatsapp') || '',
      level: result.level, cert: result.cert, role: result.role,
      badge_id: result.badgeId,
      ts_client: new Date().toISOString(),
    };
    try {
      const cur = JSON.parse(localStorage.getItem('gr_user_ctx') || '{}');
      localStorage.setItem('gr_user_ctx', JSON.stringify(Object.assign(cur, { email: data.email, whatsapp: data.whatsapp })));
    } catch (_) {}
    setStatus({ kind:'sending', msg:'Sending your plan…' });
    const SHEETS_ENDPOINT = (window.GR_CONFIG && window.GR_CONFIG.SHEETS_ENDPOINT) || '';
    if (SHEETS_ENDPOINT) {
      try {
        const params = new URLSearchParams();
        Object.entries(data).forEach(([k, v]) => params.set(k, v));
        const res = await fetch(SHEETS_ENDPOINT, { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'}, body: params.toString() });
        if (!res.ok) throw new Error();
      } catch (_) {}
    }
    setStatus({ kind:'success', msg:'Plan emailed. Also saved to your browser — your next visit will pre-fill calculators.' });
  };
  return (
    <div className="gr-card" style={{marginTop:18, padding:28, background:'var(--gr-bg-cream)'}}>
      <div className="gr-eyebrow" style={{color:'var(--gr-gold-700)'}}>Save your plan</div>
      <h3 className="gr-h4" style={{fontSize:20, marginTop:6}}>Email me a 1-page plan + cohort dates</h3>
      <p className="gr-p" style={{marginTop:8, fontSize:14}}>We'll email a personalised plan with cert prep schedule, role pod curriculum, 5 named GCCs hiring for your profile, and the next 3 cohort start dates.</p>
      {status.kind === 'success' ? (
        <div style={{marginTop:14, padding:'12px 14px', borderRadius:12, background:'var(--gr-green-50)', color:'var(--gr-green)', font:'600 13.5px/1.5 Inter'}}>
          <Icon name="check-circle" size={14} style={{verticalAlign:'-2px', marginRight:6}}/>{status.msg}
        </div>
      ) : (
        <form ref={ref} onSubmit={onSubmit} style={{marginTop:14, display:'grid', gridTemplateColumns:'1fr 1fr auto', gap:10}}>
          <input name="email" type="email" required placeholder="you@example.com" style={inpS}/>
          <input name="whatsapp" type="tel" placeholder="+91 …" style={inpS}/>
          <button type="submit" disabled={status.kind === 'sending'} className="gr-btn gr-btn-gold gr-btn-lg">
            {status.kind === 'sending' ? 'Sending…' : 'Email my plan'} <Icon name="arrow-right" size={14}/>
          </button>
        </form>
      )}
    </div>
  );
}
const inpS = { padding:'12px 14px', font:'500 14px/1.4 Inter', border:'1.5px solid var(--gr-border)', borderRadius:11, background:'#fff', color:'var(--gr-fg-1)' };

Object.assign(window, { SkillBadgeAssessPage });
