// MODIBU - Modals

const { useState: useStateM, useEffect: useEffectM, useRef: useRefM } = React;

// ============ Quiz Modal (Edukasi / Fakta-Hoax) ============
function QuizModal({ data, onClose, onAnswer }) {
  const [selected, setSelected] = useStateM(null);
  const [locked, setLocked] = useStateM(false);
  const [time, setTime] = useStateM(15);
  const totalRef = useRefM(15);

  useEffectM(() => {
    if (locked) return;
    if (time <= 0) {
      setLocked(true);
      return;
    }
    const t = setTimeout(() => setTime(s => s - 1), 1000);
    return () => clearTimeout(t);
  }, [time, locked]);

  const handleSelect = (key) => {
    if (locked) return;
    setSelected(key);
    setLocked(true);
  };

  const isCorrect = selected === data.correct;
  const timedOut = locked && selected === null;

  const accent = data.type === 'edukasi' ? 'var(--c-edukasi)' : 'var(--c-fakta)';
  const accentDeep = data.type === 'edukasi' ? 'var(--c-edukasi-deep)' : 'var(--c-fakta-deep)';
  const catLabel = data.type === 'edukasi' ? 'EDUKASI' : 'FAKTA / HOAKS';

  const pct = (time / totalRef.current) * 100;
  const danger = time <= 5;

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" style={{
        maxWidth: 720,
        background: 'white',
        borderColor: accent,
        boxShadow: `0 0 0 6px ${accent}, 0 24px 60px rgba(20,50,80,0.30)`,
      }} onClick={e => e.stopPropagation()}>

        {/* Close Button (Top-Right Corner) */}
        <button onClick={onClose} style={{
          position: 'absolute',
          top: -12, right: -12,
          background: '#FFF', 
          border: `3px solid ${accent}`, 
          borderRadius: '50%',
          width: 40, height: 40, cursor: 'pointer',
          boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          zIndex: 10,
          padding: 0
        }}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke={accent} strokeWidth="3" strokeLinecap="round">
            <path d="M18 6L6 18M6 6l12 12" />
          </svg>
        </button>

        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 24 }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 10,
            background: accent, color: 'white',
            padding: '8px 20px', borderRadius: 999,
            fontFamily: 'Fredoka', fontWeight: 700, fontSize: 14, letterSpacing: 0.08,
            textShadow: '0 1px 0 rgba(0,0,0,0.15)',
            boxShadow: `0 4px 0 ${accentDeep}88`
          }}>
            {catLabel}
          </div>
        </div>

        {/* Illustration (Medium Size) */}
        {data.icon && (
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 20 }}>
            <div style={{
              width: 100, height: 100,
              background: `${accent}15`,
              borderRadius: '50%',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              border: `2px dashed ${accent}44`
            }}>
              <img src={data.icon} alt="icon" style={{ width: 70, height: 70, objectFit: 'contain' }} />
            </div>
          </div>
        )}

        {/* Timer */}
        <div style={{ marginBottom: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
            <span style={{ fontFamily: 'Fredoka', fontWeight: 600, fontSize: 13, color: 'var(--ink-soft)' }}>
              ⏱ Waktu menjawab
            </span>
            <span style={{
              fontFamily: 'Fredoka', fontWeight: 700, fontSize: 16,
              color: danger ? '#E03131' : 'var(--ink)',
            }}>
              {time}s
            </span>
          </div>
          <div className={`timer-bar${danger ? ' danger' : ''}`}>
            <div className="fill" style={{ width: `${pct}%` }} />
          </div>
        </div>

        {/* Question */}
        <div className="h-title" style={{
          fontSize: 22, lineHeight: 1.3, marginBottom: 20,
        }}>
          {data.question}
        </div>

        {/* Options */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {data.options.map(opt => {
            let cls = 'option-btn';
            if (locked) {
              if (opt.key === data.correct) cls += ' correct';
              else if (opt.key === selected) cls += ' wrong';
              else cls += ' disabled';
            }
            return (
              <button key={opt.key} className={cls} onClick={() => handleSelect(opt.key)} disabled={locked}>
                <span className="opt-letter">{opt.key}</span>
                <span style={{ flex: 1, textAlign: 'left' }}>{opt.text}</span>
                {locked && opt.key === data.correct && (
                  <svg width="22" height="22" viewBox="0 0 24 24" fill="white">
                    <path d="M20 6L9 17l-5-5" stroke="white" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" fill="none" />
                  </svg>
                )}
                {locked && opt.key === selected && opt.key !== data.correct && (
                  <svg width="22" height="22" viewBox="0 0 24 24" fill="white">
                    <path d="M18 6L6 18M6 6l12 12" stroke="white" strokeWidth="3" strokeLinecap="round" fill="none" />
                  </svg>
                )}
              </button>
            );
          })}
        </div>

        {/* Result */}
        {locked && (
          <div style={{
            marginTop: 22,
            padding: 18,
            borderRadius: 18,
            background: timedOut ? '#FFF4E6' : isCorrect ? '#EBFBEE' : '#FFF5F5',
            border: `2.5px solid ${timedOut ? '#FFA94D' : isCorrect ? '#51CF66' : '#FF6B6B'}`,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
              <span style={{ fontSize: 28 }}>
                {timedOut ? '⏰' : isCorrect ? '🎉' : '💪'}
              </span>
              <div className="font-display-b" style={{ fontSize: 20, color: timedOut ? '#E8590C' : isCorrect ? '#2F9E44' : '#C92A2A' }}>
                {timedOut ? 'Waktu habis!' : isCorrect ? `Tepat sekali! +${data.type === 'edukasi' ? 10 : 10} poin` : 'Belum tepat. 0 poin'}
              </div>
            </div>
            <p style={{ margin: 0, fontSize: 14.5, lineHeight: 1.55, color: 'var(--ink)' }}>
              <strong>Penjelasan:</strong> {data.explanation}
            </p>
            {data.tip && (
              <p style={{ margin: '10px 0 0 0', fontSize: 13.5, lineHeight: 1.55, color: 'var(--ink-soft)', fontStyle: 'italic' }}>
                {data.tip}
              </p>
            )}
            <div style={{ marginTop: 16, display: 'flex', justifyContent: 'flex-end' }}>
              <button className="btn btn-primary btn-sm" onClick={() => onAnswer && onAnswer(isCorrect ? 10 : 0)}>
                Lanjut →
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ============ Challenge Modal (Tantangan / Refleksi) ============
function ChallengeModal({ data, onClose, onSubmit }) {
  const [text, setText] = useStateM('');
  const [sent, setSent] = useStateM(false);
  const isRefleksi = data.type === 'refleksi';
  const accent = isRefleksi ? 'var(--c-refleksi)' : 'var(--c-tantangan)';
  const accentDeep = isRefleksi ? 'var(--c-refleksi-deep)' : 'var(--c-tantangan-deep)';

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" style={{
        maxWidth: 640, background: 'white',
        boxShadow: `0 0 0 6px ${accent}, 0 24px 60px rgba(20,50,80,0.30)`,
      }} onClick={e => e.stopPropagation()}>

        {/* Close Button (Top-Right Corner) */}
        <button onClick={onClose} style={{
          position: 'absolute',
          top: -12, right: -12,
          background: '#FFF', 
          border: `3px solid ${accent}`, 
          borderRadius: '50%',
          width: 40, height: 40, cursor: 'pointer',
          boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          zIndex: 10,
          padding: 0
        }}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke={accent} strokeWidth="3" strokeLinecap="round">
            <path d="M18 6L6 18M6 6l12 12" />
          </svg>
        </button>

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 24 }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 10,
            background: accent, color: 'white',
            padding: '8px 20px', borderRadius: 999,
            fontFamily: 'Fredoka', fontWeight: 700, fontSize: 14, letterSpacing: 0.08,
            textShadow: '0 1px 0 rgba(0,0,0,0.15)',
            boxShadow: `0 4px 0 ${accentDeep}88`
          }}>
            {data.category.toUpperCase()}
          </div>
        </div>

        {/* Illustration (Medium Size) */}
        {data.icon && (
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 20 }}>
            <div style={{
              width: 100, height: 100,
              background: `${accent}15`,
              borderRadius: '50%',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              border: `2px dashed ${accent}44`
            }}>
              <img src={data.icon} alt="icon" style={{ width: 70, height: 70, objectFit: 'contain' }} />
            </div>
          </div>
        )}

        {!sent ? (
          <>
            <div className="h-title" style={{ fontSize: 20, lineHeight: 1.35, marginBottom: 14 }}>
              {data.question}
            </div>
            {data.example && (
              <div style={{
                padding: 12, borderRadius: 12, background: '#F8F9FA',
                fontSize: 13, color: 'var(--ink-soft)', marginBottom: 14, lineHeight: 1.5,
              }}>
                {data.example}
              </div>
            )}
            <textarea
              value={text}
              onChange={e => setText(e.target.value)}
              placeholder={isRefleksi ? 'Tulis refleksimu di sini…' : 'Tulis jawabanmu di sini…'}
              rows={5}
              style={{
                width: '100%', padding: 14, fontSize: 15, lineHeight: 1.55,
                fontFamily: 'inherit', color: 'var(--ink)',
                border: '2.5px solid #E5EEF4', borderRadius: 16,
                resize: 'vertical', outline: 'none',
              }}
              onFocus={e => e.target.style.borderColor = accent}
              onBlur={e => e.target.style.borderColor = '#E5EEF4'}
            />
            <div style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              marginTop: 14,
            }}>
              <div style={{ fontSize: 12, color: 'var(--ink-soft)', fontFamily: 'Fredoka', fontWeight: 600 }}>
                {data.scoring}
              </div>
              <button
                className={isRefleksi ? 'btn btn-blue' : 'btn btn-pink'}
                onClick={() => { setSent(true); }}
                disabled={text.length < 5}
                style={{ opacity: text.length < 5 ? 0.5 : 1 }}
              >
                Kirim ke Guru BK
              </button>
            </div>
          </>
        ) : (
          <div style={{ textAlign: 'center', padding: '20px 0' }}>
            <div style={{ fontSize: 56, marginBottom: 6 }}>📨</div>
            <div className="font-display-b" style={{ fontSize: 24, marginBottom: 8 }}>
              Jawaban terkirim!
            </div>
            <p style={{ color: 'var(--ink-soft)', fontSize: 14, maxWidth: 380, margin: '0 auto 18px', lineHeight: 1.55 }}>
              Guru BK akan menilai jawabanmu. Poin (0–20) akan ditampilkan sesaat lagi pada skor real-time.
            </p>
            <div style={{
              background: '#F8F9FA', borderRadius: 14, padding: 14,
              maxWidth: 460, margin: '0 auto 20px', textAlign: 'left',
              border: '2px dashed #DEE2E6',
            }}>
              <div style={{ fontSize: 11, fontFamily: 'Fredoka', fontWeight: 700, color: 'var(--ink-soft)', marginBottom: 6, letterSpacing: 0.06 }}>JAWABANMU</div>
              <div style={{ fontSize: 14, color: 'var(--ink)', lineHeight: 1.5 }}>"{text}"</div>
            </div>
            <button className="btn btn-primary" onClick={() => onSubmit && onSubmit(text)}>
              Tutup
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

// ============ Card Modal (Kesempatan / Hukuman) ============
function CardModal({ data, onClose }) {
  const isHukuman = data.type === 'hukuman';
  const accent = isHukuman ? 'var(--c-hukuman)' : 'var(--c-kesempatan)';
  const accentDeep = isHukuman ? 'var(--c-hukuman-deep)' : 'var(--c-kesempatan-deep)';
  const icon = isHukuman ? '🚨' : '⭐';

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        position: 'relative',
        animation: 'popIn 0.3s ease-out',
      }}>
        {/* Close Button (Top-Right) */}
        <button onClick={onClose} style={{
          position: 'absolute',
          top: -12, right: -12,
          background: '#FFF',
          border: `3px solid ${accent}`,
          borderRadius: '50%',
          width: 38, height: 38, cursor: 'pointer',
          boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          zIndex: 10,
          padding: 0
        }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={accent} strokeWidth="3.5" strokeLinecap="round">
            <path d="M18 6L6 18M6 6l12 12" />
          </svg>
        </button>

        <div style={{
          background: 'white',
          borderRadius: 24,
          padding: 0,
          width: 360,
          overflow: 'hidden',
          boxShadow: '0 24px 60px rgba(20,50,80,0.40)',
          border: '4px solid white',
        }}>
          {/* Top stripe */}
          <div style={{
            background: accent,
            padding: '14px 20px',
            color: 'white',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}>
            <div style={{
              fontFamily: 'Fredoka', fontWeight: 700, fontSize: 13,
              letterSpacing: 0.1, textShadow: '0 1px 0 rgba(0,0,0,0.18)',
            }}>
              KARTU {isHukuman ? 'HUKUMAN' : 'KESEMPATAN'}
            </div>
            <TileIcon type={isHukuman ? 'hukuman' : 'kesempatan'} size={20} />
          </div>
          {/* Center icon */}
          <div style={{
            background: `linear-gradient(180deg, white 0%, ${isHukuman ? '#FFF5F5' : '#E7F5FF'} 100%)`,
            padding: '28px 20px 24px',
            textAlign: 'center',
          }}>
            <div style={{
              width: 88, height: 88, borderRadius: '50%',
              background: accent,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 44,
              border: '4px solid white',
              boxShadow: `0 6px 0 ${accentDeep}`,
              marginBottom: 12,
            }}>
              {icon}
            </div>
            <div className="font-display-b" style={{ fontSize: 24, marginBottom: 8, color: accentDeep }}>
              {data.title}
            </div>
            <p style={{ margin: 0, fontSize: 14.5, lineHeight: 1.55, color: 'var(--ink)', padding: '0 8px' }}>
              {data.desc}
            </p>
          </div>
          {/* Effect */}
          <div style={{
            padding: '16px 20px 22px',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            gap: 12,
          }}>
            <div style={{
              padding: '12px 22px',
              background: isHukuman ? '#FFF5F5' : '#EBFBEE',
              borderRadius: 999,
              border: `2.5px dashed ${accent}`,
              fontFamily: 'Fredoka', fontWeight: 700, fontSize: 17,
              color: accentDeep,
            }}>
              {data.effect}
            </div>
            <button className={isHukuman ? 'btn btn-red' : 'btn btn-blue'} onClick={onClose}>
              {isHukuman ? 'Terima konsekuensi' : 'Klaim hadiah'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============ Material Popup (Tahukah kamu?) ============
function MaterialModal({ data, onClose }) {
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" style={{
        maxWidth: 560,
        boxShadow: '0 0 0 6px var(--c-finish), 0 24px 60px rgba(20,50,80,0.30)',
        position: 'relative'
      }} onClick={e => e.stopPropagation()}>
        {/* Close Button (Top-Right) */}
        <button onClick={onClose} style={{
          position: 'absolute',
          top: -12, right: -12,
          background: '#FFF',
          border: '3px solid var(--c-finish)',
          borderRadius: '50%',
          width: 38, height: 38, cursor: 'pointer',
          boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          zIndex: 10,
          padding: 0
        }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--c-finish)" strokeWidth="3.5" strokeLinecap="round">
            <path d="M18 6L6 18M6 6l12 12" />
          </svg>
        </button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
          <div style={{
            width: 56, height: 56, borderRadius: '50%',
            background: 'linear-gradient(180deg, #B197FC, #9775FA)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 28,
            boxShadow: '0 4px 0 var(--c-finish-deep)',
            border: '3px solid white',
          }}>
            💡
          </div>
          <div>
            <div style={{ fontFamily: 'Fredoka', fontWeight: 700, fontSize: 11, color: 'var(--c-finish-deep)', letterSpacing: 0.08 }}>
              {data.title.toUpperCase()}
            </div>
            <div className="h-title" style={{ fontSize: 22 }}>{data.subtitle}</div>
          </div>
        </div>
        <p style={{ fontSize: 15, lineHeight: 1.65, color: 'var(--ink)' }}>
          {data.body}
        </p>
        <div style={{
          background: '#F8F9FA',
          borderRadius: 16,
          padding: 16,
          marginTop: 12,
        }}>
          {data.points.map((p, i) => (
            <div key={i} style={{
              display: 'flex',
              alignItems: 'flex-start',
              gap: 10,
              padding: '8px 0',
              borderBottom: i < data.points.length - 1 ? '1px solid #E9ECEF' : 'none',
            }}>
              <div style={{
                width: 24, height: 24, borderRadius: '50%',
                background: 'var(--c-edukasi)', color: 'white',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 14, fontWeight: 700, flexShrink: 0,
              }}>{p.icon}</div>
              <div style={{ fontSize: 14.5, lineHeight: 1.5 }}>{p.label}</div>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 20 }}>
          <button className="btn btn-primary" onClick={onClose}>Mengerti, lanjutkan!</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { QuizModal, ChallengeModal, CardModal, MaterialModal });
