/* GA-Coach · Kompetenz-Check — Ergebnis-Report, E-Mail-Gate & Danke-Seite */

/* ---- Konfetti (kein externes Paket) ---- */
function kcFireConfetti(canvas) {
  if (!canvas) return;
  if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
  const ctx = canvas.getContext('2d');
  const DPR = Math.min(window.devicePixelRatio || 1, 2);
  const W = canvas.width = canvas.clientWidth * DPR;
  const H = canvas.height = canvas.clientHeight * DPR;
  const colors = ['#2F58A4', '#4FC3D9', '#90BAE5', '#F5A524', '#FFD83D', '#244786'];
  const parts = Array.from({ length: 160 }, () => ({
    x: W / 2 + (Math.random() - 0.5) * W * 0.3, y: H * 0.30 + (Math.random() - 0.5) * 40,
    vx: (Math.random() - 0.5) * 16 * DPR, vy: (Math.random() * -16 - 4) * DPR,
    g: (0.35 + Math.random() * 0.25) * DPR, w: (6 + Math.random() * 7) * DPR, h: (8 + Math.random() * 10) * DPR,
    rot: Math.random() * Math.PI, vr: (Math.random() - 0.5) * 0.4, c: colors[(Math.random() * colors.length) | 0]
  }));
  let raf, t = 0;
  function frame() {
    t += 1; ctx.clearRect(0, 0, W, H);
    parts.forEach(p => {
      p.vy += p.g; p.x += p.vx; p.y += p.vy; p.vx *= 0.99; p.rot += p.vr;
      const alpha = t > 90 ? Math.max(0, 1 - (t - 90) / 50) : 1;
      ctx.save(); ctx.globalAlpha = alpha; ctx.translate(p.x, p.y); ctx.rotate(p.rot);
      ctx.fillStyle = p.c; ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h); ctx.restore();
    });
    if (t < 145) raf = requestAnimationFrame(frame); else ctx.clearRect(0, 0, W, H);
  }
  cancelAnimationFrame(raf); frame();
}

const LEVEL_TONE = { stark: { c: 'var(--ga-success)', t: 'Stark' }, solide: { c: 'var(--ga-primary)', t: 'Solide' }, 'ausbaufähig': { c: 'var(--ga-accent-amber)', t: 'Ausbaufähig' } };

function KCProfileBars({ dims }) {
  const [grow, setGrow] = useState(false);
  useEffect(() => { const id = setTimeout(() => setGrow(true), 120); return () => clearTimeout(id); }, []);
  useLucide([]);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {dims.map(d => (
        <div key={d.id}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 7 }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 9, fontSize: 14.5, fontWeight: 700, color: 'var(--ga-text)' }}>
              <span style={{ width: 28, height: 28, borderRadius: 8, background: 'var(--ga-primary-050)', color: 'var(--ga-primary)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={d.icon} size={15} /></span>
              {d.label}
            </span>
            <span style={{ fontSize: 12.5, fontWeight: 800, color: LEVEL_TONE[d.level].c }}>{LEVEL_TONE[d.level].t} · {d.pct}%</span>
          </div>
          <div className="rep-bar-track"><div className={'rep-bar-fill' + (d.level === 'ausbaufähig' ? ' weak' : '')} style={{ width: (grow ? d.pct : 0) + '%' }} /></div>
        </div>
      ))}
    </div>
  );
}

