// 黒板 — 手書き風に文字と図がリアルタイムで描かれる演出
const { useEffect, useRef, useState: useStateBB } = React;

// ラフな手書き風の線を描くためのユーティリティ
function roughPath(x1, y1, x2, y2, amp = 2) {
  const mx = (x1+x2)/2 + (Math.random()-0.5)*amp;
  const my = (y1+y2)/2 + (Math.random()-0.5)*amp;
  return `M ${x1} ${y1} Q ${mx} ${my} ${x2} ${y2}`;
}

// 各文字を「チョーク風に現れる」アニメで表示
function ChalkText({ text, x, y, size = 32, delay = 0, color = '#fff' }) {
  return (
    <text
      x={x} y={y}
      fontFamily="'Yomogi', 'Klee One', 'Zen Kurenaido', cursive"
      fontSize={size}
      fill={color}
      style={{
        opacity: 0,
        animation: `fadeInChalk 0.5s ease-out ${delay}s forwards`,
        letterSpacing: '0.04em',
      }}>
      {text}
    </text>
  );
}

// 手書き風に線を一本、stroke-dashoffset でアニメーション
function ChalkStroke({ d, delay = 0, duration = 0.8, color = '#fff', width = 2.5, opacity = 1 }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const len = el.getTotalLength ? el.getTotalLength() : 300;
    el.style.strokeDasharray = len;
    el.style.strokeDashoffset = len;
    el.getBoundingClientRect();
    el.style.transition = `stroke-dashoffset ${duration}s ease-out ${delay}s, opacity 0.2s linear ${delay}s`;
    el.style.strokeDashoffset = 0;
    el.style.opacity = opacity;
  }, [d, delay, duration, opacity]);
  return <path ref={ref} d={d} stroke={color} strokeWidth={width} fill="none" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: 0 }}/>;
}

function Blackboard({ theme = 'green', content = null, boardKey = 0 }) {
  // theme: green (緑の黒板) / paper (茶紙) / white (白板)
  const palette = {
    green: { bg: '#2b4a34', bg2: '#1f3627', frame: '#8a6237', chalk: '#f6eed8', chalkAccent: '#f2c94c', chalkRed: '#f2a88b' },
    brown: { bg: '#4a3520', bg2: '#372616', frame: '#8a6237', chalk: '#f6eed8', chalkAccent: '#f2c94c', chalkRed: '#f2a88b' },
    white: { bg: '#fbf6e8', bg2: '#f3ecd6', frame: '#8a6237', chalk: '#2d2418', chalkAccent: '#c84a3b', chalkRed: '#6b8e5a' },
  }[theme] || { bg: '#2b4a34', bg2: '#1f3627', frame: '#8a6237', chalk: '#f6eed8', chalkAccent: '#f2c94c', chalkRed: '#f2a88b' };

  return (
    <div style={{
      position: 'relative',
      width: '100%', height: '100%',
      background: palette.frame,
      padding: '18px 22px 26px',
      borderRadius: '14px 20px 14px 20px/20px 14px 20px 14px',
      boxShadow: 'inset 0 0 0 4px rgba(0,0,0,0.08), 4px 6px 0 rgba(45,36,24,0.15)',
    }}>
      {/* 木目テクスチャ */}
      <svg width="0" height="0" style={{ position: 'absolute' }}>
        <defs>
          <pattern id="wood" width="140" height="30" patternUnits="userSpaceOnUse">
            <rect width="140" height="30" fill={palette.frame}/>
            <path d="M 0 10 Q 50 8 100 12 T 140 10" stroke="#6a4620" strokeWidth="0.8" fill="none" opacity="0.4"/>
            <path d="M 0 20 Q 70 22 140 18" stroke="#6a4620" strokeWidth="0.5" fill="none" opacity="0.3"/>
          </pattern>
          <filter id="chalkDust">
            <feTurbulence baseFrequency="0.9" numOctaves="2" result="noise"/>
            <feColorMatrix in="noise" type="matrix" values="0 0 0 0 1  0 0 0 0 1  0 0 0 0 1  0 0 0 0.12 0"/>
            <feComposite in2="SourceGraphic" operator="in"/>
          </filter>
        </defs>
      </svg>

      <div style={{
        position: 'absolute', inset: '14px 18px 22px',
        background: `linear-gradient(135deg, ${palette.bg} 0%, ${palette.bg2} 100%)`,
        borderRadius: '6px',
        boxShadow: 'inset 0 0 40px rgba(0,0,0,0.25), inset 0 0 0 1px rgba(255,255,255,0.03)',
      }}/>

      {/* 黒板面 — SVGで手書き表示 */}
      <div style={{ position: 'relative', height: '100%', padding: '14px 18px' }}>
        <svg key={boardKey} width="100%" height="100%" viewBox="0 0 800 380" preserveAspectRatio="xMidYMid meet" style={{ display: 'block' }}>
          <style>{`
            @keyframes fadeInChalk {
              from { opacity: 0; filter: blur(2px); }
              to { opacity: 0.95; filter: blur(0); }
            }
          `}</style>
          {content && content(palette)}
        </svg>

        {/* チョークトレイ */}
        <div style={{
          position: 'absolute', bottom: -6, left: '12%', right: '12%', height: 8,
          background: palette.frame, borderRadius: 3,
          boxShadow: '0 2px 4px rgba(0,0,0,0.3), inset 0 1px 0 rgba(255,255,255,0.1)'
        }}/>
        <div style={{ position: 'absolute', bottom: -4, left: '20%', width: 28, height: 6, background: palette.chalk, borderRadius: 2, opacity: 0.9 }}/>
        <div style={{ position: 'absolute', bottom: -4, left: '30%', width: 20, height: 6, background: palette.chalkAccent, borderRadius: 2, opacity: 0.9 }}/>
      </div>
    </div>
  );
}

Object.assign(window, { Blackboard, ChalkText, ChalkStroke, roughPath });
