// Share modal — copy link, QR, friend challenge
const ShareModal = ({ profile, score, mode, onClose }) => {
  const t = window.MP_I18N.t;
  const lang = window.MP_I18N.getLang();
  const [tab, setTab] = React.useState('challenge');
  const [copied, setCopied] = React.useState(false);

  const url = window.location.origin + window.location.pathname;
  const shareUrl = `${url}?challenge=${encodeURIComponent(profile.firstName)}&s=${score || profile.points}&m=${mode || 'time_attack'}`;
  const shareText = t('share_text', { score: score || profile.points });

  const copy = async () => {
    try {
      await navigator.clipboard.writeText(shareUrl);
      setCopied(true);
      window.MP_SOUND.celebrate();
      setTimeout(() => setCopied(false), 1500);
    } catch {}
  };

  const nativeShare = async () => {
    if (navigator.share) {
      try {
        await navigator.share({ title: t('share_title'), text: shareText, url: shareUrl });
      } catch {}
    } else copy();
  };

  // QR via Google Charts (offline-friendly fallback: shows code)
  const qrSrc = `https://api.qrserver.com/v1/create-qr-code/?size=240x240&data=${encodeURIComponent(profile.schoolCode ? url + '?school=' + profile.schoolCode : url)}&color=1a0b2e&bgcolor=ffffff`;

  return (
    <div className="modal-wrap" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="row">
          <button className={'tab' + (tab === 'challenge' ? ' active' : '')} onClick={() => setTab('challenge')}>{t('challenge_friend')}</button>
          <button className={'tab' + (tab === 'qr' ? ' active' : '')} onClick={() => setTab('qr')}>{t('qr_for_class')}</button>
        </div>

        {tab === 'challenge' ? (
          <div className="mt-md">
            <Mascot id={profile.mascot || 'pixel'} size={100} />
            <div className="h-2 mt-md">{t('share_title')}</div>
            <div className="big-number" style={{ fontSize: 64 }}>{score || profile.points}</div>
            <div className="caption">{shareText}</div>
            <div className="col mt-md">
              <button className="btn btn-primary btn-block" onClick={nativeShare}>📤 {t('share_score')}</button>
              <button className="btn btn-cyan btn-block" onClick={copy}>
                {copied ? '✓ ' + t('copied') : '🔗 ' + t('copy_link')}
              </button>
            </div>
          </div>
        ) : (
          <div className="mt-md">
            <div className="h-2">{t('school_code')}</div>
            <div className="big-number" style={{ fontSize: 56, color: 'var(--cyan)' }}>{profile.schoolCode || '—'}</div>
            <div className="caption">{lang === 'es' ? 'Compártelo con tus amigos para entrar a la misma escuela' : 'Share with friends to join the same school'}</div>
            <div className="card-pop mt-md" style={{ background: 'white', padding: 12, display: 'inline-block' }}>
              <img src={qrSrc} alt="QR" width="200" height="200" onError={e => e.currentTarget.style.display='none'} />
            </div>
            <div className="caption mt-sm">{lang === 'es' ? 'Escanea para abrir' : 'Scan to open'}</div>
          </div>
        )}

        <button className="btn btn-ghost btn-block mt-md" onClick={onClose}>✕ {t('back')}</button>
      </div>
    </div>
  );
};

window.ShareModal = ShareModal;
