const { TagChip, Card, Button, Badge } = window.TaglyDesignSystem_1a793a;

const FREE_LIMITS = { hashtags: 15, keywords: 10, longTail: 8, related: 6 };
const FAVORITES_KEY = 'tagly_favorites_v1';

function downloadBlob(filename, text, type) {
  const blob = new Blob([text], { type });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url; a.download = filename; document.body.appendChild(a); a.click();
  document.body.removeChild(a); URL.revokeObjectURL(url);
}
function loadFavorites() { try { return JSON.parse(localStorage.getItem(FAVORITES_KEY)) || []; } catch (e) { return []; } }
function saveFavorites(list) { try { localStorage.setItem(FAVORITES_KEY, JSON.stringify(list.slice(0, 30))); } catch (e) {} }

function CategoryTabs({ categories, active, onChange }) {
  return (
    <div style={{ display: 'flex', gap: 24, borderBottom: '1px solid var(--border-default)', marginBottom: 20, overflowX: 'auto' }}>
      {categories.map(c => (
        <button key={c.key} onClick={() => onChange(c.key)} aria-pressed={active === c.key} className="tagly-focusable" style={{
          position: 'relative', background: 'none', border: 'none', cursor: 'pointer', whiteSpace: 'nowrap',
          padding: '0 2px 14px', fontFamily: 'var(--font-sans)', fontSize: 15, fontWeight: 600,
          color: active === c.key ? 'var(--text-heading)' : 'var(--text-muted)',
        }}>
          {c.label} {c.count != null && <span style={{ color: 'var(--text-muted)', fontWeight: 400 }}>({c.count})</span>}
          {active === c.key && <span style={{ position: 'absolute', left: 0, right: 0, bottom: -1, height: 2, background: 'var(--tg-ink)', borderRadius: 2 }} />}
        </button>
      ))}
    </div>
  );
}

function AdSlot() {
  return (
    <div style={{
      marginTop: 32, width: '100%', maxWidth: 336, minHeight: 100, margin: '32px auto 0',
      border: '1px dashed var(--border-default)', borderRadius: 'var(--radius-md)',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 4, padding: 16,
    }}>
      <span style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>Advertisement</span>
      <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>336×280 · loads after results render</span>
    </div>
  );
}

const PURPOSE_LABEL = { awareness: 'Awareness', engagement: 'Engagement', 'niche discovery': 'Niche discovery', community: 'Community', conversion: 'Conversion' };
const PURPOSE_DESC = {
  awareness: 'Maximize how many new people see your content.',
  engagement: 'Drive likes, comments, shares, and replies.',
  'niche discovery': 'Reach a smaller, highly relevant audience.',
  community: 'Signal you into the platform’s own active communities.',
  conversion: 'Match intent-driven searches right before action.',
};
const TIER_LABEL = { broad: 'Broad reach', medium: 'Medium reach', niche: 'Niche reach' };
const TIER_COLOR = { broad: 'var(--tg-primary)', medium: 'var(--tg-success, #1a8a4a)', niche: 'var(--text-muted)' };

function Gauge({ label, value, color }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 10.5 }}>
      <span style={{ color: 'var(--text-muted)', minWidth: 68 }}>{label}</span>
      <div style={{ width: 56, height: 5, borderRadius: 999, background: 'var(--border-soft)', overflow: 'hidden' }}>
        <div style={{ width: `${Math.min(100, value)}%`, height: '100%', background: color || 'var(--tg-primary)' }} />
      </div>
    </div>
  );
}

