/* cst-share.jsx — the virality layer: identity badges, compare/leaderboard line,
   live counter, the peak-emotion share button, and the ShareSheet modal that
   generates + distributes the branded result card. Exported to window.
   Loads after cst-share-card.jsx. */

const { useState: _shS, useEffect: _shE, useRef: _shR } = React;
const _SC = window.CST;
const { FONT: _sF, TEXT: _sT, HAZE: _sH, HAZE_DIM: _sHD, HAIR: _sHR, GLASS: _sG, GLASS_HI: _sGH, INK: _sI, INK_DEEP: _sID, AMBER: _sAM } = _SC;

const SHORTLINK = 'cstechpartner.com';

// ---------- spec builders (one per tool result) ----------------------------
function ideaBadge(s) { return s >= 85 ? 'Founder-grade idea' : s >= 70 ? 'Worth building' : s >= 55 ? 'Rough diamond' : 'Back to the whiteboard'; }
function swotBadge(s) { return s >= 70 ? 'Decision-ready operator' : s >= 55 ? 'On the clock' : 'At a crossroads'; }

function ideaSpec(verdict, idea, accent) {
  const s = verdict.score, badge = ideaBadge(s);
  const v = verdict.verdict || '';
  const pct = window.CST_STATS.percentileFromScore(s);
  return {
    tool: 'Idea check', accent, heroKind: 'ring', ringPct: s, heroValue: s, heroUnit: '/ 100',
    badge, verdict: v, subject: idea,
    leaderboard: `Sharper than ${pct}% of ideas checked this week.`,
    challenge: `Can your idea beat ${s}?`, hookCaps: true,
    shortlink: SHORTLINK,
    captions: {
      bold: `${s}/100. ${badge}. I just pressure-tested my idea on CS Tech — think yours scores higher? Prove it.`,
      humble: `Ran my idea through CS Tech's idea check: ${s}/100 — “${v}”. Genuinely useful if you're building something.`,
      challenger: `My idea scored ${s}/100 on CS Tech. Bet you can't beat it →`,
    },
  };
}

function swotSpec(board, accent) {
  const s = board.score, badge = swotBadge(s);
  const pct = window.CST_STATS.percentileFromScore(s);
  return {
    tool: 'SWOT', accent, heroKind: 'ring', ringPct: s, heroValue: s, heroUnit: 'READY',
    badge, verdict: board.headline || '',
    leaderboard: `Clearer than ${pct}% of operators who ran this week.`,
    challenge: `How ready are you? →`,
    shortlink: SHORTLINK,
    captions: {
      bold: `Decision-readiness: ${s}/100. ${badge}. CS Tech's SWOT read is blunt and actually useful.`,
      humble: `Ran my business through CS Tech's living SWOT. Readiness ${s}/100 — “${board.headline}”.`,
      challenger: `${s}/100 decision-ready on CS Tech. Where do you land? →`,
    },
  };
}

function priceJobSpec(r, accent) {
  const hourly = _SC.moneyFull(r.effHourly);
  const badge = r.flag === 'losing' ? 'Running at a loss' : r.flag === 'under' ? 'Certified under-priced' : 'Priced like a pro';
  const u = window.CST_STATS.underpricedPct();
  const leaderboard = (r.flag === 'under' || r.flag === 'losing')
    ? `You're in good company — ${u}% of jobs run here were under-priced.`
    : `Only ${100 - u}% of jobs run here are priced this sharply.`;
  return {
    tool: 'Price-It', accent, heroKind: 'plain', heroValue: hourly, heroUnit: '/ hour, really',
    badge, verdict: r.headline || '',
    leaderboard,
    challenge: `What's your real hourly? →`,
    shortlink: SHORTLINK,
    captions: {
      bold: `Turns out my time was really earning ${hourly}/hr. ${badge}. Found out in 60s with CS Tech's Price-It.`,
      humble: `Used CS Tech's Price-It on my work — my true effective rate is ${hourly}/hr. Worth knowing.`,
      challenger: `My time earns ${hourly}/hr. What's yours actually worth? →`,
    },
  };
}