function KCResult({ profile, onContinue }) {
  const confettiRef = useRef(null);
  const fired = useRef(false);
  useLucide([]);
  useEffect(() => {
    if (!fired.current) { fired.current = true; const id = setTimeout(() => kcFireConfetti(confettiRef.current), 200); return () => clearTimeout(id); }
  }, []);

  const RESULTS = window.GA_ASSESSMENT.results;
  const idx = RESULTS.findIndex(r => r.id === profile.result.id);
  const { strengths, gaps, topics, path, result, score, maxScore } = profile;

  return (
    <div className="ob-narrow ob-screen" style={{ maxWidth: 820 }}>
      <canvas ref={confettiRef} className="ob-confetti"></canvas>

      {/* Level */}
      <div className="ob-center">
        <div className="ob-result-badge ob-pop"><Icon name="party-popper" size={44} /></div>
        <div className="ob-eyebrow" style={{ marginTop: 14 }}><Icon name="sparkles" size={13} /> Dein Ergebnis</div>
        <h1 className="ob-title" style={{ margin: '10px 0 4px' }}>Du startest als<br /><span className="accent">{result.name}</span></h1>
        <div className="ob-meter">{RESULTS.map((r, i) => <div key={r.id} className={'seg' + (i <= idx ? ' on' : '')}></div>)}</div>
        <div style={{ fontSize: 12, color: 'var(--ga-muted)', marginTop: 8, fontWeight: 700, letterSpacing: '.04em' }}>{RESULTS.map(r => r.name).join('  ·  ')}</div>
      </div>

      {/* Coach */}
      <div style={{ display: 'flex', gap: 18, alignItems: 'flex-start', marginTop: 28 }}>
        <img src="assets/coach-photo.png" className="ob-coach-avatar" width="64" height="64" alt="Dennis" style={{ flexShrink: 0 }} />
        <div className="ob-bubble">
          <div className="ob-coach-tag"><Icon name="message-circle" size={13} /> Dennis</div>
          {result.summary}
        </div>
      </div>

      {/* Kompetenzprofil */}
      <div className="ob-assess-card ob-rise" style={{ marginTop: 20, animationDelay: '.05s' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18, flexWrap: 'wrap', gap: 8 }}>
          <div className="eyebrow" style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}><Icon name="radar" size={14} /> Dein Kompetenzprofil</div>
          <div style={{ fontSize: 12.5, color: 'var(--ga-muted)', fontWeight: 700 }}>Score {score} / {maxScore} Punkte</div>
        </div>
        <KCProfileBars dims={profile.dims} />
      </div>

      {/* Stärken & Entwicklungspotenziale */}
      <div className="rep-grid" style={{ marginTop: 16 }}>
        <div className="ob-assess-card ob-rise" style={{ animationDelay: '.1s' }}>
          <div className="eyebrow" style={{ display: 'inline-flex', alignItems: 'center', gap: 7, color: 'var(--ga-success)' }}><Icon name="trending-up" size={14} /> Deine Stärken</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 14 }}>
            {strengths.map(d => (
              <div key={d.id} style={{ display: 'flex', gap: 11, alignItems: 'center' }}>
                <span style={{ width: 36, height: 36, borderRadius: 9, background: 'rgba(16,185,129,.12)', color: 'var(--ga-success)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={d.icon} size={18} /></span>
                <div><div style={{ fontSize: 14.5, fontWeight: 700 }}>{d.label}</div><div style={{ fontSize: 12.5, color: 'var(--ga-muted)' }}>{d.pct}% — hier bist du sicher unterwegs</div></div>
              </div>
            ))}
          </div>
        </div>
        <div className="ob-assess-card ob-rise" style={{ animationDelay: '.15s' }}>
          <div className="eyebrow" style={{ display: 'inline-flex', alignItems: 'center', gap: 7, color: 'var(--ga-accent-amber)' }}><Icon name="target" size={14} /> Entwicklungspotenzial</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 14 }}>
            {gaps.map(d => (
              <div key={d.id} style={{ display: 'flex', gap: 11, alignItems: 'center' }}>
                <span style={{ width: 36, height: 36, borderRadius: 9, background: 'rgba(245,165,36,.14)', color: 'var(--ga-accent-amber)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={d.icon} size={18} /></span>
                <div><div style={{ fontSize: 14.5, fontWeight: 700 }}>{d.label}</div><div style={{ fontSize: 12.5, color: 'var(--ga-muted)' }}>{d.pct}% — hier liegt dein größter Hebel</div></div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Empfohlene Themen */}
      <div className="ob-assess-card ob-rise" style={{ marginTop: 16, animationDelay: '.2s' }}>
        <div className="eyebrow" style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}><Icon name="lightbulb" size={14} /> Empfohlene nächste Themen</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, marginTop: 14 }}>
          {topics.map(t => (
            <span key={t.dimId} style={{ display: 'inline-flex', alignItems: 'center', gap: 9, padding: '11px 15px', borderRadius: 12, background: 'var(--ga-section)', border: '1px solid var(--ga-line)', fontSize: 13.5, fontWeight: 700, color: 'var(--ga-text)' }}>
              <Icon name={t.icon} size={16} style={{ color: 'var(--ga-primary)' }} /> {t.title}
            </span>
          ))}
        </div>
      </div>

      {/* Persönlicher Lernpfad */}
      <div style={{ marginTop: 30 }}>
        <div className="ob-center" style={{ marginBottom: 20 }}>
          <div className="ob-eyebrow" style={{ justifyContent: 'center' }}><Icon name="route" size={13} /> Dein persönlicher Lernpfad</div>
          <h2 style={{ fontSize: 'clamp(22px,3.2vw,28px)', fontWeight: 800, letterSpacing: '-.01em', margin: '10px 0 0', lineHeight: 1.2 }}>Starte bei <span style={{ color: 'var(--ga-primary)' }}>{result.start}</span> — Schritt für Schritt</h2>
        </div>
        <div>
          {path.map((m, i) => (
            <div key={m.key} className="path-item">
              <div className="path-rail">
                <div className={'path-node' + (m.focus ? ' focus' : '')}>{m.n}</div>
                {i < path.length - 1 && <div className="path-line"></div>}
              </div>
              <div className={'path-card' + (m.focus ? ' focus' : '')}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
                    <span style={{ width: 38, height: 38, borderRadius: 10, background: 'var(--ga-primary-050)', color: 'var(--ga-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={m.icon} size={19} /></span>
                    <div>
                      <div style={{ fontSize: 15.5, fontWeight: 800, lineHeight: 1.25 }}>{m.title}</div>
                      <div style={{ fontSize: 12.5, color: 'var(--ga-muted)', fontWeight: 600, marginTop: 2, display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name="clock" size={13} /> {m.dur}</div>
                    </div>
                  </div>
                  {m.focus && <span className="chip" style={{ background: 'rgba(245,165,36,.16)', color: '#9a6500' }}><Icon name="target" size={13} /> Fokus für dich</span>}
                </div>
                <div style={{ fontSize: 13, color: 'var(--ga-text-soft)', marginTop: 10, paddingLeft: 49, lineHeight: 1.45 }}>{m.note}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* E-Mail-Gate */}
      <KCEmailGate profile={profile} onContinue={onContinue} />

      <div className="ob-center" style={{ marginTop: 22 }}>
        <button className="ob-back" onClick={() => onContinue.restart()} style={{ margin: '0 auto' }}><Icon name="rotate-ccw" size={16} /> Check neu starten</button>
      </div>
    </div>
  );
}

function KCEmailGate({ profile, onContinue }) {
  const [email, setEmail] = useState('');
  const [err, setErr] = useState(false);
  useLucide([]);
  const bonuses = [
    { i: 'file-text', t: 'Deinen vollständigen Kompetenzbericht' },
    { i: 'route', t: 'Deinen persönlichen Lernpfad' },
    { i: 'file-check-2', t: 'Das VDI 3814 Cheatsheet (PDF)' },
    { i: 'smartphone', t: '7-Tage-Zugang zur GA-Coach App' },
    { i: 'sparkles', t: 'Weitere passende Empfehlungen' },
  ];
  const submit = (e) => {
    e.preventDefault();
    const ok = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
    if (!ok) { setErr(true); return; }
    onContinue.submit(email.trim());
  };
  return (
    <div className="ob-assess-card ob-rise" style={{ marginTop: 30, padding: 0, overflow: 'hidden', border: '1px solid var(--ga-line)' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1.05fr 1fr', gap: 0 }} className="gate-split">
        <div style={{ padding: '30px 30px 30px', background: 'var(--ga-primary-050)' }}>
          <div className="eyebrow" style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}><Icon name="mail-check" size={14} /> Fast geschafft</div>
          <h2 style={{ fontSize: 'clamp(21px,2.6vw,26px)', fontWeight: 800, lineHeight: 1.2, letterSpacing: '-.01em', margin: '12px 0 0', color: 'var(--ga-text)' }}>Dein vollständiger Kompetenzbericht ist fertig.</h2>
          <p style={{ fontSize: 14.5, color: 'var(--ga-text-soft)', lineHeight: 1.55, margin: '12px 0 0' }}>Trag deine E-Mail ein und wir senden dir <b>kostenlos</b>:</p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 16 }}>
            {bonuses.map(b => (
              <div key={b.t} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 14, color: 'var(--ga-text)', fontWeight: 600 }}>
                <span style={{ width: 30, height: 30, borderRadius: 8, background: '#fff', color: 'var(--ga-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, boxShadow: 'var(--ga-shadow-1)' }}><Icon name={b.i} size={16} /></span>
                {b.t}
              </div>
            ))}
          </div>
        </div>
        <div style={{ padding: '30px', display: 'flex', flexDirection: 'column', justifyContent: 'center', background: 'var(--ga-white)' }}>
          <form onSubmit={submit} noValidate>
            <label style={{ fontSize: 13, fontWeight: 700, color: 'var(--ga-text)' }}>Deine E-Mail-Adresse</label>
            <input type="email" value={email} placeholder="deine@email.de" className={'gate-input' + (err ? ' err' : '')} style={{ width: '100%', marginTop: 8 }}
              onChange={e => { setEmail(e.target.value); if (err) setErr(false); }} />
            {err && <div style={{ color: 'var(--ga-danger)', fontSize: 12.5, marginTop: 8, fontWeight: 600 }}>Bitte gib eine gültige E-Mail-Adresse ein.</div>}
            <button type="submit" className="ob-cta" style={{ width: '100%', justifyContent: 'center', marginTop: 14 }}><Icon name="send" size={18} /> Bericht kostenlos zusenden</button>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 14, color: 'var(--ga-muted)', fontSize: 12, flexWrap: 'wrap' }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="shield-check" size={14} /> Kein Spam</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="mouse-pointer-click" size={14} /> Jederzeit abbestellbar</span>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}

function KCSuccess({ profile, email, onRestart }) {
  const confettiRef = useRef(null);
  const fired = useRef(false);
  useLucide([]);
  useEffect(() => {
    if (!fired.current) { fired.current = true; const id = setTimeout(() => kcFireConfetti(confettiRef.current), 200); return () => clearTimeout(id); }
  }, []);
  const bonuses = [
    { i: 'smartphone', t: '7 Tage GA-Coach App', d: 'Voller Zugriff auf Quiz, Lernpfade & XP — gratis.', href: 'https://gacoach.app', ext: true },
    { i: 'file-check-2', t: 'VDI 3814 Cheatsheet', d: 'Die 10 wichtigsten Punkte als PDF.', href: '/wp-content/uploads/2026/05/0_Das-ultimative-10-Punkte-Cheatsheet-VDI-3814.pdf' },
  ];
  return (
    <div className="ob-narrow ob-screen" style={{ maxWidth: 720 }}>
      <canvas ref={confettiRef} className="ob-confetti"></canvas>
      <div className="ob-center">
        <div className="ob-result-badge ob-pop" style={{ background: 'linear-gradient(145deg, var(--ga-success), #0a7d56)' }}><Icon name="check" size={46} /></div>
        <div className="ob-eyebrow" style={{ marginTop: 14, color: 'var(--ga-success)' }}><Icon name="party-popper" size={13} /> Geschafft</div>
        <h1 className="ob-title" style={{ margin: '10px 0 6px' }}>Vielen Dank!<br /><span className="accent">Dein Bericht ist unterwegs.</span></h1>
        <p style={{ fontSize: 16, color: 'var(--ga-muted)', lineHeight: 1.6, maxWidth: 520, margin: '0 auto' }}>
          Wir haben deinen vollständigen Kompetenzbericht und deinen persönlichen Lernpfad an <b style={{ color: 'var(--ga-text)' }}>{email}</b> geschickt. Schau gleich in dein Postfach.
        </p>
      </div>

      <div style={{ marginTop: 28 }}>
        <div className="ob-center" style={{ marginBottom: 14 }}>
          <div className="eyebrow" style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}><Icon name="gift" size={14} /> Dein Dankeschön</div>
        </div>
        <div className="grid-3">
          {bonuses.map(b => {
            const inner = (
              <div className="card" style={{ padding: 22, textAlign: 'center', cursor: b.href ? 'pointer' : 'default', transition: 'box-shadow .2s', textDecoration: 'none', color: 'inherit', display: 'block' }}>
                <div style={{ width: 52, height: 52, borderRadius: 14, background: 'var(--ga-primary-050)', color: 'var(--ga-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto' }}><Icon name={b.i} size={24} /></div>
                <h3 style={{ fontSize: 16, fontWeight: 800, margin: '14px 0 0' }}>{b.t}</h3>
                <p style={{ fontSize: 13, color: 'var(--ga-muted)', lineHeight: 1.5, marginTop: 6 }}>{b.d}</p>
                {b.href && !b.ext && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 10, fontSize: 12.5, fontWeight: 700, color: 'var(--ga-primary)' }}><Icon name="download" size={13} /> PDF herunterladen</span>}
                {b.href && b.ext && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 10, fontSize: 12.5, fontWeight: 700, color: 'var(--ga-primary)' }}><Icon name="external-link" size={13} /> Jetzt öffnen</span>}
              </div>
            );
            return b.href
              ? <a key={b.t} href={b.href} {...(!b.ext ? { download: true } : {})} target="_blank" rel="noopener noreferrer" style={{ textDecoration: 'none', color: 'inherit' }}>{inner}</a>
              : <React.Fragment key={b.t}>{inner}</React.Fragment>;
          })}
        </div>
      </div>

      <div className="ob-assess-card" style={{ marginTop: 24, display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap', justifyContent: 'center', textAlign: 'center', background: 'var(--ga-primary-900)', border: 'none' }}>
        <div style={{ flex: '1 1 260px', textAlign: 'left' }}>
          <div style={{ fontSize: 18, fontWeight: 800, color: '#fff' }}>Leg direkt los — in der GA-Coach App.</div>
          <div style={{ fontSize: 14, color: 'rgba(255,255,255,.78)', marginTop: 4 }}>Dein Lernpfad wartet schon auf dich.</div>
        </div>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <a href="https://gacoach.app" target="_blank" rel="noopener noreferrer" className="btn btn-light"><Icon name="smartphone" size={18} /> GA-Coach App öffnen</a>
          <a href="/#academy" className="btn btn-ghost-dark"><Icon name="graduation-cap" size={18} /> Zur Academy</a>
        </div>
      </div>

      <div className="ob-center" style={{ marginTop: 22 }}>
        <button className="ob-back" onClick={onRestart} style={{ margin: '0 auto' }}><Icon name="rotate-ccw" size={16} /> Check neu starten</button>
      </div>
    </div>
  );
}

Object.assign(window, { KCResult, KCEmailGate, KCSuccess, kcFireConfetti });