function StrategyPanel({ strategy }) {
  if (!strategy) return null;
  return (
    <Card style={{ marginBottom: 24, background: 'var(--surface-soft)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <Badge variant="pro">AI strategy</Badge>
        <span style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>Estimated guidance, not measured platform data</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 16 }}>
        <div><div style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-heading)', marginBottom: 4 }}>Suggested tag mix</div><div style={{ fontSize: 13, color: 'var(--text-body)' }}>{strategy.mix}</div></div>
        <div><div style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-heading)', marginBottom: 4 }}>Posting guidance</div><div style={{ fontSize: 13, color: 'var(--text-body)' }}>{strategy.postingGuidance}</div></div>
        <div><div style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-heading)', marginBottom: 4 }}>Content angle</div><div style={{ fontSize: 13, color: 'var(--text-body)' }}>{strategy.contentAngle}</div></div>
        <div><div style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-heading)', marginBottom: 4 }}>Complementary keywords</div><div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>{strategy.complementaryKeywords.map(k => <code key={k} style={{ fontFamily: 'var(--font-mono)', fontSize: 12, background: '#fff', border: '1px solid var(--border-soft)', borderRadius: 999, padding: '3px 9px' }}>{k}</code>)}</div></div>
      </div>
    </Card>
  );
}

function ExpandedTopics({ topics, onPick }) {
  if (!topics?.length) return null;
  return (
    <div style={{ marginBottom: 20 }}>
      <div style={{ fontSize: 12, color: 'var(--text-muted)', marginBottom: 6 }}>Related angles — click to broaden your search</div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
        {topics.map((t, i) => (
          <button key={i} onClick={() => onPick(t)} style={{ fontSize: 12.5, background: 'var(--surface-soft)', border: '1px solid var(--border-soft)', borderRadius: 999, padding: '5px 12px', cursor: 'pointer', color: 'var(--text-body)' }}>{t}</button>
        ))}
      </div>
    </div>
  );
}

