/* certificate.jsx — Cisco Arena certificate + feedback gate
 * Requires React 18 + Babel standalone.
 * For PNG download, load html2canvas before this file:
 * <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
 */

(function() {
  var useState = React.useState;
  var useMemo = React.useMemo;

  function clamp(n, min, max) {
    return Math.max(min, Math.min(max, n));
  }

  function fmtNum(n) {
    return Number(n || 0).toLocaleString();
  }

  function ordinal(n) {
    var v = Number(n || 0);
    if (!v) return '—';
    var mod10 = v % 10;
    var mod100 = v % 100;
    if (mod10 === 1 && mod100 !== 11) return v + 'st';
    if (mod10 === 2 && mod100 !== 12) return v + 'nd';
    if (mod10 === 3 && mod100 !== 13) return v + 'rd';
    return v + 'th';
  }

  function rankLine(rank, totalPlayers, isWinner) {
    if (isWinner || Number(rank) === 1) return '🏆 1st Place — Champion';
    return ordinal(rank) + ' of ' + Number(totalPlayers || 0) + ' racers';
  }

  function podiumTone(rank, isWinner) {
    if (isWinner || Number(rank) === 1) return 'winner';
    if (Number(rank) === 2) return 'silver';
    if (Number(rank) === 3) return 'bronze';
    return 'finisher';
  }

  function certificateTitle(isWinner) {
    return isWinner ? 'Certificate of Champions' : 'Certificate of Completion';
  }

  function shareCopy(props) {
    var pieces = [
      'I just completed the Cisco Arena ISE challenge',
      props.rank && props.totalPlayers ? '— finished ' + ordinal(props.rank) + ' of ' + props.totalPlayers : '',
      props.finalScore != null ? 'with ' + fmtNum(props.finalScore) + ' points!' : 'and unlocked my certificate!',
      '🏆 #CiscoArena #ISE'
    ].filter(Boolean);
    return pieces.join(' ');
  }

  var ArenaCertificate = React.forwardRef(function ArenaCertificate(props, ref) {
    var tone = podiumTone(props.rank, props.isWinner);
    var rootRef = props.certificateRef || ref;
    var accentStyle = { '--team-accent': props.teamColor || '#00BCEB' };
    var champion = !!props.isWinner || Number(props.rank) === 1;

    return (
      <div className={'arena-certificate-shell tone-' + tone + ' theme-' + (props.themeId || 'cisco')}>
        <div ref={rootRef} className={'arena-certificate arena-certificate--' + (props.themeId || 'cisco') + ' is-' + tone} style={accentStyle}>
          <div className="arena-certificate__chrome" aria-hidden="true">
            <div className="arena-certificate__mesh"></div>
            <div className="arena-certificate__watermark">
              <span>c</span><span>i</span><span>s</span><span>c</span><span>o</span>
            </div>
            <div className="arena-certificate__theme-mark arena-certificate__theme-mark--gp"></div>
            <div className="arena-certificate__theme-mark arena-certificate__theme-mark--cup"></div>
          </div>

          <div className="arena-certificate__content">
            <div className="arena-certificate__topbar">
              <div>
                <div className="arena-certificate__eyebrow">Cisco Arena</div>
                <div className="arena-certificate__event">{props.eventName || 'Cisco Arena'}</div>
              </div>
              <div className={'arena-certificate__badge ' + (champion ? 'is-champion' : 'is-finish')}>{champion ? tc('🏆 CAMPEÓN') : tc('FINALISTA')}</div>
            </div>

            <div className="arena-certificate__main">
              <div className="arena-certificate__label">{certificateTitle(champion)}</div>
              <h1 className="arena-certificate__name">{props.playerName || 'Player Name'}</h1>
              <div className="arena-certificate__subtitle">
                {tc('otorgado por completar')} <strong>{props.moduleName || 'Cisco Identity Services Engine'}</strong>
              </div>

              <div className="arena-certificate__stats">
                <div className="arena-certificate__stat">
                  <span>{tc('Equipo')}</span>
                  <strong style={{ color: props.teamColor || '#00BCEB' }}>{props.teamName || tc('Equipo Cisco Arena')}</strong>
                </div>
                <div className="arena-certificate__stat">
                  <span>{tc('Posición final')}</span>
                  <strong>{rankLine(props.rank, props.totalPlayers, champion)}</strong>
                </div>
                <div className="arena-certificate__stat">
                  <span>{tc('Puntuación final')}</span>
                  <strong>{fmtNum(props.finalScore)} pts</strong>
                </div>
                <div className="arena-certificate__stat">
                  <span>{tc('Fecha')}</span>
                  <strong>{props.date || tc('Fecha del evento')}</strong>
                </div>
              </div>
            </div>

            <div className="arena-certificate__footer">
              <div className="arena-certificate__signature">
                <span className="arena-certificate__signature-line"></span>
                <strong>Cisco Arena · {props.date || 'Event date'}</strong>
              </div>
              <div className="arena-certificate__seal">
                <div className="arena-certificate__seal-rank">{champion ? '1' : ordinal(props.rank)}</div>
                <div className="arena-certificate__seal-copy">of {props.totalPlayers || '—'} racers</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  });

  function CertificateActions(props) {
    var _status = useState('idle'), status = _status[0], setStatus = _status[1];
    var shareText = useMemo(function() {
      return shareCopy(props);
    }, [props.playerName, props.rank, props.totalPlayers, props.finalScore, props.eventName]);
    var shareUrl = props.shareUrl || 'https://www.cisco.com';

    function resolveNode() {
      if (!props.certificateRef) return null;
      return props.certificateRef.current || props.certificateRef;
    }

    function downloadPng() {
      var node = resolveNode();
      if (!node) {
        setStatus('missing-ref');
        return;
      }
      if (typeof window.html2canvas !== 'function') {
        setStatus('missing-lib');
        return;
      }
      setStatus('rendering');
      window.html2canvas(node, {
        backgroundColor: null,
        scale: Math.max(2, window.devicePixelRatio || 1),
        useCORS: true
      }).then(function(canvas) {
        var link = document.createElement('a');
        var safeName = String(props.playerName || 'player').replace(/[^a-z0-9]+/gi, '-').replace(/^-|-$/g, '').toLowerCase() || 'player';
        link.href = canvas.toDataURL('image/png');
        link.download = safeName + '-cisco-arena-certificate.png';
        link.click();
        setStatus('downloaded');
      }).catch(function() {
        setStatus('error');
      });
    }

    function shareToLinkedIn() {
      window.open('https://www.linkedin.com/sharing/share-offsite/?url=' + encodeURIComponent(shareUrl), '_blank', 'noopener,noreferrer');
    }

    function copyShareText() {
      navigator.clipboard.writeText(shareText).then(function() {
        setStatus('copied');
      }).catch(function() {
        setStatus('copy-error');
      });
    }

    return (
      <div className="certificate-actions">
        <div className="certificate-actions__row">
          <button type="button" className="certificate-btn certificate-btn--primary" onClick={downloadPng}>{tc('📥 Descargar PNG')}</button>
          <button type="button" className="certificate-btn" onClick={shareToLinkedIn}>{tc('🔗 Compartir en LinkedIn')}</button>
          <button type="button" className="certificate-btn" onClick={copyShareText}>{tc('Copiar texto')}</button>
        </div>
        <div className="certificate-actions__hint">
          {status === 'rendering' ? tc('Generando PNG del certificado…') : null}
          {status === 'downloaded' ? tc('PNG descargado.') : null}
          {status === 'copied' ? tc('Texto de LinkedIn copiado.') : null}
          {status === 'missing-lib' ? tc('html2canvas no cargado.') : null}
          {status === 'missing-ref' ? tc('Referencia del certificado no encontrada.') : null}
          {status === 'error' ? tc('No se pudo generar el certificado.') : null}
          {status === 'copy-error' ? tc('No se pudo copiar el texto.') : null}
          {status === 'idle' ? tc('Descarga un PNG listo para redes o copia el texto para LinkedIn.') : null}
        </div>
      </div>
    );
  }

  function StarPicker(props) {
    return (
      <div className="feedback-stars" role="radiogroup" aria-label={props.label}>
        {[1,2,3,4,5].map(function(value) {
          return (
            <button
              key={value}
              type="button"
              className={'feedback-stars__star' + (props.value >= value ? ' is-on' : '')}
              onClick={function() { props.onChange(value); }}
              aria-pressed={props.value === value}
            >
              ★
            </button>
          );
        })}
      </div>
    );
  }

  function FeedbackGate(props) {
    var _form = useState({
      stars: { experience: 0, content: 0, difficulty: 0 },
      nps: null,
      improve: '',
      love: ''
    }), form = _form[0], setForm = _form[1];
    var _submit = useState('idle'), submitState = _submit[0], setSubmitState = _submit[1];

    var isValid = form.stars.experience > 0 && form.stars.content > 0 && form.stars.difficulty > 0 && form.nps != null;

    function setStar(key, value) {
      setForm(function(prev) {
        return Object.assign({}, prev, {
          stars: Object.assign({}, prev.stars, { [key]: value })
        });
      });
    }

    function setField(key, value) {
      setForm(function(prev) { return Object.assign({}, prev, { [key]: value }); });
    }

    function submit(e) {
      e.preventDefault();
      if (!isValid || !props.onSubmit) return;
      setSubmitState('submitting');
      Promise.resolve(props.onSubmit({
        stars: {
          experience: form.stars.experience,
          content: form.stars.content,
          difficulty: form.stars.difficulty
        },
        nps: form.nps,
        improve: form.improve,
        love: form.love
      })).then(function() {
        setSubmitState('done');
      }).catch(function() {
        setSubmitState('error');
      });
    }

    return (
      <form className="feedback-gate" onSubmit={submit}>
        <div className="feedback-gate__eyebrow">{tc('Cisco Arena · desbloqueo final')}</div>
        <h2 className="feedback-gate__title">{tc('Cuéntanos sobre la experiencia')}</h2>
        <p className="feedback-gate__intro">{tc('Comparte feedback rápido para desbloquear tu certificado y tarjeta lista para LinkedIn.')}</p>

        <div className="feedback-gate__grid">
          <div className="feedback-card">
            <label className="feedback-card__label">{tc('Experiencia')}</label>
            <StarPicker label="Experience" value={form.stars.experience} onChange={function(v) { setStar('experience', v); }} />
          </div>
          <div className="feedback-card">
            <label className="feedback-card__label">{tc('Calidad del contenido')}</label>
            <StarPicker label="Content quality" value={form.stars.content} onChange={function(v) { setStar('content', v); }} />
          </div>
          <div className="feedback-card">
            <label className="feedback-card__label">{tc('Dificultad')} <span>{tc('(3 = ideal)')}</span></label>
            <StarPicker label="Difficulty" value={form.stars.difficulty} onChange={function(v) { setStar('difficulty', v); }} />
          </div>
        </div>

        <div className="feedback-card feedback-card--nps">
          <label className="feedback-card__label">{tc('¿Lo recomendarías a un colega?')}</label>
          <div className="feedback-nps__meta"><span>{tc('Poco probable')}</span><strong>{form.nps != null ? form.nps : '—'}</strong><span>{tc('Sin duda')}</span></div>
          <input className="feedback-nps" type="range" min="0" max="10" step="1" value={form.nps == null ? 0 : form.nps} onChange={function(e) { setField('nps', clamp(Number(e.target.value), 0, 10)); }} />
          <div className="feedback-nps__ticks">{[0,1,2,3,4,5,6,7,8,9,10].map(function(n) { return <span key={n}>{n}</span>; })}</div>
        </div>

        <div className="feedback-gate__grid feedback-gate__grid--text">
          <div className="feedback-card">
            <label className="feedback-card__label">{tc('¿Qué mejorarías?')}</label>
            <textarea value={form.improve} onChange={function(e) { setField('improve', e.target.value); }} placeholder={tc('Opcional — ritmo, contenido, proyector, flujo en el teléfono…')}></textarea>
          </div>
          <div className="feedback-card">
            <label className="feedback-card__label">{tc('¿Qué te encantó?')}</label>
            <textarea value={form.love} onChange={function(e) { setField('love', e.target.value); }} placeholder={tc('Opcional — energía, formato de quiz, competencia, tema de equipos…')}></textarea>
          </div>
        </div>

        <div className="feedback-gate__footer">
          <button type="submit" className="certificate-btn certificate-btn--primary feedback-gate__submit" disabled={!isValid || submitState === 'submitting'}>
            {submitState === 'submitting' ? tc('Desbloqueando…') : tc('Desbloquear mi certificado')}
          </button>
          <div className="feedback-gate__status">
            {submitState === 'idle' ? tc('Las calificaciones y NPS son obligatorias. Los comentarios son opcionales.') : null}
            {submitState === 'done' ? tc('Feedback guardado — certificado listo.') : null}
            {submitState === 'error' ? tc('No se pudo enviar el feedback. Inténtalo de nuevo.') : null}
          </div>
        </div>
      </form>
    );
  }

  window.ArenaCertificate = ArenaCertificate;
  window.CertificateActions = CertificateActions;
  window.FeedbackGate = FeedbackGate;
})();
