// カメラモーダル — 撮影して「今日の写真」から問題生成
const { useState: useStateCam, useRef: useRefCam, useEffect: useEffectCam } = React;

function CameraModal({ open, onClose, onCapture }) {
  const videoRef = useRefCam(null);
  const canvasRef = useRefCam(null);
  const fileRef = useRefCam(null);
  const jsonRef = useRefCam(null);
  const [stream, setStream] = useStateCam(null);
  const [err, setErr] = useStateCam(null);
  const [preview, setPreview] = useStateCam(null);
  const [caption, setCaption] = useStateCam('');
  const [mode, setMode] = useStateCam('camera'); // camera | zukan
  const [zukanItems, setZukanItems] = useStateCam([]);

  useEffectCam(() => {
    if (!open) return;
    let active = true;
    (async () => {
      try {
        const s = await navigator.mediaDevices.getUserMedia({
          video: { facingMode: { ideal: 'environment' }, width: { ideal: 1280 } },
          audio: false,
        });
        if (!active) { s.getTracks().forEach(t => t.stop()); return; }
        setStream(s);
        if (videoRef.current) videoRef.current.srcObject = s;
      } catch (e) {
        setErr(e.message || 'カメラが使えません');
      }
    })();
    return () => {
      active = false;
      setStream(prev => { prev?.getTracks().forEach(t => t.stop()); return null; });
      setPreview(null); setCaption(''); setErr(null);
    };
  }, [open]);

  if (!open) return null;

  const snap = () => {
    const v = videoRef.current; const c = canvasRef.current;
    if (!v || !v.videoWidth) return;
    c.width = v.videoWidth; c.height = v.videoHeight;
    c.getContext('2d').drawImage(v, 0, 0);
    setPreview(c.toDataURL('image/jpeg', 0.85));
  };

  const submit = () => {
    onCapture({ image: preview, caption: caption.trim() || '撮った写真' });
    onClose();
  };

  const onFilePick = (e) => {
    const f = e.target.files?.[0];
    if (!f) return;
    const r = new FileReader();
    r.onload = () => setPreview(r.result);
    r.readAsDataURL(f);
  };

  const onZukanImport = (e) => {
    const f = e.target.files?.[0];
    if (!f) return;
    const r = new FileReader();
    r.onload = () => {
      try {
        const data = JSON.parse(r.result);
        const items = Array.isArray(data) ? data : (data.items || []);
        setZukanItems(items.filter(it => it.image));
        setMode('zukan');
      } catch (err) {
        setErr('JSONの読み込みに失敗: ' + err.message);
      }
    };
    r.readAsText(f);
  };

  const pickZukanItem = (item) => {
    setPreview(item.image);
    // 解説テキストの1行目をキャプション候補に
    const firstLine = (item.text || '').split('\n').find(l => l.trim()) || '';
    setCaption(firstLine.replace(/\*\*/g, '').slice(0, 40));
    setMode('camera');
  };

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(20,14,8,0.88)',
      zIndex: 2000, display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <div style={{
        width: 'min(720px, 92vw)', maxHeight: '90vh',
        background: '#fff8ea', borderRadius: 16,
        border: '2px solid #2d2418',
        boxShadow: '6px 8px 0 rgba(0,0,0,0.3)',
        padding: 20,
        display: 'flex', flexDirection: 'column', gap: 12,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <h3 style={{ margin: 0, fontSize: 18, color: '#2d2418' }}>今日の写真から勉強</h3>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', fontSize: 18, cursor: 'pointer', color: '#2d2418' }}>✕</button>
        </div>

        {/* ソース選択 */}
        <div style={{ display: 'flex', gap: 6, background: '#ede7d8', padding: 3, borderRadius: 999 }}>
          {[
            { v: 'camera', l: 'その場で撮影' },
            { v: 'file',   l: '画像アップロード' },
            { v: 'zukan',  l: 'なぜなに図鑑から' },
          ].map(o => (
            <button key={o.v} onClick={() => {
              if (o.v === 'file') { fileRef.current?.click(); return; }
              if (o.v === 'zukan') { jsonRef.current?.click(); return; }
              setMode(o.v);
            }} style={{
              flex: 1, border: 'none',
              background: mode === o.v ? '#fff' : 'transparent',
              color: mode === o.v ? '#c84a3b' : '#666',
              padding: '7px 4px', fontSize: 12, fontWeight: 600,
              borderRadius: 999, cursor: 'pointer',
              fontFamily: 'inherit',
            }}>{o.l}</button>
          ))}
          <input ref={fileRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={onFilePick}/>
          <input ref={jsonRef} type="file" accept="application/json,.json" style={{ display: 'none' }} onChange={onZukanImport}/>
        </div>

        {mode === 'zukan' && zukanItems.length > 0 && !preview ? (
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(90px,1fr))',
            gap: 8, maxHeight: 320, overflowY: 'auto', padding: 4,
          }}>
            {zukanItems.map((it, i) => (
              <div key={i} onClick={() => pickZukanItem(it)} style={{
                aspectRatio: '1', borderRadius: 8, overflow: 'hidden',
                cursor: 'pointer', border: '2px solid transparent',
                boxShadow: '0 2px 6px rgba(0,0,0,0.1)', position: 'relative',
              }}>
                <img src={it.image} style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
              </div>
            ))}
          </div>
        ) : (
          <div style={{
            background: '#000', borderRadius: 10, overflow: 'hidden',
            aspectRatio: '4/3', position: 'relative',
          }}>
            {err ? (
              <div style={{ color: '#fff', padding: 20, textAlign: 'center', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {err}
              </div>
            ) : preview ? (
              <img src={preview} style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
            ) : (
              <video ref={videoRef} autoPlay playsInline muted style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
            )}
          </div>
        )}

        <canvas ref={canvasRef} style={{ display: 'none' }}/>

        {preview && (
          <input
            type="text"
            value={caption}
            onChange={e => setCaption(e.target.value)}
            placeholder="写ってるもの（例: コーヒーカップ、桜の木、東京スカイツリー…）"
            style={{
              padding: '10px 14px', fontSize: 14,
              border: '1.5px solid #8a6237', borderRadius: 8,
              background: '#fff', color: '#2d2418', outline: 'none',
              fontFamily: 'inherit',
            }}
          />
        )}

        <div style={{ display: 'flex', gap: 8, justifyContent: 'center' }}>
          {!preview ? (
            <button onClick={snap} disabled={!!err} style={btnPrimary}>撮影</button>
          ) : (
            <>
              <button onClick={() => setPreview(null)} style={btnSecondary}>撮り直し</button>
              <button onClick={submit} disabled={!caption.trim()} style={{ ...btnPrimary, opacity: !caption.trim() ? 0.5 : 1 }}>
                先生にみせる ▶
              </button>
            </>
          )}
        </div>
        <div style={{ fontSize: 11, color: '#8a6237', textAlign: 'center', lineHeight: 1.5 }}>
          撮った写真や「なぜなに図鑑」の写真から、先生が関連する問題を出してくれます。<br/>
          図鑑連携は JSON エクスポート（<code>localStorage.getItem('zukan_v1')</code>）を読み込みます。
        </div>
      </div>
    </div>
  );
}

const btnPrimary = {
  background: '#c84a3b', color: '#fff8ea',
  border: 'none', padding: '10px 22px',
  fontSize: 14, fontWeight: 600, letterSpacing: '0.1em',
  cursor: 'pointer',
  borderRadius: '12px 18px 12px 18px/18px 12px 18px 12px',
  boxShadow: '2px 3px 0 rgba(45,36,24,0.2)',
  fontFamily: 'inherit',
};
const btnSecondary = {
  background: '#fff8ea', color: '#2d2418',
  border: '1.5px solid #2d2418', padding: '10px 22px',
  fontSize: 14, fontWeight: 600, letterSpacing: '0.1em',
  cursor: 'pointer', borderRadius: 10,
  fontFamily: 'inherit',
};

// 画像から問題を生成（キャプションベース）
async function generateQuestionFromPhoto(caption, subject) {
  const prompt = `あなたは大人向けの家庭教師です。学習者が今日撮った写真を見せてきました。

写真に写っているもの: ${caption}
学習者が興味を持ちそうな科目: ${subject}

この写真の題材から、知的好奇心を刺激する問題を1問作ってください。
「へぇ！」となるような豆知識系や、身近なものから学問に繋げる問題を。

以下のJSONのみで返答:
{
  "question": "問題文（1-2文・日本語）",
  "hint": "ヒント（1文）",
  "answer": "模範解答（短く）",
  "draw": { "title": "黒板見出し（6文字以内）", "lines": ["黒板に書く2-4行（各20文字以内）"] },
  "intro": "先生が『この写真からこんな問題どうかな？』と投げかける話し言葉（1文）"
}`;
  try {
    const resp = await window.claude.complete(prompt);
    const m = resp.match(/\{[\s\S]*\}/);
    if (!m) throw new Error('no json');
    return JSON.parse(m[0]);
  } catch (e) {
    return {
      question: `${caption}にまつわる豆知識クイズを考えてみましょう。`,
      hint: '身近な視点から掘ってみると意外な発見があります。',
      answer: '自由回答',
      draw: { title: '今日の題材', lines: [caption, 'から学びを！'] },
      intro: 'いい写真ですね！これから考えてみましょう。',
    };
  }
}

Object.assign(window, { CameraModal, generateQuestionFromPhoto });