function CopyFormatMenu({ items, label }) {
  const [open, setOpen] = React.useState(false);
  const [copied, setCopied] = React.useState(null);
  function doCopy(fmt) {
    let text;
    if (fmt === 'full') text = items.map(i => i.tag).join(' ');
    else if (fmt === 'comma') text = items.map(i => i.tag).join(', ');
    else if (fmt === 'nohash') text = items.map(i => i.tag.replace(/^#/, '')).join(' ');
    else if (fmt === 'markdown') text = items.map(i => `- ${i.tag}`).join('\n');
    else if (fmt === 'category') {
      const groups = {};
      items.forEach(i => { const k = i.purpose || 'other'; (groups[k] = groups[k] || []).push(i.tag); });
      text = Object.entries(groups).map(([k, v]) => `${PURPOSE_LABEL[k] || k}:\n${v.join(' ')}`).join('\n\n');
    }
    navigator.clipboard.writeText(text).catch(() => {});
    setCopied(fmt); setOpen(false);
    setTimeout(() => setCopied(c => (c === fmt ? null : c)), 1400);
  }
  return (
    <div style={{ position: 'relative', display: 'inline-block' }}>
      <Button size="sm" onClick={() => setOpen(o => !o)}>{copied ? 'Copied!' : `Copy all ${label.toLowerCase()} ▾`}</Button>
      {open && (
        <div style={{ position: 'absolute', top: '110%', left: 0, background: '#fff', border: '1px solid var(--border-default)', borderRadius: 10, boxShadow: 'var(--shadow-float)', zIndex: 20, minWidth: 200, overflow: 'hidden' }}>
          {[['full', 'Full set (with #)'], ['category', 'Grouped by category'], ['comma', 'Comma-separated'], ['nohash', 'Without # symbols'], ['markdown', 'Markdown list']].map(([fmt, txt]) => (
            <button key={fmt} onClick={() => doCopy(fmt)} style={{ display: 'block', width: '100%', textAlign: 'left', padding: '10px 14px', fontSize: 13, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-body)' }}>{txt}</button>
          ))}
        </div>
      )}
    </div>
  );
}

function PublishPackageView({ pkg, platform, topic }) {
  const [copiedField, setCopiedField] = React.useState(null);
  if (!pkg) return null;
  function copy(field, text) {
    navigator.clipboard.writeText(text).catch(() => {});
    setCopiedField(field);
    setTimeout(() => setCopiedField(f => (f === field ? null : f)), 1200);
  }
  function copyFullPackage() {
    const parts = [
      `Title: ${pkg.title}`,
      `Caption: ${pkg.caption}`,
      `Hashtags: ${pkg.hashtags.map(h => h.tag).join(' ')}`,
      `Alt text: ${pkg.altText}`,
      `CTA: ${pkg.cta}`,
      pkg.firstComment ? pkg.firstComment : null,
      `Suggested posting time (estimated): ${pkg.postingTime.text}`,
    ].filter(Boolean);
    copy('full', parts.join('\n\n'));
  }
  const rows = [
    ['Title', pkg.title],
    ['Caption', pkg.caption],
    ['Hashtags', pkg.hashtags.map(h => h.tag).join(' ')],
    ['Alt text', pkg.altText],
    ['Call to action', pkg.cta],
  ];
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16, flexWrap: 'wrap', gap: 10 }}>
        <div style={{ fontSize: 13, color: 'var(--text-muted)' }}>A complete, ready-to-publish package for <strong style={{ color: 'var(--text-heading)' }}>"{topic}"</strong> on {platform}.</div>
        <Button size="sm" onClick={copyFullPackage}>{copiedField === 'full' ? 'Copied!' : 'Copy full package'}</Button>
      </div>
      <div style={{ display: 'grid', gap: 10 }}>
        {rows.map(([label, value]) => (
          <Card key={label} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 4 }}>{label}</div>
              <div style={{ fontSize: 13.5, color: 'var(--text-body)', wordBreak: 'break-word' }}>{value}</div>
            </div>
            <button onClick={() => copy(label, value)} style={{ flexShrink: 0, fontSize: 12, background: 'none', border: '1px solid var(--border-default)', borderRadius: 999, padding: '5px 12px', cursor: 'pointer', color: 'var(--text-body)' }}>{copiedField === label ? 'Copied' : 'Copy'}</button>
          </Card>
        ))}
        {pkg.firstComment && (
          <Card style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 4 }}>First comment</div>
              <div style={{ fontSize: 13.5, color: 'var(--text-body)', whiteSpace: 'pre-wrap' }}>{pkg.firstComment}</div>
            </div>
            <button onClick={() => copy('firstComment', pkg.firstComment)} style={{ flexShrink: 0, fontSize: 12, background: 'none', border: '1px solid var(--border-default)', borderRadius: 999, padding: '5px 12px', cursor: 'pointer', color: 'var(--text-body)' }}>{copiedField === 'firstComment' ? 'Copied' : 'Copy'}</button>
          </Card>
        )}
        <Card style={{ background: 'var(--surface-soft)' }}>
          <div style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 4 }}>Suggested posting time <span style={{ fontWeight: 400, textTransform: 'none' }}>(estimated, not measured)</span></div>
          <div style={{ fontSize: 13.5, color: 'var(--text-body)' }}>{pkg.postingTime.text}</div>
        </Card>
      </div>
    </div>
  );
}