function priceBizSpec(r, accent) {
  const val = _SC.money(r.likely);
  const badge = (r.profitMargin != null && r.profitMargin < 10) ? 'Margin-constrained' : 'Sellable asset';
  return {
    tool: 'Price-It', accent, heroKind: 'plain', heroValue: val, heroUnit: 'ballpark value',
    badge, verdict: r.headline || '',
    leaderboard: `A starting band — not an appraisal.`,
    challenge: `What's your business worth? →`,
    shortlink: SHORTLINK,
    captions: {
      bold: `My business ballparks around ${val}. ${badge}. Got the number in 60s with CS Tech's Price-It.`,
      humble: `Ran a quick valuation on CS Tech's Price-It: roughly ${val}. A useful gut-check.`,
      challenger: `${val} ballpark. Think your business is worth more? Find out →`,
    },
  };
}

// ---------- on-screen virality components -----------------------------------
function IdentityBadge({ label, accent, style }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 8, alignSelf: 'flex-start',
      padding: '7px 13px', borderRadius: 99, background: accent + '1c', border: `1px solid ${accent}66`,
      fontFamily: _sF, fontSize: 11.5, fontWeight: 800, letterSpacing: 1.5, textTransform: 'uppercase', color: accent, ...style,
    }}>
      <span style={{ width: 6, height: 6, borderRadius: 99, background: accent, boxShadow: `0 0 8px ${accent}` }} />
      {label}
    </span>);
}

function LeaderboardLine({ text, accent }) {
  // [XX%] tokens are highlighted as fill-me placeholders
  const parts = String(text).split(/(\[[^\]]+\])/g);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontFamily: _sF, fontSize: 12, color: _sH, lineHeight: 1.4 }}>
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={accent} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
        <path d="M4 20V10M10 20V4M16 20v-8M22 20H2" />
      </svg>
      <span>{parts.map((p, i) => /^\[.*\]$/.test(p)
        ? <span key={i} style={{ color: accent, fontWeight: 700 }}>{p}</span>
        : <span key={i}>{p}</span>)}</span>
    </div>);
}

// "● [N] ideas pressure-tested this week" — now provided by cst-stats.jsx
// (LiveCounter is defined there, time-seeded + persisted, no login needed).

// the peak-emotion share button — prominent, lightly pulsing
function PeakShare({ accent, onShare, label = 'Share your score' }) {
  const [hover, setHover] = _shS(false);
  return (
    <button onClick={onShare} onPointerEnter={() => setHover(true)} onPointerLeave={() => setHover(false)}
      style={{
        width: '100%', border: 'none', borderRadius: 13, cursor: 'pointer', padding: '15px 18px',
        fontFamily: _sF, fontSize: 15, fontWeight: 800, color: _sI, background: accent, letterSpacing: 0.3,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9,
        boxShadow: `0 0 0 1px ${accent}, 0 10px 30px -8px ${accent}`,
        transform: hover ? 'translateY(-1px)' : 'none', transition: 'transform .18s, box-shadow .2s',
        animation: hover ? 'none' : 'cstShareGlow 2.4s ease-in-out infinite',
      }}>
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={_sI} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="18" cy="5" r="3" /><circle cx="6" cy="12" r="3" /><circle cx="18" cy="19" r="3" />
        <line x1="8.6" y1="10.7" x2="15.4" y2="6.3" /><line x1="8.6" y1="13.3" x2="15.4" y2="17.7" />
      </svg>
      {label}
    </button>);
}

window.CST_SHARE = {
  SHORTLINK, ideaSpec, swotSpec, priceJobSpec, priceBizSpec,
  IdentityBadge, LeaderboardLine, PeakShare,
};
Object.assign(window, { IdentityBadge, LeaderboardLine, PeakShare });
