// Full SEO Audit — tabbed: Technical | Content | Speed | All Issues

(function () {

function SevBadge({ sev }) {
  const map = { critical:['var(--bad)','var(--bad-soft)','Critical'], major:['var(--warn)','var(--warn-soft)','Major'], minor:['var(--ink-3)','var(--surface-3)','Minor'] };
  const [color, bg, label] = map[sev] || map.minor;
  return <span style={{ fontSize:11, fontWeight:700, padding:'2px 8px', borderRadius:100, color, background:bg }}>{label}</span>;
}

function ScoreBar({ score, label }) {
  const color = score>=70?'var(--good)':score>=50?'var(--warn)':'var(--bad)';
  return (
    <div style={{ display:'flex', alignItems:'center', gap:12 }}>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ display:'flex', justifyContent:'space-between', marginBottom:5 }}>
          <span style={{ fontSize:13, color:'var(--ink-2)' }}>{label}</span>
          <span style={{ fontSize:13, fontWeight:700, color }}>{score}</span>
        </div>
        <div style={{ height:6, background:'var(--surface-3)', borderRadius:99, overflow:'hidden' }}>
          <div style={{ width:`${score}%`, height:'100%', background:color, borderRadius:99 }}/>
        </div>
      </div>
    </div>
  );
}