function ResultsPanel({ results, isPro, onGoPro, onExpandTopic }) {
  const [active, setActive] = React.useState('hashtags');
  const [copiedId, setCopiedId] = React.useState(null);
  const [selected, setSelected] = React.useState(() => new Set());
  const [query, setQuery] = React.useState('');
  const [tierFilter, setTierFilter] = React.useState('all');
  const [groupBy, setGroupBy] = React.useState('purpose');
  const [isFav, setIsFav] = React.useState(false);
  const [toastMsg, setToastMsg] = React.useState(null);

  React.useEffect(() => {
    setActive('hashtags'); setSelected(new Set()); setQuery(''); setTierFilter('all');
    const favs = loadFavorites();
    setIsFav(favs.some(f => f.topic === results.topic && f.platform === results.platform));
  }, [results.topic, results.platform]);

  const categories = [
    { key: 'hashtags', label: 'Hashtags', count: results.hashtags.length, items: results.hashtags },
    { key: 'keywords', label: 'Keywords', count: results.keywords.length, items: results.keywords },
    { key: 'longTail', label: 'Long-tail', count: results.longTail.length, items: results.longTail },
    { key: 'related', label: 'Related searches', count: results.related.length, items: results.related },
    { key: 'captions', label: 'Captions & titles', count: (results.captions?.length || 0) + (results.titles?.length || 0), items: [...(results.captions || []), ...(results.titles || [])] },
    { key: 'publish', label: 'Publish package', count: null, items: [] },
  ];
  const current = categories.find(c => c.key === active);
  const limit = FREE_LIMITS[active] || 999;
  const proItems = isPro ? current.items : current.items.slice(0, limit);
  const visibleItems = proItems.filter(item => {
    if (tierFilter !== 'all' && item.tier !== tierFilter) return false;
    if (query && !item.tag.toLowerCase().includes(query.toLowerCase())) return false;
    return true;
  });
  const lockedCount = current.items.length - proItems.length;

  function copyOne(tag) {
    navigator.clipboard.writeText(tag).catch(() => {});
    setCopiedId(tag);
    setTimeout(() => setCopiedId(id => (id === tag ? null : id)), 1100);
  }
  function toggle(tag) {
    setSelected(prev => { const n = new Set(prev); n.has(tag) ? n.delete(tag) : n.add(tag); return n; });
  }
  function exportTxt() {
    downloadBlob(`tagly-${results.topic.replace(/\s+/g, '-')}-${current.key}.txt`, visibleItems.map(i => i.tag).join(' '), 'text/plain');
  }
  function exportCsv() {
    if (!isPro) { onGoPro(); return; }
    const rows = ['tag,score,competition,trend,purpose,confidence', ...visibleItems.map(i => `"${i.tag}",${i.score},${i.competition},${i.trend},${i.purpose || ''},${i.confidence || ''}`)];
    downloadBlob(`tagly-${results.topic.replace(/\s+/g, '-')}-${current.key}.csv`, rows.join('\n'), 'text/csv');
  }
  function exportMarkdown() {
    const md = `# ${results.topic} \u2014 ${current.label} (${results.platform})\n\n` + visibleItems.map(i => `- ${i.tag}`).join('\n');
    downloadBlob(`tagly-${results.topic.replace(/\s+/g, '-')}-${current.key}.md`, md, 'text/markdown');
  }
  function toggleFavorite() {
    const favs = loadFavorites();
    const exists = favs.some(f => f.topic === results.topic && f.platform === results.platform);
    const next = exists ? favs.filter(f => !(f.topic === results.topic && f.platform === results.platform)) : [{ topic: results.topic, platform: results.platform, savedAt: Date.now() }, ...favs];
    saveFavorites(next);
    setIsFav(!exists);
    setToastMsg(exists ? 'Removed from favorites' : 'Saved to favorites');
    setTimeout(() => setToastMsg(null), 1600);
  }
  function shareLink() {
    const url = new URL(window.location.href.split('?')[0].split('#')[0]);
    url.searchParams.set('topic', results.topic);
    url.searchParams.set('platform', results.platform);
    url.hash = 'generate';
    navigator.clipboard.writeText(url.toString()).catch(() => {});
    setToastMsg('Shareable link copied \u2014 anyone can open it to see this result');
    setTimeout(() => setToastMsg(null), 2200);
  }

  const clusterKeys = groupBy === 'topic'
    ? [...new Set(visibleItems.map(i => i.topic).filter(Boolean))]
    : ['awareness', 'engagement', 'niche discovery', 'community', 'conversion'];

  return (
    <div id="results" style={{ maxWidth: 'var(--container-tool)', margin: '0 auto', padding: '0 24px 64px' }}>
      <div style={{ marginBottom: 28 }}>
        <div style={{ fontSize: 'var(--type-count-display-size)', fontWeight: 'var(--type-count-display-weight)', lineHeight: 'var(--type-count-display-lh)', letterSpacing: 'var(--type-count-display-ls)', color: 'var(--tg-primary)' }}>
          {isPro ? results.total : Object.values(FREE_LIMITS).reduce((a, b) => a + b, 0)}
        </div>
        <div style={{ color: 'var(--text-muted)', fontSize: 14, margin: '4px 0 8px' }}>
          tags ready for <strong style={{ color: 'var(--text-heading)' }}>"{results.topic}"</strong> on {results.platform}
          {!isPro && <> · <button onClick={onGoPro} style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', color: 'var(--tg-primary)', fontSize: 14 }}>Go Pro for the full {results.total}</button></>}
        </div>
        {active === 'hashtags' && (
          <div style={{ fontSize: 12.5, color: 'var(--text-muted)', margin: '0 0 18px' }}>
            Recommended for {results.platform}: use about <strong style={{ color: 'var(--text-heading)' }}>{results.recommendedCount} {results.tagWord}</strong> — the top-ranked ones below are marked for you.
          </div>
        )}
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
          {active !== 'publish' && <React.Fragment>
            <Button variant="secondary" size="sm" onClick={exportTxt}>Export .txt</Button>
            <Button variant="secondary" size="sm" onClick={exportMarkdown}>Export .md</Button>
            <Button variant="secondary" size="sm" onClick={exportCsv}>{isPro ? 'Export .csv' : 'Export .csv 🔒'}</Button>
            <CopyFormatMenu items={visibleItems} label={current.label} />
          </React.Fragment>}
          <button onClick={toggleFavorite} title="Save this topic + platform to favorites" style={{ background: 'none', border: '1px solid var(--border-default)', borderRadius: 999, padding: '7px 13px', fontSize: 13, cursor: 'pointer', color: isFav ? 'var(--tg-primary)' : 'var(--text-body)' }}>{isFav ? '\u2605 Saved' : '\u2606 Save'}</button>
          <button onClick={shareLink} style={{ background: 'none', border: '1px solid var(--border-default)', borderRadius: 999, padding: '7px 13px', fontSize: 13, cursor: 'pointer', color: 'var(--text-body)' }}>Share link</button>
          {toastMsg && <span style={{ fontSize: 12, color: 'var(--tg-success, #1a8a4a)' }}>{toastMsg}</span>}
        </div>
      </div>

      {active === 'hashtags' && <StrategyPanel strategy={results.strategy} />}
      {active === 'hashtags' && <ExpandedTopics topics={results.expandedTopics} onPick={onExpandTopic} />}

      <CategoryTabs categories={categories} active={active} onChange={setActive} />

      {active === 'publish' && <PublishPackageView pkg={results.publishPackage} platform={results.platform} topic={results.topic} />}

      {active === 'hashtags' && (
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 16, alignItems: 'center' }}>
          <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search tags…" aria-label="Search within results" style={{ height: 34, borderRadius: 'var(--radius-full)', border: '1px solid var(--border-default)', padding: '0 14px', fontSize: 13, fontFamily: 'var(--font-sans)', minWidth: 140 }} />
          {['all', 'broad', 'medium', 'niche'].map(t => (
            <button key={t} onClick={() => setTierFilter(t)} className="tagly-focusable" style={{
              fontSize: 12.5, fontWeight: 600, padding: '6px 13px', borderRadius: 'var(--radius-full)', cursor: 'pointer',
              border: tierFilter === t ? '1px solid transparent' : '1px solid var(--border-default)',
              background: tierFilter === t ? 'var(--tg-ink)' : 'var(--surface-canvas)',
              color: tierFilter === t ? '#fff' : 'var(--text-body)',
            }}>{t === 'all' ? 'All tiers' : TIER_LABEL[t]}</button>
          ))}
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 4, background: 'var(--surface-soft)', borderRadius: 999, padding: 3 }}>
            {['purpose', 'topic'].map(g => (
              <button key={g} onClick={() => setGroupBy(g)} style={{ fontSize: 11.5, fontWeight: 600, padding: '5px 11px', borderRadius: 999, border: 'none', cursor: 'pointer', background: groupBy === g ? '#fff' : 'transparent', color: groupBy === g ? 'var(--text-heading)' : 'var(--text-muted)' }}>By {g}</button>
            ))}
          </div>
        </div>
      )}

      {active === 'hashtags' ? (
        <React.Fragment>
          {clusterKeys.map(key => {
            const group = visibleItems.filter(i => (groupBy === 'topic' ? i.topic === key : i.purpose === key));
            if (!group.length) return null;
            const avgConf = Math.round(group.reduce((s, i) => s + (i.confidence === 'High' ? 90 : i.confidence === 'Medium' ? 60 : 30), 0) / group.length);
            const avgSpec = Math.round(group.reduce((s, i) => s + (i.specificity || 50), 0) / group.length);
            const avgReach = Math.round(group.reduce((s, i) => s + (i.reach || 50), 0) / group.length);
            const heading = groupBy === 'topic' ? (key === 'platform' ? 'Platform culture' : key === 'general' ? 'General' : key.charAt(0).toUpperCase() + key.slice(1)) : PURPOSE_LABEL[key];
            return (
              <div key={key} style={{ marginBottom: 22 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 8, flexWrap: 'wrap' }}>
                  <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-heading)' }}>{heading}</span>
                  {groupBy === 'purpose' && <span style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>{PURPOSE_DESC[key]}</span>}
                  <div style={{ display: 'flex', gap: 12, marginLeft: 'auto' }}>
                    <Gauge label="Confidence" value={avgConf} color="var(--tg-primary)" />
                    <Gauge label="Specificity" value={avgSpec} color="var(--tg-success, #1a8a4a)" />
                    <Gauge label="Reach" value={avgReach} color="#e0a11a" />
                  </div>
                </div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
                  {group.map(item => (
                    <div key={item.tag} style={{ display: 'inline-flex', flexDirection: 'column', alignItems: 'center', gap: 3 }}>
                      <TagChip
                        label={item.tag}
                        copied={copiedId === item.tag}
                        selected={selected.has(item.tag)}
                        onClick={() => { copyOne(item.tag); toggle(item.tag); }}
                        title={`${item.reason || ''} \u00b7 confidence ${item.confidence} \u00b7 specificity ${item.specificity} \u00b7 reach ${item.reach} \u00b7 score ${item.score} \u00b7 ${item.competition} competition`}
                        aria-label={`Copy ${item.tag}, ${PURPOSE_LABEL[item.purpose]}, confidence ${item.confidence}`}
                      />
                      {item.tier && <span style={{ fontSize: 9.5, fontWeight: 600, color: TIER_COLOR[item.tier], textTransform: 'uppercase', letterSpacing: '0.04em' }}>{TIER_LABEL[item.tier]}</span>}
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
        </React.Fragment>
      ) : active !== 'publish' && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
          {visibleItems.map(item => (
            <TagChip
              key={item.tag}
              label={item.tag}
              copied={copiedId === item.tag}
              selected={selected.has(item.tag)}
              onClick={() => { copyOne(item.tag); toggle(item.tag); }}
              title={item.reason || `score ${item.score}`}
              aria-label={`Copy ${item.tag}`}
            />
          ))}
        </div>
      )}
      {active === 'hashtags' && visibleItems.length === 0 && (
        <p style={{ fontSize: 13.5, color: 'var(--text-muted)', textAlign: 'center', padding: '24px 0' }}>No tags match your search or filter.</p>
      )}

      {!isPro && active !== 'publish' && lockedCount > 0 && (
        <Card style={{ marginTop: 16, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
          <div>
            <Badge variant="pro" style={{ marginBottom: 6 }}>Pro</Badge>
            <div style={{ fontSize: 14, color: 'var(--text-heading)', fontWeight: 600 }}>{lockedCount} more {current.label.toLowerCase()} ready</div>
            <div style={{ fontSize: 13, color: 'var(--text-muted)' }}>Unlock the full ranked set, CSV export, and saved history for $3/mo.</div>
          </div>
          <Button size="sm" onClick={onGoPro}>Go Pro</Button>
        </Card>
      )}

      {active !== 'publish' && (
        <p style={{ fontSize: 12.5, color: 'var(--text-muted)', marginTop: 18 }}>
          Click any tag to copy it individually. Scores are a relative popularity proxy (0–99); competition, specificity, and reach gauges are illustrative in this prototype.
        </p>
      )}

      {!isPro && active !== 'publish' && <AdSlot />}
    </div>
  );
}

window.TaglyResults = { ResultsPanel };
