// Certificate.jsx — printable achievement certificate.
// Opens as a modal overlay in screen mode; the @media print rules in styles.css
// hide everything else and expand it to a full A4/Letter page so window.print()
// produces a clean PDF.

function Certificate({ badge, kidName, earnedDate, catalog, logs, onClose }) {
  if (!badge) return null;

  const dateObj = earnedDate ? new Date(earnedDate) : new Date();
  const dateStr = dateObj.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });

  // Pick up to 4 relevant logged objects to name in the citation.
  const relevantLogs = Object.entries(logs || {})
    .map(([id, log]) => ({ obj: catalog.find(o => o.id === id), log }))
    .filter(x => x.obj)
    .sort((a, b) => (b.log.date || '').localeCompare(a.log.date || ''));

  const featured = (() => {
    if (badge.id === 'planet-hop') return relevantLogs.filter(x => x.obj.cat === 'Planet').slice(0, 3);
    if (badge.id === 'messier') return relevantLogs.filter(x => x.obj.tags?.includes('Messier')).slice(0, 3);
    if (badge.id === 'deep-sky') return relevantLogs.filter(x => x.obj.cat === 'Galaxy').slice(0, 1);
    if (badge.id === 'all-cats') return ['Moon', 'Planet', 'Star', 'Constellation', 'Nebula', 'Cluster', 'Galaxy']
      .map(c => relevantLogs.find(x => x.obj.cat === c))
      .filter(Boolean);
    return relevantLogs.slice(0, 4);
  })();

  const totalSeen = relevantLogs.length;

  return (
    <div className="cert-overlay" onClick={onClose}>
      <div className="cert-wrap" onClick={e => e.stopPropagation()}>
        <div className="cert-controls">
          <button className="cert-btn" onClick={() => {
            // Clone the cert into <body> so print has no ancestor interference.
            const page = document.getElementById('cert-page');
            if (!page) { window.print(); return; }
            const clone = page.cloneNode(true);
            clone.id = 'cert-print-clone';
            document.body.appendChild(clone);
            document.body.classList.add('printing');
            const cleanup = () => {
              document.body.classList.remove('printing');
              clone.remove();
              window.removeEventListener('afterprint', cleanup);
            };
            window.addEventListener('afterprint', cleanup);
            window.print();
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M3 5V2h8v3M3 10H1V5h12v5h-2M3 8h8v5H3z" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinejoin="round"/></svg>
            Print / Save as PDF
          </button>
          <button className="cert-btn cert-btn--ghost" onClick={onClose}>Close</button>
        </div>

        <div className="cert-page" id="cert-page">
          <CertificateBody
            badge={badge}
            kidName={kidName}
            dateStr={dateStr}
            featured={featured}
            totalSeen={totalSeen}
          />
        </div>
      </div>
    </div>
  );
}

function CertificateBody({ badge, kidName, dateStr, featured, totalSeen }) {
  return (
    <div className="cert">
      {/* corner ornaments */}
      <CertCorner pos="tl" />
      <CertCorner pos="tr" />
      <CertCorner pos="bl" />
      <CertCorner pos="br" />

      {/* decorative star field */}
      <div className="cert__stars" aria-hidden="true">
        {[...Array(40)].map((_, i) => {
          const x = (i * 73 + 13) % 100;
          const y = (i * 47 + 7) % 100;
          const r = 0.5 + ((i * 13) % 5) * 0.25;
          return <span key={i} className="cert__star" style={{ left: `${x}%`, top: `${y}%`, width: r, height: r }} />;
        })}
      </div>

      <div className="cert__frame">
        <div className="cert__header">
          <div className="cert__mark">
            <svg viewBox="0 0 80 80" width="56" height="56">
              <circle cx="40" cy="40" r="36" fill="none" stroke="currentColor" strokeWidth="1" opacity="0.4"/>
              <circle cx="40" cy="40" r="28" fill="none" stroke="currentColor" strokeWidth="0.7" opacity="0.3"/>
              <g stroke="currentColor" strokeWidth="1.2" strokeLinecap="round">
                <line x1="40" y1="16" x2="40" y2="22"/>
                <line x1="40" y1="58" x2="40" y2="64"/>
                <line x1="16" y1="40" x2="22" y2="40"/>
                <line x1="58" y1="40" x2="64" y2="40"/>
              </g>
              <circle cx="40" cy="40" r="3" fill="currentColor"/>
            </svg>
          </div>
          <div className="cert__org">
            <div className="cert__org-kicker">THE FIELD LOG · EST. STARDATE</div>
            <div className="cert__org-name">Stars We Have Seen &middot; GoUniverseGo</div>
            <div className="cert__org-sub">Certificate of Celestial Observation</div>
          </div>
        </div>

        <div className="cert__rule">
          <span className="cert__rule-dot" />
          <span className="cert__rule-dot" />
          <span className="cert__rule-dot" />
        </div>

        <div className="cert__preamble">This is to certify that the observer</div>

        <div className="cert__name">{kidName || 'Observer'}</div>

        <div className="cert__citation">
          has, through patient stargazing under their own dark sky, earned the rank of
        </div>

        <div className="cert__award">
          <CertBadgeIcon badge={badge} />
          <div className="cert__award-text">
            <div className="cert__award-name">{badge.name}</div>
            <div className="cert__award-desc">{prettyDesc(badge)}</div>
          </div>
        </div>

        {featured.length > 0 && (
          <div className="cert__observed">
            <div className="cert__observed-label">OBJECTS OBSERVED</div>
            <div className="cert__observed-list">
              {featured.map((x, i) => (
                <div key={i} className="cert__observed-row">
                  <span className="cert__observed-name">{x.obj.name}</span>
                  <span className="cert__observed-dots" />
                  <span className="cert__observed-date">{formatDate(x.log.date)}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        <div className="cert__footer">
          <div className="cert__sig">
            <svg className="cert__sig-line" viewBox="0 0 240 40" preserveAspectRatio="none">
              <path d="M4 30 C 30 10, 60 34, 90 20 S 140 8, 170 24 S 220 18, 236 26" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
            </svg>
            <div className="cert__sig-label">CHIEF OBSERVER</div>
          </div>
          <div className="cert__seal">
            <svg viewBox="0 0 120 120" width="100" height="100">
              <circle cx="60" cy="60" r="54" fill="none" stroke="currentColor" strokeWidth="1" opacity="0.5"/>
              <circle cx="60" cy="60" r="48" fill="none" stroke="currentColor" strokeWidth="0.5" opacity="0.5" strokeDasharray="2 3"/>
              <path id="cert-seal-path" d="M 60 12 A 48 48 0 1 1 59.9 12" fill="none"/>
              <text fill="currentColor" fontFamily="var(--font-mono)" fontSize="7" letterSpacing="2">
                <textPath xlinkHref="#cert-seal-path" startOffset="0">STARS WE HAVE SEEN · GOUNIVERSEGO · AD ASTRA ·</textPath>
              </text>
              <g transform="translate(60 60)">
                <g stroke="currentColor" strokeWidth="1" fill="none">
                  <line x1="0" y1="-20" x2="0" y2="20"/>
                  <line x1="-20" y1="0" x2="20" y2="0"/>
                  <line x1="-14" y1="-14" x2="14" y2="14"/>
                  <line x1="-14" y1="14" x2="14" y2="-14"/>
                </g>
                <circle cx="0" cy="0" r="3" fill="currentColor"/>
              </g>
            </svg>
          </div>
          <div className="cert__date">
            <div className="cert__date-value">{dateStr}</div>
            <div className="cert__date-label">DATE AWARDED</div>
          </div>
        </div>

        <div className="cert__meta">
          ENTRY NO. {String(hashCode(kidName + badge.id)).slice(-6).padStart(6, '0')} &nbsp;·&nbsp; {totalSeen} SIGHTING{totalSeen === 1 ? '' : 'S'} LOGGED
        </div>
      </div>
    </div>
  );
}

function CertCorner({ pos }) {
  return (
    <svg className={`cert__corner cert__corner--${pos}`} viewBox="0 0 60 60" width="60" height="60" aria-hidden="true">
      <g stroke="currentColor" strokeWidth="0.8" fill="none">
        <path d="M 4 30 L 4 4 L 30 4" />
        <path d="M 10 30 L 10 10 L 30 10" opacity="0.5" />
        <circle cx="4" cy="4" r="2" fill="currentColor" />
        <circle cx="18" cy="4" r="0.8" fill="currentColor"/>
        <circle cx="4" cy="18" r="0.8" fill="currentColor"/>
      </g>
    </svg>
  );
}

function CertBadgeIcon({ badge }) {
  // Large, monochrome version of the badge icon for the certificate.
  return (
    <svg width="76" height="76" viewBox="0 0 76 76" className="cert__award-icon">
      <circle cx="38" cy="38" r="34" fill="none" stroke="currentColor" strokeWidth="1.2"/>
      <circle cx="38" cy="38" r="28" fill="none" stroke="currentColor" strokeWidth="0.6" strokeDasharray="1 2"/>
      <g transform="translate(21 21) scale(2)" fill="currentColor" stroke="currentColor">
        {iconFor(badge.id)}
      </g>
    </svg>
  );
}

function iconFor(id) {
  switch (id) {
    case 'first-light': return <g strokeWidth="0.6"><line x1="9" y1="2" x2="9" y2="16"/><line x1="2" y1="9" x2="16" y2="9"/><circle cx="9" cy="9" r="1.4" fill="currentColor"/></g>;
    case 'five-alive':  return <text x="9" y="12" textAnchor="middle" fontSize="11" fontFamily="var(--font-mono)" fontWeight="600">5</text>;
    case 'planet-hop':  return <g fill="none" strokeWidth="0.6"><circle cx="9" cy="9" r="2.4"/><ellipse cx="9" cy="9" rx="7" ry="2"/></g>;
    case 'deep-sky':    return <g fill="none" strokeWidth="0.6"><ellipse cx="9" cy="9" rx="7" ry="2.3" transform="rotate(25 9 9)"/><circle cx="9" cy="9" r="1.2" fill="currentColor"/></g>;
    case 'messier':     return <text x="9" y="12" textAnchor="middle" fontSize="10" fontFamily="var(--font-mono)" fontWeight="600">M</text>;
    case 'all-cats':    return <g><circle cx="4" cy="9" r="1"/><circle cx="9" cy="4" r="1"/><circle cx="14" cy="9" r="1"/><circle cx="9" cy="14" r="1"/><circle cx="9" cy="9" r="1"/></g>;
    case 'cartographer': return <g fill="none" strokeWidth="0.6" strokeLinejoin="round"><path d="M2 4 L9 1.5 L16 4 L16 15 L9 12.5 L2 15 Z"/><line x1="9" y1="1.5" x2="9" y2="12.5"/><circle cx="12" cy="6" r="0.8" fill="currentColor"/></g>;
    default: return null;
  }
}

function prettyDesc(badge) {
  // Longer, certificate-friendly descriptions.
  const map = {
    'first-light': 'for the first object entered in the field log',
    'five-alive':  'for logging five distinct celestial sightings',
    'planet-hop':  'for sighting and recording three planets',
    'deep-sky':    'for observing a galaxy beyond our own Milky Way',
    'messier':     'for identifying three objects from the Messier catalogue',
    'all-cats':    'for observing at least one object from every category in the catalogue',
    'cartographer': 'for charting every object in the catalogue — an entire sky fully mapped',
  };
  return map[badge.id] || badge.desc;
}

function formatDate(d) {
  if (!d) return '';
  try { return new Date(d).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }); } catch { return d; }
}

function hashCode(s) {
  let h = 0;
  for (let i = 0; i < s.length; i++) h = ((h << 5) - h + s.charCodeAt(i)) | 0;
  return Math.abs(h);
}

Object.assign(window, { Certificate });
