// Pet MBTI — shareable result (a link friends can open + a keepsake PNG).
// Exports: ShareModal, drawShareCard
const SC = window.PM_C;
const SS = window.PM_STR;
const { PawIcon, Btn } = window;

// draw a 1080×1350 keepsake card for a type; returns a canvas
async function drawShareCard(type) {
  const g = type.colors;
  const W = 1080, H = 1350;
  const cv = document.createElement('canvas');
  cv.width = W; cv.height = H;
  const ctx = cv.getContext('2d');

  try {
    await document.fonts.ready;
    await Promise.all([
      document.fonts.load('600 64px Fredoka'),
      document.fonts.load('500 40px Fredoka'),
      document.fonts.load('800 26px Nunito'),
      document.fonts.load('700 24px Nunito'),
    ]);
  } catch (e) { /* fall back to system */ }

  const rr = (x, y, w, h, r) => { ctx.beginPath(); ctx.roundRect(x, y, w, h, r); };

  ctx.fillStyle = SC.panel; ctx.fillRect(0, 0, W, H);

  const grad = ctx.createLinearGradient(0, 0, W, 880);
  grad.addColorStop(0, g.mid); grad.addColorStop(1, g.deep);
  ctx.fillStyle = grad; ctx.fillRect(0, 0, W, 880);

  ctx.textBaseline = 'alphabetic';
  ctx.fillStyle = 'rgba(255,255,255,0.9)';
  ctx.font = "800 30px Nunito"; ctx.textAlign = 'left';
  ctx.fillText(SS.cardBrand, 70, 120);
  ctx.textAlign = 'right'; ctx.font = "600 34px Fredoka";
  ctx.save(); ctx.fillStyle = '#fff';
  const code = type.code.split('');
  let cx = W - 70;
  for (let i = code.length - 1; i >= 0; i--) { const ch = code[i]; const w = ctx.measureText(ch).width; cx -= w; ctx.fillText(ch, cx + w, 120); cx -= 12; }
  ctx.restore();

  const px = 70, py = 190, pw = W - 140, ph = 560, pad = 16, rad = 34;
  ctx.save();
  ctx.shadowColor = 'rgba(0,0,0,0.22)'; ctx.shadowBlur = 46; ctx.shadowOffsetY = 22;
  ctx.fillStyle = '#fff'; rr(px, py, pw, ph, rad); ctx.fill();
  ctx.restore();
  const img = new Image(); img.src = type.img;
  await new Promise((res) => { img.onload = res; img.onerror = res; });
  const ix = px + pad, iy = py + pad, iw = pw - pad * 2, ih = ph - pad * 2;
  ctx.save(); rr(ix, iy, iw, ih, rad - 12); ctx.clip();
  const s = Math.max(iw / img.width, ih / img.height);
  const dw = img.width * s, dh = img.height * s;
  ctx.drawImage(img, ix + (iw - dw) / 2, iy + (ih - dh) / 2, dw, dh);
  ctx.restore();

  ctx.textAlign = 'center';
  ctx.fillStyle = SC.muted; ctx.font = "800 26px Nunito";
  ctx.fillText(SS.cardYourPet, W / 2, 960);
  ctx.fillStyle = SC.ink; ctx.font = "600 76px Fredoka";
  ctx.fillText(type.nick, W / 2, 1040);

  ctx.fillStyle = g.deep; ctx.font = "500 italic 40px Fredoka";
  const words = ('“' + type.tagline + '”').split(' ');
  const maxW = W - 200; let line = '', ly = 1110; const lines = [];
  for (const wd of words) { const test = line ? line + ' ' + wd : wd; if (ctx.measureText(test).width > maxW && line) { lines.push(line); line = wd; } else line = test; }
  if (line) lines.push(line);
  lines.forEach((l, i) => ctx.fillText(l, W / 2, ly + i * 50));

  const fy = 1270;
  ctx.fillStyle = g.mid;
  const paw = (px0, py0, sc) => {
    ctx.save(); ctx.translate(px0, py0); ctx.scale(sc, sc);
    const e = (x, y, rx, ry) => { ctx.beginPath(); ctx.ellipse(x, y, rx, ry, 0, 0, Math.PI * 2); ctx.fill(); };
    e(16, 21, 7, 6); e(8, 12, 3, 3.6); e(16, 9, 3.1, 3.8); e(24, 12, 3, 3.6);
    ctx.restore();
  };
  ctx.textAlign = 'center'; ctx.font = "800 30px Nunito"; ctx.fillStyle = SC.ink;
  const brand = 'Paws';
  const bw = ctx.measureText(brand).width;
  const totalW = 40 + bw;
  const startX = W / 2 - totalW / 2;
  paw(startX, fy - 26, 1.0);
  ctx.textAlign = 'left'; ctx.font = "600 36px Fredoka"; ctx.fillStyle = SC.ink;
  ctx.fillText(brand, startX + 44, fy);
  ctx.textAlign = 'center'; ctx.font = "700 26px Nunito"; ctx.fillStyle = SC.muted;
  ctx.fillText(SS.cardTagline, W / 2, fy + 40);

  return cv;
}