function IssueCard({ issue }) {
  const [open, setOpen] = React.useState(false);
  const sevColor = issue.sev==='critical'?'var(--bad)':issue.sev==='major'?'var(--warn)':'var(--ink-3)';
  const c = window.CP_CLIENT || {};
  return (
    <div style={{ border:'1px solid var(--border)', borderRadius:'var(--r-2)', overflow:'hidden' }}>
      <div onClick={() => setOpen(o=>!o)}
        style={{ display:'flex', alignItems:'flex-start', gap:12, padding:'12px 14px', cursor:'pointer', background:'var(--surface-3)', userSelect:'none' }}>
        <div style={{ width:7, height:7, borderRadius:'50%', background:sevColor, marginTop:5, flexShrink:0 }}/>
        <div style={{ flex:1 }}>
          <div style={{ display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
            <span style={{ fontSize:13.5, fontWeight:600, color:'var(--ink)' }}>{issue.title}</span>
            <SevBadge sev={issue.sev}/>
          </div>
        </div>
        <Icon name={open?'chevUp':'chev'} size={14} style={{ color:'var(--ink-3)', flexShrink:0, marginTop:2 }}/>
      </div>
      {open && (
        <div style={{ padding:'12px 14px 14px 33px', background:'var(--surface)', borderTop:'1px solid var(--border)' }}>
          <p className="hk-small" style={{ color:'var(--ink-2)', marginBottom:12, lineHeight:1.6 }}>{issue.detail}</p>
          <LockedSection
            label="Fix Guide — Book a Free Strategy Call"
            sub="Get step-by-step instructions to fix this issue and every other problem found in your audit."
            ctaLabel="Get the Fix"
          >
            <div style={{ padding:'10px 12px', background:'var(--surface-3)', borderRadius:'var(--r-1)', borderLeft:'3px solid var(--accent)' }}>
              <div className="hk-tiny" style={{ color:'var(--ink-3)', fontWeight:600, marginBottom:3, textTransform:'uppercase', letterSpacing:'0.06em' }}>Fix</div>
              <div className="hk-small" style={{ color:'var(--ink)', lineHeight:1.6 }}>{issue.fix}</div>
            </div>
          </LockedSection>
        </div>
      )}
    </div>
  );
}

function IssueGroup({ issues, label }) {
  if (!issues || issues.length === 0) return null;
  return (
    <div style={{ marginBottom:20 }}>
      <div style={{ fontSize:11.5, fontWeight:700, color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'0.07em', marginBottom:8 }}>{label} ({issues.length})</div>
      <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
        {issues.map((issue, i) => <IssueCard key={i} issue={issue}/>)}
      </div>
    </div>
  );
}

const CWV_HINTS = {
  LCP:  'Largest Contentful Paint — how fast your biggest content (hero image, headline) appears. Under 2.5s = good. Over 4s = visitors are leaving.',
  CLS:  'Cumulative Layout Shift — measures if your page "jumps around" while loading. A shifting page frustrates users. Under 0.1 = good.',
  FCP:  'First Contentful Paint — how fast the first piece of content appears on screen. The sooner, the better.',
  INP:  'Interaction to Next Paint — how fast your page responds when someone clicks or taps. Under 200ms = good.',
  TTFB: 'Time to First Byte — how fast your server starts sending data. High TTFB usually means server or hosting issues. Under 800ms = good.',
};

function CWVMetric({ label, value, unit, status }) {
  const color = status==='poor'?'var(--bad)':status==='needs-improvement'?'var(--warn)':'var(--good)';
  const bg    = status==='poor'?'var(--bad-soft)':status==='needs-improvement'?'var(--warn-soft)':'var(--good-soft)';
  const statusLabel = status==='poor'?'Poor':status==='needs-improvement'?'Needs Improvement':'Good';
  const hint = CWV_HINTS[label];
  return (
    <div style={{ background:'var(--surface)', border:`1px solid color-mix(in srgb, ${color} 25%, transparent)`, borderRadius:'var(--r-3)', padding:'16px 18px' }}>
      <div style={{ fontSize:26, fontWeight:700, color, lineHeight:1, marginBottom:4 }}>
        {value}<span style={{ fontSize:14, color:'var(--ink-3)', fontWeight:400 }}>{unit}</span>
      </div>
      <div style={{ display:'flex', alignItems:'center', gap:5, marginBottom:4 }}>
        <span style={{ fontSize:12.5, fontWeight:600, color:'var(--ink-2)' }}>{label}</span>
        {hint && <Hint text={hint} width={240}/>}
      </div>
      <span style={{ fontSize:11, fontWeight:700, padding:'2px 8px', borderRadius:100, color, background:bg }}>{statusLabel}</span>
    </div>
  );
}

function EEATBar({ label, value }) {
  const color = value>=70?'var(--good)':value>=50?'var(--warn)':'var(--bad)';
  return (
    <div>
      <div style={{ display:'flex', justifyContent:'space-between', marginBottom:4 }}>
        <span style={{ fontSize:13, color:'var(--ink-2)' }}>{label}</span>
        <span style={{ fontSize:13, fontWeight:700, color }}>{value}/100</span>
      </div>
      <div style={{ height:7, background:'var(--surface-3)', borderRadius:99, overflow:'hidden' }}>
        <div style={{ width:`${value}%`, height:'100%', background:color, borderRadius:99 }}/>
      </div>
    </div>
  );
}

const TABS = [
  { id:'technical', label:'Technical SEO' },
  { id:'content',   label:'Content & On-Page' },
  { id:'speed',     label:'Page Speed' },
  { id:'all',       label:'All Issues' }
];

function AuditPageContent({ go }) {
  const c = window.CP_CLIENT || {};
  const scores = c.scores || {};
  const [tab, setTab] = React.useState('technical');

  const allIssues = [
    ...(c.technical?.issues || []),
    ...(c.content?.issues   || []),
    ...(c.speed?.issues     || []),
    ...(c.local?.issues     || []),
    ...(c.backlinks?.issues || [])
  ];

  return (
    <div>
      <div style={{ marginBottom:20 }}>
        <h2 className="hk-h3" style={{ marginBottom:4 }}>Full SEO Report</h2>
        <p className="hk-small" style={{ color:'var(--ink-3)' }}>
          Comprehensive audit for <strong>{c.domain}</strong> · {c.auditDate}
        </p>
      </div>

      {/* Score summary row */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(130px,1fr))', gap:10, marginBottom:24 }}>
        {[
          { label:'Overall', score:scores.overall ?? c.audit?.overallScore ?? 0 },
          { label:'Technical', score:scores.technical??0 },
          { label:'Content', score:scores.content??0 },
          { label:'Speed', score:scores.speed??0 },
          { label:'Schema', score:scores.schema??0 },
          { label:'AI Search', score:scores.aiSearch??0 }
        ].map(({ label, score }) => {
          const color = score>=70?'var(--good)':score>=50?'var(--warn)':'var(--bad)';
          return (
            <div key={label} style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-2)', padding:'12px 14px', textAlign:'center' }}>
              <div style={{ fontSize:22, fontWeight:700, color, lineHeight:1, marginBottom:4 }}>{score}</div>
              <div className="hk-tiny" style={{ color:'var(--ink-3)' }}>{label}</div>
            </div>
          );
        })}
      </div>

      {/* Tabs */}
      <div style={{ display:'flex', gap:2, borderBottom:'1px solid var(--border)', marginBottom:24, overflowX:'auto' }}>
        {TABS.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)}
            style={{ padding:'9px 16px', fontSize:13.5, fontWeight:tab===t.id?700:400,
              color:tab===t.id?'var(--ink)':'var(--ink-3)',
              background:'transparent', border:'none', cursor:'pointer',
              borderBottom:tab===t.id?'2px solid var(--accent)':'2px solid transparent',
              marginBottom:-1, whiteSpace:'nowrap', fontFamily:'inherit', transition:'color .12s' }}>
            {t.label}
          </button>
        ))}
      </div>

      {/* ── Technical ─────────────────────────────────────────── */}
      {tab==='technical' && (() => {
        const tech = c.technical || {};
        return (
          <div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12, marginBottom:24 }}>
              {/* Category scores */}
              <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'18px 20px' }}>
                <div className="hk-h4" style={{ marginBottom:16 }}>Category Scores</div>
                <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
                  {(tech.categories||[]).map(cat => {
                    const color = cat.score>=70?'var(--good)':cat.score>=50?'var(--warn)':'var(--bad)';
                    const statusIcon = cat.status==='pass'?'check':cat.status==='fail'?'close':'minus';
                    return (
                      <div key={cat.id} style={{ display:'flex', alignItems:'center', gap:10 }}>
                        <div style={{ width:20, height:20, borderRadius:'50%', background: cat.status==='pass'?'var(--good-soft)':cat.status==='fail'?'var(--bad-soft)':'var(--warn-soft)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                          <Icon name={statusIcon} size={11} style={{ color }}/>
                        </div>
                        <span style={{ flex:1, fontSize:13, color:'var(--ink-2)' }}>{cat.label}</span>
                        <span style={{ fontSize:13.5, fontWeight:700, color, flexShrink:0 }}>{cat.score}</span>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* Quick stats */}
              <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'18px 20px' }}>
                <div className="hk-h4" style={{ marginBottom:16 }}>Quick Stats</div>
                <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
                  {[
                    { label:'Crawlable pages', value:'47', note:'of ~52 total' },
                    { label:'Indexed pages', value:'41', note:'via GSC' },
                    { label:'Broken links (404)', value:'5', warn:true },
                    { label:'Redirect chains', value:'3', warn:true },
                    { label:'HTTPS secure', value:'✓ Yes', good:true },
                    { label:'Mobile friendly', value:'✓ Yes', good:true }
                  ].map((s,i) => (
                    <div key={i} style={{ display:'flex', justifyContent:'space-between', padding:'7px 0', borderBottom:i<5?'1px solid var(--surface-3)':'' }}>
                      <span style={{ fontSize:13, color:'var(--ink-3)' }}>{s.label}</span>
                      <span style={{ fontSize:13, fontWeight:600, color:s.good?'var(--good)':s.warn?'var(--bad)':'var(--ink)' }}>{s.value} <span style={{ fontWeight:400, color:'var(--ink-3)' }}>{s.note||''}</span></span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
            <IssueGroup issues={tech.issues?.filter(i=>i.sev==='critical')} label="Critical"/>
            <IssueGroup issues={tech.issues?.filter(i=>i.sev==='major')} label="Major"/>
            <IssueGroup issues={tech.issues?.filter(i=>i.sev==='minor')} label="Minor"/>
          </div>
        );
      })()}

      {/* ── Content & On-Page ─────────────────────────────────── */}
      {tab==='content' && (() => {
        const ct = c.content || {};
        const eeat = ct.eeat || {};
        return (
          <div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12, marginBottom:24 }}>
              {/* E-E-A-T */}
              <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'18px 20px' }}>
                <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:4 }}>
                  <span className="hk-h4">E-E-A-T Score</span>
                  <Hint text="E-E-A-T = Experience, Expertise, Authoritativeness, Trustworthiness. Google uses these signals to decide if your site deserves to rank. Low E-E-A-T = poor rankings, even with good content." width={250}/>
                </div>
                <div className="hk-tiny" style={{ color:'var(--ink-3)', marginBottom:16 }}>Google's quality signals</div>
                <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
                  <EEATBar label="Experience"        value={eeat.experience||0}/>
                  <EEATBar label="Expertise"         value={eeat.expertise||0}/>
                  <EEATBar label="Authoritativeness" value={eeat.authoritativeness||0}/>
                  <EEATBar label="Trustworthiness"   value={eeat.trustworthiness||0}/>
                </div>
              </div>

              {/* AI readiness */}
              <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'18px 20px' }}>
                <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:4 }}>
                  <span className="hk-h4">AI Search Readiness</span>
                  <Hint text="ChatGPT, Perplexity, and Google AI Overviews are replacing regular search. If your site isn't structured for AI, you become invisible to the next generation of search." width={240}/>
                </div>
                <div className="hk-tiny" style={{ color:'var(--ink-3)', marginBottom:16 }}>How well AI products can cite your content</div>
                <div style={{ textAlign:'center', marginBottom:16 }}>
                  <div style={{ fontSize:52, fontWeight:700, color:(ct.aiReadiness||0)>=60?'var(--warn)':'var(--bad)', lineHeight:1 }}>{ct.aiReadiness||0}</div>
                  <div className="hk-tiny" style={{ color:'var(--ink-3)' }}>AI Citation Readiness Score</div>
                </div>
                <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                  {[
                    { label:'FAQ sections present',        done:false },
                    { label:'Structured answer formats',   done:false },
                    { label:'Entity markup (schema)',       done:false },
                    { label:'First-party data / studies',  done:false },
                    { label:'Author E-E-A-T signals',      done:false },
                    { label:'llms.txt configured',         done:false }
                  ].map((item,i) => (
                    <div key={i} style={{ display:'flex', alignItems:'center', gap:8 }}>
                      <div style={{ width:14, height:14, borderRadius:3, border:`1.5px solid ${item.done?'var(--good)':'var(--border)'}`, background:item.done?'var(--good)':'transparent', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                        {item.done && <Icon name="check" size={8} style={{ color:'#fff' }}/>}
                      </div>
                      <span className="hk-tiny" style={{ color:item.done?'var(--ink)':'var(--ink-3)' }}>{item.label}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
            <IssueGroup issues={ct.issues?.filter(i=>i.sev==='critical')} label="Critical"/>
            <IssueGroup issues={ct.issues?.filter(i=>i.sev==='major')} label="Major"/>
            <IssueGroup issues={ct.issues?.filter(i=>i.sev==='minor')} label="Minor"/>
          </div>
        );
      })()}

      {/* ── Speed ─────────────────────────────────────────────── */}
      {tab==='speed' && (() => {
        const sp = c.speed || {};
        return (
          <div>
            {/* Device scores */}
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12, marginBottom:24 }}>
              {[
                { label:'Mobile Score', score:sp.mobileScore??0 },
                { label:'Desktop Score', score:sp.desktopScore??0 }
              ].map(d => {
                const color = d.score>=90?'var(--good)':d.score>=50?'var(--warn)':'var(--bad)';
                return (
                  <div key={d.label} style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'18px 20px', textAlign:'center' }}>
                    <div style={{ fontSize:48, fontWeight:700, color, lineHeight:1, marginBottom:6 }}>{d.score}</div>
                    <div style={{ fontSize:13, color:'var(--ink-2)' }}>{d.label}</div>
                    <div className="hk-tiny" style={{ color:'var(--ink-3)', marginTop:2 }}>Google PageSpeed Insights</div>
                  </div>
                );
              })}
            </div>

            {/* Core Web Vitals */}
            <div style={{ marginBottom:24 }}>
              <div className="hk-h4" style={{ marginBottom:14 }}>Core Web Vitals</div>
              <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(160px,1fr))', gap:10 }}>
                {[sp.lcp, sp.cls, sp.fcp, sp.inp, sp.ttfb].filter(Boolean).map(m => (
                  <CWVMetric key={m.label} label={m.label} value={m.value} unit={m.unit} status={m.status}/>
                ))}
              </div>
            </div>

            <IssueGroup issues={sp.issues?.filter(i=>i.sev==='critical')} label="Critical"/>
            <IssueGroup issues={sp.issues?.filter(i=>i.sev==='major')} label="Major"/>
            <IssueGroup issues={sp.issues?.filter(i=>i.sev==='minor')} label="Minor"/>
          </div>
        );
      })()}

      {/* ── All Issues ────────────────────────────────────────── */}
      {tab==='all' && (
        <div>
          <div style={{ display:'flex', gap:16, marginBottom:20, flexWrap:'wrap' }}>
            {[
              { sev:'critical', color:'var(--bad)',  count:allIssues.filter(i=>i.sev==='critical').length },
              { sev:'major',    color:'var(--warn)', count:allIssues.filter(i=>i.sev==='major').length    },
              { sev:'minor',    color:'var(--ink-3)',count:allIssues.filter(i=>i.sev==='minor').length    }
            ].map(s => (
              <div key={s.sev} style={{ display:'flex', alignItems:'center', gap:8, padding:'8px 14px', background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-2)' }}>
                <span style={{ width:8, height:8, borderRadius:'50%', background:s.color, display:'inline-block' }}/>
                <span style={{ fontSize:13, color:'var(--ink-2)', fontWeight:500 }}>{s.count} {s.sev}</span>
              </div>
            ))}
          </div>
          <IssueGroup issues={allIssues.filter(i=>i.sev==='critical')} label="Critical"/>
          <IssueGroup issues={allIssues.filter(i=>i.sev==='major')} label="Major"/>
          <IssueGroup issues={allIssues.filter(i=>i.sev==='minor')} label="Minor"/>
        </div>
      )}

      {/* CTA */}
      <div style={{ marginTop:32, padding:'20px 24px', background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', display:'flex', alignItems:'center', justifyContent:'space-between', gap:16, flexWrap:'wrap' }}>
        <div>
          <div className="hk-h4" style={{ marginBottom:4 }}>Ready to fix these issues?</div>
          <div className="hk-small" style={{ color:'var(--ink-3)' }}>HiKit Studio can implement every fix on this report.</div>
        </div>
        <a href={c.bookingUrl} target="_blank" rel="noopener"
          style={{ display:'inline-flex', alignItems:'center', gap:6, padding:'10px 20px', background:'var(--accent)', color:'#fff', borderRadius:'var(--r-3)', textDecoration:'none', fontSize:13.5, fontWeight:600, flexShrink:0 }}>
          <Icon name="calendar" size={14}/> Book a free strategy call
        </a>
      </div>
    </div>
  );
}

CP_PAGES.audit = { title: 'Full Report', component: AuditPageContent };

})();
