// ノートエリア — 回答入力 + 履歴
const { useState: useStateNB, useRef: useRefNB, useEffect: useEffectNB } = React;

// 連続正解時に出るはなまるSVGスタンプ
function HanamaruStamp({ count }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      background: '#fff2d4', border: '1.5px solid #c84a3b',
      borderRadius: 999, padding: '1px 8px',
      fontSize: 11, color: '#c84a3b', fontWeight: 700,
      transform: 'rotate(-4deg)',
      boxShadow: '1px 2px 0 rgba(45,36,24,0.15)',
    }}>
      <svg width="14" height="14" viewBox="-10 -10 20 20">
        <circle cx="0" cy="0" r="8" fill="none" stroke="#c84a3b" strokeWidth="2"/>
        <path d="M -4 0 L -1 3 L 5 -4" stroke="#c84a3b" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
      {count}れんぞく
    </span>
  );
}

function Notebook({ history, onSubmit, busy, currentQuestion, onExplain, onRetry }) {
  const [value, setValue] = useStateNB('');
  const taRef = useRefNB(null);
  const listRef = useRefNB(null);

  useEffectNB(() => {
    if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight;
  }, [history.length]);

  const submit = () => {
    const v = value.trim();
    if (!v || busy) return;
    onSubmit(v);
    setValue('');
  };

  return (
    <div style={{
      position: 'relative',
      width: '100%', height: '100%',
      background: '#fbf6e8',
      backgroundImage: 'repeating-linear-gradient(transparent 0, transparent 31px, rgba(90,74,51,0.15) 31px, rgba(90,74,51,0.15) 32px)',
      borderRadius: '16px 10px 18px 14px/10px 18px 14px 16px',
      border: '1.5px solid #8a6237',
      boxShadow: '3px 5px 0 rgba(45,36,24,0.12), inset 0 0 0 1px rgba(255,255,255,0.3)',
      padding: '18px 20px',
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
    }}>
      {/* 赤いマージン線 */}
      <div style={{ position: 'absolute', top: 0, bottom: 0, left: 52, width: 1.5, background: '#c84a3b', opacity: 0.45 }}/>

      {/* ラベル（付箋風） */}
      <div style={{
        position: 'absolute', top: -10, right: 24,
        background: '#f2c94c', color: '#2d2418',
        padding: '4px 14px', fontSize: 12, fontWeight: 600,
        transform: 'rotate(2deg)',
        boxShadow: '2px 2px 0 rgba(45,36,24,0.2)',
        letterSpacing: '0.08em',
      }}>MY NOTE</div>

      {/* 履歴リスト */}
      <div ref={listRef} className="scrolly" style={{
        flex: 1, overflowY: 'auto',
        paddingLeft: 40, paddingRight: 6,
        fontFamily: "'Yomogi', 'Klee One', cursive",
        fontSize: 15, lineHeight: '32px',
        color: '#2d2418',
      }}>
        {history.length === 0 && (
          <div style={{ color: '#8a7453', fontStyle: 'italic', paddingTop: 8 }}>
            ここに回答を書いていきましょう
          </div>
        )}
        {history.map((h, i) => (
          <div key={i} style={{ marginBottom: 14 }}>
            <div style={{ fontSize: 11, color: '#8a6237', letterSpacing: '0.1em', lineHeight: '18px', display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
              <span>Q{i+1}. {h.question.length > 40 ? h.question.slice(0,40) + '…' : h.question}</span>
              {h.correct && h.streakAtTime >= 2 && <HanamaruStamp count={h.streakAtTime}/>}
            </div>
            <div style={{ color: '#2d2418' }}>{h.answer}</div>
            {h.feedback && (
              <div style={{
                fontSize: 13,
                color: h.correct ? '#4a6b3a' : '#a94a3b',
                borderLeft: `2px solid ${h.correct ? '#6b8e5a' : '#c84a3b'}`,
                paddingLeft: 8, marginTop: 2, lineHeight: '20px',
              }}>
                {h.correct ? '◎ ' : '△ '}{h.feedback}
                {h.correct === false && h.correctAnswer && (
                  <span style={{ color: '#8a6237', marginLeft: 6, fontSize: 12 }}>（正解: {h.correctAnswer}）</span>
                )}
              </div>
            )}
            {/* アクション行 */}
            {h.correct !== null && (onExplain || onRetry) && (
              <div style={{ display: 'flex', gap: 8, marginTop: 4, paddingLeft: 10 }}>
                {onExplain && !h.explanation && (
                  <button
                    onClick={() => onExplain(i)}
                    disabled={busy || h.explaining}
                    style={actionBtn}
                  >
                    {h.explaining ? '解説中…' : '詳しく'}
                  </button>
                )}
                {onRetry && h.correct === false && (
                  <button onClick={() => onRetry(i)} disabled={busy} style={actionBtn}>↻ もう一度</button>
                )}
              </div>
            )}
            {h.explanation && (
              <div style={{
                marginTop: 6, marginLeft: 10,
                background: '#fff8ea', border: '1px dashed #8a6237',
                borderRadius: 8, padding: '8px 12px',
                fontSize: 13, lineHeight: '20px', color: '#3d2d20',
              }}>
                <div style={{ fontSize: 10, color: '#8a6237', letterSpacing: '0.1em', marginBottom: 4 }}>先生の解説</div>
                {h.explanation}
                {h.tip && (
                  <div style={{ marginTop: 4, fontSize: 12, color: '#6b8e5a' }}>{h.tip}</div>
                )}
              </div>
            )}
          </div>
        ))}
      </div>

      {/* 入力欄 */}
      <div style={{
        marginTop: 12, paddingLeft: 40,
        borderTop: '1px dashed rgba(138,98,55,0.4)', paddingTop: 12,
        display: 'flex', gap: 8, alignItems: 'flex-end',
      }}>
        <textarea
          ref={taRef}
          value={value}
          onChange={e => setValue(e.target.value)}
          onKeyDown={e => {
            if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); submit(); }
          }}
          placeholder={currentQuestion ? 'ここに回答を入力… (Cmd/Ctrl+Enterで送信)' : '「出題する」ボタンを押して始めましょう（自由にメモもOK）'}
          disabled={busy}
          rows={2}
          style={{
            flex: 1,
            background: 'transparent',
            border: 'none',
            outline: 'none',
            resize: 'none',
            fontFamily: "'Yomogi','Klee One',cursive",
            fontSize: 15, lineHeight: '28px',
            color: '#2d2418',
          }}
        />
        <button
          onClick={submit}
          disabled={busy || !value.trim()}
          title={!currentQuestion ? '自由に質問・メモとして送信できます' : ''}
          style={{
            background: busy ? '#d7c9a5' : '#c84a3b',
            color: '#fff8ea',
            border: 'none',
            padding: '10px 18px',
            fontSize: 14, fontWeight: 600,
            letterSpacing: '0.1em',
            cursor: busy ? 'default' : 'pointer',
            borderRadius: '12px 18px 12px 18px/18px 12px 18px 12px',
            boxShadow: '2px 3px 0 rgba(45,36,24,0.2)',
            opacity: !value.trim() || !currentQuestion ? 0.5 : 1,
            transition: 'transform 0.08s',
          }}
          onMouseDown={e => e.currentTarget.style.transform = 'translate(1px,1px)'}
          onMouseUp={e => e.currentTarget.style.transform = 'translate(0,0)'}
          onMouseLeave={e => e.currentTarget.style.transform = 'translate(0,0)'}
        >
          {busy ? '採点中…' : '提出'}
        </button>
      </div>
    </div>
  );
}

const actionBtn = {
  background: '#fff8ea', color: '#2d2418',
  border: '1px solid #8a6237',
  padding: '3px 10px', fontSize: 11,
  letterSpacing: '0.05em',
  cursor: 'pointer',
  borderRadius: 999,
  fontFamily: 'inherit',
};

Object.assign(window, { Notebook });