function ShareModal({ type, pct, onClose }) {
  const g = type.colors;
  const [url, setUrl] = React.useState(null);        // keepsake image data URL
  const blobRef = React.useRef(null);
  const [status, setStatus] = React.useState('');
  const [copied, setCopied] = React.useState(false);

  // The shareable link — opens straight to this exact result (right type + bars).
  const shareLink = React.useMemo(() => window.pmShareUrl(type.code, pct), [type.code, pct]);
  const shareText = SS.shareText(type.nick, type.code);

  React.useEffect(() => {
    let alive = true;
    drawShareCard(type).then((cv) => {
      if (!alive) return;
      setUrl(cv.toDataURL('image/png'));
      cv.toBlob((b) => { blobRef.current = b; }, 'image/png');
    });
    return () => { alive = false; };
  }, [type.code]);

  const flash = (msg) => { setStatus(msg); setTimeout(() => setStatus(''), 2200); };

  const copyLink = async () => {
    try {
      await navigator.clipboard.writeText(shareLink);
    } catch (e) {
      // Fallback for browsers without the async clipboard API
      const ta = document.createElement('textarea');
      ta.value = shareLink; ta.style.position = 'fixed'; ta.style.opacity = '0';
      document.body.appendChild(ta); ta.select();
      try { document.execCommand('copy'); } catch (_) {}
      ta.remove();
    }
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const shareLinkNative = async () => {
    if (navigator.share) {
      try {
        await navigator.share({ title: SS.shareNativeTitle(type.nick), text: shareText, url: shareLink });
      } catch (e) { /* cancelled */ }
    } else {
      copyLink();
    }
  };

  const download = () => {
    const a = document.createElement('a');
    a.href = url; a.download = `paws-${type.code}-${type.nick.replace(/\s+/g, '')}.png`;
    document.body.appendChild(a); a.click(); a.remove();
    flash(SS.savedToDevice);
  };

  const shareImage = async () => {
    try {
      const file = new File([blobRef.current], `paws-${type.code}.png`, { type: 'image/png' });
      if (navigator.canShare && navigator.canShare({ files: [file] })) {
        await navigator.share({ files: [file], title: SS.shareNativeTitle(type.nick), text: shareText });
      } else download();
    } catch (e) { /* cancelled */ }
  };

  const canShareFiles = typeof navigator !== 'undefined' && navigator.canShare;

  const inputStyle = {
    flex: 1, minWidth: 0, border: 'none', background: 'transparent', outline: 'none',
    fontFamily: "'Nunito', sans-serif", fontWeight: 700, fontSize: 13, color: SC.ink2,
    padding: '12px 0 12px 14px', textOverflow: 'ellipsis',
  };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(44,35,28,0.5)',
      display: 'grid', placeItems: 'center', padding: 20, animation: 'pm-fade .2s ease', backdropFilter: 'blur(3px)' }}>
      <div onClick={(e) => e.stopPropagation()} className="pm-pop" style={{ background: SC.bg, borderRadius: 28,
        padding: '22px 22px 24px', maxWidth: 400, width: '100%', maxHeight: '92vh', overflowY: 'auto',
        boxShadow: '0 24px 60px rgba(0,0,0,0.3)', position: 'relative' }}>
        <button onClick={onClose} aria-label={SS.close} style={{ position: 'absolute', top: 14, right: 14, width: 38, height: 38,
          borderRadius: 999, border: 'none', background: SC.panel, cursor: 'pointer', fontSize: 20, color: SC.ink2, lineHeight: 1 }}>×</button>
        <h3 style={{ margin: '2px 0 4px', textAlign: 'center', fontFamily: "'Fredoka', sans-serif", fontWeight: 600, fontSize: 22, color: SC.ink }}>{SS.shareHead(type.nick)}</h3>
        <p style={{ margin: '0 0 16px', textAlign: 'center', fontFamily: "'Nunito', sans-serif", fontWeight: 700, fontSize: 13.5, color: SC.muted }}>{SS.shareSub}</p>

        {/* ── shareable link ── */}
        <div style={{ display: 'flex', alignItems: 'center', background: SC.panel, borderRadius: 14,
          border: `1px solid ${SC.line}`, overflow: 'hidden', boxShadow: '0 3px 12px rgba(168,107,52,0.06)' }}>
          <input readOnly value={shareLink} aria-label={SS.shareLinkBtn} style={inputStyle}
            onFocus={(e) => e.target.select()} />
          <button onClick={copyLink} style={{ flexShrink: 0, border: 'none', cursor: 'pointer', alignSelf: 'stretch',
            background: copied ? g.mid : g.deep, color: '#fff', fontFamily: "'Fredoka', sans-serif", fontWeight: 600,
            fontSize: 14, padding: '0 18px', transition: 'background .15s ease' }}>
            {copied ? SS.copied : SS.copy}
          </button>
        </div>
        <p style={{ margin: '8px 2px 0', fontFamily: "'Nunito', sans-serif", fontWeight: 700, fontSize: 11.5, color: SC.muted, textAlign: 'center' }}>
          {SS.shareNote(type.nick)}
        </p>

        <div style={{ marginTop: 14, display: 'flex', gap: 10 }}>
          <Btn onClick={shareLinkNative} color={g.deep} style={{ flex: 1 }}>
            <PawIcon size={17} color="#fff" /> {SS.shareLinkBtn}
          </Btn>
        </div>

        {/* ── keepsake image card ── */}
        <div style={{ marginTop: 22, display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ flex: 1, height: 1, background: SC.line }} />
          <span style={{ fontFamily: "'Nunito', sans-serif", fontWeight: 800, fontSize: 11.5, color: SC.muted, letterSpacing: '.5px' }}>{SS.orSaveCard}</span>
          <div style={{ flex: 1, height: 1, background: SC.line }} />
        </div>

        <div style={{ marginTop: 16, borderRadius: 18, overflow: 'hidden', boxShadow: `0 12px 30px ${g.deep}33`, background: SC.panel, minHeight: 220 }}>
          {url
            ? <img src={url} alt={`${type.nick} card`} style={{ width: '100%', display: 'block' }} />
            : <div style={{ display: 'grid', placeItems: 'center', height: 300 }}>
                <div className="pm-spin" style={{ width: 44, height: 44, borderRadius: 999, border: `4px solid ${SC.line}`, borderTopColor: g.mid }} />
              </div>}
        </div>

        <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
          <Btn kind="soft" onClick={canShareFiles ? shareImage : download} disabled={!url} style={{ width: '100%' }}>
            {canShareFiles ? SS.shareCardImg : SS.saveImg}
          </Btn>
          {canShareFiles && <Btn kind="ghost" onClick={download} disabled={!url} style={{ width: '100%' }}>{SS.saveImg}</Btn>}
          <div style={{ textAlign: 'center', minHeight: 18, fontFamily: "'Nunito', sans-serif", fontWeight: 800, fontSize: 12.5, color: g.deep }}>{status}</div>
        </div>

        {/* app CTA */}
        <div style={{ marginTop: 8, paddingTop: 18, borderTop: `1px solid ${SC.line}`, display: 'flex',
          flexDirection: 'column', alignItems: 'center', gap: 12, textAlign: 'center' }}>
          <p style={{ margin: 0, fontFamily: "'Nunito', sans-serif", fontWeight: 700, fontSize: 13.5, color: SC.ink2, textWrap: 'pretty' }}>
            {SS.shareAppCta(type.nick)}
          </p>
          <div style={{ display: 'flex', alignItems: 'center', gap: 18, flexWrap: 'wrap', justifyContent: 'center' }}>
            <window.AppStoreBadge />
            <window.AppQR size={84} />
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ShareModal, drawShareCard });
