// Local SEO — GBP status, NAP consistency, reviews, issues

(function () {

function StatusDot({ status }) {
  const color = status==='correct'?'var(--good)':status==='inconsistent'?'var(--bad)':'var(--warn)';
  const label = status==='correct'?'Correct':status==='inconsistent'?'Inconsistent':'Unknown';
  return (
    <span style={{ display:'inline-flex', alignItems:'center', gap:5, fontSize:12, fontWeight:600, color }}>
      <span style={{ width:7, height:7, borderRadius:'50%', background:color, display:'inline-block' }}/>
      {label}
    </span>
  );
}

function IssueCard({ issue }) {
  const [open, setOpen] = React.useState(false);
  const sevColor = issue.sev==='critical'?'var(--bad)':issue.sev==='major'?'var(--warn)':'var(--ink-3)';
  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)' }}>
        <div style={{ width:7, height:7, borderRadius:'50%', background:sevColor, marginTop:5, flexShrink:0 }}/>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:13.5, fontWeight:600, color:'var(--ink)' }}>{issue.title}</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 local SEO 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 StarRating({ rating }) {
  return (
    <span style={{ display:'inline-flex', gap:2, alignItems:'center' }}>
      {[1,2,3,4,5].map(n => (
        <svg key={n} width="12" height="12" viewBox="0 0 24 24" fill={n<=Math.round(rating)?'#f59e0b':'var(--surface-3)'} stroke={n<=Math.round(rating)?'#f59e0b':'var(--border)'} strokeWidth="1.5">
          <path d="m12 4 2.5 5.2 5.5.8-4 3.9.9 5.6L12 16.8 7.1 19.5 8 13.9l-4-3.9 5.5-.8z"/>
        </svg>
      ))}
      <span style={{ fontSize:12, color:'var(--ink-2)', marginLeft:4, fontWeight:600 }}>{rating}</span>
    </span>
  );
}

