// In-app sertifika görüntüleme sayfası — modül bitiminde gösterilir
function CertificatePage({ certId, moduleId, setPage }) {
  const t = window.t;
  const isEn = window.LANG === 'en';
  const data = window.APP_DATA;
  const mod = data.modules[moduleId];

  const colorMap = {
    moss: '#4F9D52', sun: '#F2A63B', coral: '#E86A4F',
    lavender: '#8A7AD1', sky: '#5CA5C7', rose: '#D6739A',
  };
  const mainColor = colorMap[mod.color];

  const certUrl = `${location.origin}/sertifika/${certId}`;
  const svgUrl = `${location.origin}/sertifika/${certId}.svg?lang=${isEn ? 'en' : 'tr'}`;
  const shareText = (t('cert.share_text') || '').replace('{title}', mod.title);

  const [copied, setCopied] = useState(false);
  const [busy, setBusy] = useState(null); // 'png' | 'pdf' | null

  const copyLink = async () => {
    try {
      await navigator.clipboard.writeText(certUrl);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {}
  };

  // SVG'yi 2400x1600 PNG canvas'ına çevir, dataURL döndür
  const renderToPng = async () => {
    const resp = await fetch(svgUrl);
    const svgText = await resp.text();
    const blob = new Blob([svgText], { type: 'image/svg+xml' });
    const url = URL.createObjectURL(blob);

    try {
      const img = new Image();
      img.crossOrigin = 'anonymous';
      await new Promise((resolve, reject) => {
        img.onload = resolve;
        img.onerror = () => reject(new Error('SVG yüklenemedi'));
        img.src = url;
      });

      const canvas = document.createElement('canvas');
      canvas.width = 2400; canvas.height = 1600; // 2x retina
      const ctx = canvas.getContext('2d');
      ctx.fillStyle = '#FBF7EE';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

      return { dataUrl: canvas.toDataURL('image/png', 0.95), canvas };
    } finally {
      URL.revokeObjectURL(url);
    }
  };

  const downloadPng = async () => {
    if (busy) return;
    setBusy('png');
    try {
      const { canvas } = await renderToPng();
      canvas.toBlob((blob) => {
        const a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = `claude-akademi-${certId}.png`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        setTimeout(() => URL.revokeObjectURL(a.href), 1000);
      }, 'image/png');
    } catch (err) {
      console.error('[png]', err);
      alert(t('app.connection_error'));
    } finally {
      setBusy(null);
    }
  };

  // jsPDF'i ihtiyaç anında yükle (CDN, ~370KB)
  const loadJsPdf = () => {
    if (window.jspdf && window.jspdf.jsPDF) return Promise.resolve(window.jspdf.jsPDF);
    return new Promise((resolve, reject) => {
      const s = document.createElement('script');
      s.src = 'https://cdn.jsdelivr.net/npm/jspdf@2.5.2/dist/jspdf.umd.min.js';
      s.onload = () => resolve(window.jspdf && window.jspdf.jsPDF);
      s.onerror = () => reject(new Error('jsPDF yüklenemedi'));
      document.head.appendChild(s);
    });
  };

  const downloadPdf = async () => {
    if (busy) return;
    setBusy('pdf');
    try {
      const [{ dataUrl }, JsPDF] = await Promise.all([renderToPng(), loadJsPdf()]);
      // A4 landscape: 297×210mm. Cert oranı 3:2, kenar boşlukları 10mm.
      const pdf = new JsPDF({ orientation: 'landscape', unit: 'mm', format: 'a4' });
      const pageW = 297, pageH = 210;
      const margin = 10;
      const maxW = pageW - margin * 2;
      const ratio = 1200 / 800; // 1.5
      let imgW = maxW;
      let imgH = imgW / ratio;
      if (imgH > pageH - margin * 2) {
        imgH = pageH - margin * 2;
        imgW = imgH * ratio;
      }
      const x = (pageW - imgW) / 2;
      const y = (pageH - imgH) / 2;
      pdf.addImage(dataUrl, 'PNG', x, y, imgW, imgH, undefined, 'FAST');
      pdf.save(`claude-akademi-${certId}.pdf`);
    } catch (err) {
      console.error('[pdf]', err);
      alert(t('app.connection_error'));
    } finally {
      setBusy(null);
    }
  };

  const btnStyle = (bg, color = '#fff') => ({
    display: 'inline-flex',
    alignItems: 'center',
    gap: 8,
    padding: '10px 16px',
    borderRadius: 999,
    background: bg,
    color,
    fontWeight: 600,
    fontSize: 13.5,
    textDecoration: 'none',
    border: 'none',
    cursor: 'pointer',
    transition: 'transform 0.15s, box-shadow 0.15s',
  });

  return (
    <div className="page fade-up" style={{ maxWidth: 980 }}>
      {/* Tebrik üst başlık */}
      <div style={{
        textAlign: 'center',
        marginBottom: 28,
        padding: '24px 20px',
        background: `linear-gradient(135deg, var(--${mod.color}-soft) 0%, transparent 80%)`,
        borderRadius: 'var(--r-xl)',
        border: '1px solid var(--line)',
      }}>
        <div style={{ fontSize: 44, marginBottom: 10 }}>🎉</div>
        <div className="kicker">{t('cert.kicker')}</div>
        <h1 className="page-title" style={{ fontSize: 36, marginTop: 10, marginBottom: 8 }}>{t('cert.title_ready')}</h1>
        <p style={{ fontSize: 15, color: 'var(--ink-2)', maxWidth: 540, margin: '0 auto', lineHeight: 1.55 }}>
          {t('cert.subtitle')}
        </p>
      </div>

      {/* Sertifika önizleme */}
      <div className="card" style={{
        padding: 14,
        marginBottom: 22,
        boxShadow: 'var(--shadow-md)',
      }}>
        <img
          src={svgUrl}
          alt={`${mod.title} sertifikası`}
          style={{
            width: '100%',
            height: 'auto',
            display: 'block',
            borderRadius: 'var(--r-md)',
          }}
        />
      </div>

      {/* Cert ID */}
      <div style={{
        textAlign: 'center',
        marginBottom: 20,
        fontFamily: 'var(--font-mono)',
        fontSize: 11,
        color: 'var(--ink-3)',
        letterSpacing: '0.08em',
      }}>
        {t('cert.id_label')}: <strong>#{certId}</strong>
      </div>

      {/* Aksiyonlar */}
      <div className="row" style={{ gap: 10, flexWrap: 'wrap', justifyContent: 'center', marginBottom: 28 }}>
        <a
          href={`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(certUrl)}`}
          target="_blank"
          rel="noopener noreferrer"
          style={btnStyle('#0A66C2')}
          onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-2px)'}
          onMouseLeave={e => e.currentTarget.style.transform = 'translateY(0)'}
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M20.45 20.45h-3.55v-5.57c0-1.33-.03-3.04-1.85-3.04-1.85 0-2.14 1.45-2.14 2.95v5.66H9.36V9h3.41v1.56h.05c.48-.9 1.64-1.85 3.37-1.85 3.6 0 4.27 2.37 4.27 5.46v6.28zM5.34 7.43a2.06 2.06 0 1 1 0-4.12 2.06 2.06 0 0 1 0 4.12zm1.78 13.02H3.56V9h3.56v11.45zM22.22 0H1.77C.79 0 0 .77 0 1.72v20.56C0 23.23.79 24 1.77 24h20.45c.98 0 1.78-.77 1.78-1.72V1.72C24 .77 23.2 0 22.22 0z"/></svg>
          {t('cert.share_linkedin')}
        </a>
        <a
          href={`https://twitter.com/intent/tweet?text=${encodeURIComponent(shareText)}&url=${encodeURIComponent(certUrl)}`}
          target="_blank"
          rel="noopener noreferrer"
          style={btnStyle('#000')}
          onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-2px)'}
          onMouseLeave={e => e.currentTarget.style.transform = 'translateY(0)'}
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>
          {t('cert.share_twitter')}
        </a>
        <a
          href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(certUrl)}`}
          target="_blank"
          rel="noopener noreferrer"
          style={btnStyle('#1877F2')}
          onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-2px)'}
          onMouseLeave={e => e.currentTarget.style.transform = 'translateY(0)'}
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>
          {t('cert.share_facebook')}
        </a>
        <button
          onClick={downloadPdf}
          disabled={busy === 'pdf'}
          style={{ ...btnStyle('var(--ink)'), opacity: busy === 'pdf' ? 0.6 : 1 }}
        >
          ⬇ {busy === 'pdf' ? '...' : t('cert.download_pdf')}
        </button>
        <button
          onClick={downloadPng}
          disabled={busy === 'png'}
          style={{ ...btnStyle('transparent', 'var(--ink)'), border: '1.5px solid var(--ink)', opacity: busy === 'png' ? 0.6 : 1 }}
          className="btn btn-ghost"
        >
          ⬇ {busy === 'png' ? '...' : t('cert.download_png')}
        </button>
        <button
          onClick={copyLink}
          style={btnStyle('transparent', 'var(--ink)')}
          className="btn btn-ghost"
        >
          🔗 {copied ? t('cert.link_copied') : t('cert.copy_link')}
        </button>
        <a
          href={certUrl}
          target="_blank"
          rel="noopener noreferrer"
          style={btnStyle('transparent', 'var(--ink)')}
          className="btn btn-ghost"
        >
          ↗ {t('cert.view_public')}
        </a>
      </div>

      {/* Devam butonu */}
      <div style={{ textAlign: 'center' }}>
        <button
          className="btn"
          style={{ background: mainColor, color: '#fff', padding: '14px 32px', fontSize: 15 }}
          onClick={() => setPage('path')}
        >
          {t('cert.continue')} →
        </button>
      </div>
    </div>
  );
}

window.CertificatePage = CertificatePage;