function LocalPage({ go }) {
  const c   = window.CP_CLIENT || {};
  const loc = c.local || {};
  const gbp = loc.gbp || {};
  const nap = loc.nap || {};
  const rev = loc.reviews || {};
  const score = loc.score ?? 0;
  const scoreColor = score>=70?'var(--good)':score>=50?'var(--warn)':'var(--bad)';

  const napConsistentCount = (nap.platforms||[]).filter(p=>p.status==='correct').length;
  const napTotal = (nap.platforms||[]).length;

  return (
    <div>
      <div style={{ marginBottom:24 }}>
        <h2 className="hk-h3" style={{ marginBottom:4 }}>Local SEO</h2>
        <p className="hk-small" style={{ color:'var(--ink-3)' }}>
          Local search visibility analysis for <strong>{c.name}</strong> in {c.location}
        </p>
      </div>

      {/* ── Score + key numbers ──────────────────────────────── */}
      <div style={{ display:'grid', gridTemplateColumns:'auto 1fr', gap:12, marginBottom:24 }}>
        <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'20px 24px', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', minWidth:140 }}>
          <div style={{ fontSize:52, fontWeight:700, color:scoreColor, lineHeight:1 }}>{score}</div>
          <div style={{ fontSize:12, color:'var(--ink-3)', marginTop:4 }}>Local SEO Score</div>
          <div style={{ fontSize:12, fontWeight:700, color:scoreColor, marginTop:6 }}>{score>=70?'Strong':score>=50?'Needs Work':'Weak'}</div>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(140px,1fr))', gap:10 }}>
          {[
            { label:'GBP Rating',       value:`${gbp.rating||'—'}/5`,        color:'#f59e0b',             hint:'Google Business Profile rating — the star rating customers see when they search for you on Google Maps.' },
            { label:'Total Reviews',     value:rev.total||0,                   color:'var(--ink)',           hint:null },
            { label:'NAP Consistent',    value:`${napConsistentCount}/${napTotal}`, color: napConsistentCount===napTotal?'var(--good)':'var(--bad)', hint:'NAP = Name, Address, Phone. If these details don\'t match exactly across Google, Yelp, Bing, etc., it confuses Google and hurts your local rankings.' },
            { label:'GBP Photos',        value:`${gbp.photos||0}/${gbp.photosTarget||10}`, color:gbp.photos>=gbp.photosTarget?'var(--good)':'var(--warn)', hint:'Profiles with more photos get significantly more clicks and direction requests. Aim for 15+ quality photos.' },
            { label:'Review Response',   value:`${rev.responseRate||0}%`,      color:rev.responseRate>=70?'var(--good)':'var(--warn)', hint:'Percentage of reviews you\'ve responded to. Google tracks owner engagement — responding to reviews (even negative ones) is a local ranking signal.' },
            { label:'Schema Markup',     value:loc.schema?'✓ Present':'✗ Missing', color:loc.schema?'var(--good)':'var(--bad)', hint:'Schema markup is invisible code that tells Google exactly what your business is. Without it, Google has to guess — and often gets it wrong.' }
          ].map(m => (
            <div key={m.label} style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-2)', padding:'12px 14px' }}>
              <div style={{ fontSize:20, fontWeight:700, color:m.color, lineHeight:1.1, marginBottom:3 }}>{m.value}</div>
              <div style={{ display:'flex', alignItems:'center', gap:4 }}>
                <div className="hk-tiny" style={{ color:'var(--ink-3)' }}>{m.label}</div>
                {m.hint && <Hint text={m.hint} width={220}/>}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* ── GBP Checklist ────────────────────────────────────── */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12, marginBottom:24 }}>
        <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'18px 20px' }}>
          <div className="hk-h4" style={{ marginBottom:14 }}>Google Business Profile</div>
          <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
            {[
              { label:'Profile claimed & verified',   done:gbp.claimed && gbp.verified },
              { label:`Photos: ${gbp.photos||0} added (target: ${gbp.photosTarget||15})`, done:(gbp.photos||0)>=(gbp.photosTarget||15) },
              { label:'Holiday hours configured',     done:gbp.holidayHours },
              { label:'Attributes filled out',        done:gbp.attributes  },
              { label:'Weekly posts / updates',       done:gbp.weeklyPosts },
              { label:'LocalBusiness schema on site', done:loc.schema      }
            ].map((item, i) => (
              <div key={i} style={{ display:'flex', alignItems:'center', gap:10 }}>
                <div style={{ width:18, height:18, borderRadius:'50%', border:`2px 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={10} style={{ color:'#fff' }}/>}
                </div>
                <span style={{ fontSize:13, color:item.done?'var(--ink)':'var(--ink-3)' }}>{item.label}</span>
              </div>
            ))}
          </div>
          {gbp.missing && gbp.missing.length > 0 && (
            <div style={{ marginTop:14, padding:'10px 12px', background:'var(--warn-soft)', borderRadius:'var(--r-2)' }}>
              <div className="hk-tiny" style={{ color:'var(--ink-3)', fontWeight:600, marginBottom:4 }}>MISSING ATTRIBUTES</div>
              <div className="hk-tiny" style={{ color:'var(--ink-2)', lineHeight:1.7 }}>{gbp.missing.join(' · ')}</div>
            </div>
          )}
        </div>

        {/* Reviews */}
        <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'18px 20px' }}>
          <div className="hk-h4" style={{ marginBottom:14 }}>Review Health</div>
          <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
            {[
              { platform:'Google',      count:rev.google?.count||0,      avg:rev.google?.avg||0      },
              { platform:'Yelp',        count:rev.yelp?.count||0,        avg:rev.yelp?.avg||0        },
              { platform:'TripAdvisor', count:rev.tripadvisor?.count||0, avg:rev.tripadvisor?.avg||0 }
            ].map(r => (
              <div key={r.platform} style={{ display:'flex', alignItems:'center', gap:10 }}>
                <div style={{ width:80, fontSize:13, color:'var(--ink-2)', fontWeight:500, flexShrink:0 }}>{r.platform}</div>
                <StarRating rating={r.avg}/>
                <span style={{ fontSize:12, color:'var(--ink-3)', marginLeft:'auto' }}>{r.count} reviews</span>
              </div>
            ))}
            <div style={{ height:1, background:'var(--border)', margin:'4px 0' }}/>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
              <span style={{ fontSize:13, color:'var(--ink-2)' }}>Response rate</span>
              <span style={{ fontSize:16, fontWeight:700, color:rev.responseRate>=70?'var(--good)':'var(--warn)' }}>{rev.responseRate||0}%</span>
            </div>
            <div style={{ padding:'10px 12px', background:'var(--warn-soft)', borderRadius:'var(--r-2)' }}>
              <div className="hk-tiny" style={{ color:'var(--ink-2)', lineHeight:1.5 }}>
                {rev.responseRate < 70 ? `Only ${rev.responseRate}% of reviews get a response. Google uses engagement as a local ranking signal. Target 80%+.` : 'Great review response rate! Keep it up.'}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* ── NAP Consistency ──────────────────────────────────── */}
      <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'18px 20px', marginBottom:24 }}>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:6 }}>
          <div style={{ display:'flex', alignItems:'center', gap:6 }}>
            <span className="hk-h4">NAP Consistency</span>
            <Hint text="NAP = Name, Address, Phone. If these differ across Google, Yelp, Facebook, etc., Google sees your business as untrustworthy and drops your local rankings." width={240}/>
          </div>
          <span style={{ fontSize:12, fontWeight:700, padding:'3px 10px', borderRadius:100,
            color:napConsistentCount===napTotal?'var(--good)':'var(--bad)',
            background:napConsistentCount===napTotal?'var(--good-soft)':'var(--bad-soft)' }}>
            {napConsistentCount}/{napTotal} correct
          </span>
        </div>
        <div className="hk-tiny" style={{ color:'var(--ink-3)', marginBottom:14 }}>
          Canonical: <code style={{ fontSize:12, color:'var(--accent)' }}>{nap.name} · {nap.address} · {nap.phone}</code>
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
          {(nap.platforms||[]).map((p, i) => (
            <div key={i} style={{ display:'flex', alignItems:'center', gap:12, padding:'10px 12px', background:'var(--surface-3)', borderRadius:'var(--r-2)' }}>
              <span style={{ width:100, fontSize:13, fontWeight:500, color:'var(--ink)', flexShrink:0 }}>{p.name}</span>
              <StatusDot status={p.status}/>
              {p.issue && <span className="hk-tiny" style={{ color:'var(--ink-3)', flex:1 }}>{p.issue}</span>}
            </div>
          ))}
        </div>
      </div>

      {/* ── Issues ───────────────────────────────────────────── */}
      <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-3)', padding:'18px 20px' }}>
        <div className="hk-h4" style={{ marginBottom:16 }}>Issues & Recommendations</div>
        <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
          {(loc.issues||[]).map((issue, i) => <IssueCard key={i} issue={issue}/>)}
        </div>
      </div>
    </div>
  );
}

CP_PAGES.local = { title: 'Local SEO', component: LocalPage };

})();
