// Camera / capture screen — shared across all three variants.
// Only the result-sheet styling changes between variants.

function CameraView({ onCapture, variant, onOpenBook, onOpenSettings }) {
  const [focusPos, setFocusPos] = React.useState(null);
  const [flashing, setFlashing] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const videoRef = React.useRef(null);
  const canvasRef = React.useRef(null);
  const fileRef = React.useRef(null);

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

  const handleTap = (e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    const x = ((e.clientX - rect.left) / rect.width) * 100;
    const y = ((e.clientY - rect.top) / rect.height) * 100;
    setFocusPos({ x, y });
    setTimeout(() => setFocusPos(null), 900);
  };

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

  const handleShutter = () => {
    if (err) { fileRef.current?.click(); return; }
    const dataUrl = capturePhoto();
    if (!dataUrl) return;
    setFlashing(true);
    setTimeout(() => setFlashing(false), 160);
    setTimeout(() => onCapture(dataUrl), 240);
  };

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

  // Variant-specific camera chrome
  const chromeColor = variant === 'notebook' ? '#f4ecdc' : '#f4ecdc';
  const accentInk = variant === 'museum' ? '#8b2920' : (variant === 'encyclopedia' ? '#1e3a5f' : '#5a6b4a');

  return (
    <div style={{
      position: 'absolute', inset: 0, background: '#0a0906',
      overflow: 'hidden', userSelect: 'none',
    }}>
      {/* Real camera feed */}
      <div onClick={handleTap} style={{
        position: 'absolute', inset: 0, cursor: 'crosshair',
        background: '#0a0906',
      }}>
        {err ? (
          <div style={{
            position: 'absolute', inset: 0,
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
            color: '#f4ecdc', padding: 30, textAlign: 'center', gap: 12,
          }}>
            <div style={{ fontSize: 13, letterSpacing: 2, opacity: 0.7 }}>CAMERA UNAVAILABLE</div>
            <div style={{ fontSize: 13, opacity: 0.85 }}>{err}</div>
            <button onClick={() => fileRef.current?.click()} style={{
              marginTop: 10, background: '#f4ecdc', color: '#1a1612', border: 'none',
              padding: '10px 20px', fontSize: 12, letterSpacing: 2, cursor: 'pointer',
              fontFamily: 'ui-monospace, monospace',
            }}>画像ファイルを選ぶ</button>
          </div>
        ) : (
          <video
            ref={videoRef} autoPlay playsInline muted
            style={{
              position: 'absolute', inset: 0, width: '100%', height: '100%',
              objectFit: 'cover',
            }}
          />
        )}
        <input
          ref={fileRef} type="file" accept="image/*" capture="environment"
          style={{ display: 'none' }} onChange={onFilePick}
        />

        {/* grid */}
        <svg style={{ position: 'absolute', inset: 0, opacity: 0.12 }} width="100%" height="100%">
          <line x1="33.3%" y1="0" x2="33.3%" y2="100%" stroke="white" strokeWidth="0.5"/>
          <line x1="66.6%" y1="0" x2="66.6%" y2="100%" stroke="white" strokeWidth="0.5"/>
          <line x1="0" y1="33.3%" x2="100%" y2="33.3%" stroke="white" strokeWidth="0.5"/>
          <line x1="0" y1="66.6%" x2="100%" y2="66.6%" stroke="white" strokeWidth="0.5"/>
        </svg>

        {/* focus reticle */}
        {focusPos && (
          <div style={{
            position: 'absolute', left: `${focusPos.x}%`, top: `${focusPos.y}%`,
            width: 74, height: 74, marginLeft: -37, marginTop: -37,
            border: `1.5px solid ${accentInk}`,
            animation: 'focusPulse 0.7s ease-out forwards',
            pointerEvents: 'none',
          }}>
            {/* corner ticks */}
            {[[0,0],[1,0],[0,1],[1,1]].map(([x,y],i) => (
              <div key={i} style={{
                position: 'absolute', width: 8, height: 8,
                borderTop: y === 0 ? `1.5px solid ${accentInk}` : 'none',
                borderBottom: y === 1 ? `1.5px solid ${accentInk}` : 'none',
                borderLeft: x === 0 ? `1.5px solid ${accentInk}` : 'none',
                borderRight: x === 1 ? `1.5px solid ${accentInk}` : 'none',
                left: x === 0 ? -2 : 'auto', right: x === 1 ? -2 : 'auto',
                top: y === 0 ? -2 : 'auto', bottom: y === 1 ? -2 : 'auto',
                background: accentInk,
              }}/>
            ))}
          </div>
        )}
      </div>

      {/* Top bar — variant-specific masthead */}
      <CameraTopBar variant={variant} onOpenBook={onOpenBook} onOpenSettings={onOpenSettings}/>

      {/* Bottom capture bar */}
      <CameraBottomBar variant={variant} onShutter={handleShutter}/>

      {/* Flash */}
      {flashing && (
        <div style={{
          position: 'absolute', inset: 0, background: '#fff',
          animation: 'flash 0.16s ease-out forwards', zIndex: 40,
        }}/>
      )}

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

function CameraTopBar({ variant, onOpenBook, onOpenSettings }) {
  if (variant === 'museum') {
    return (
      <div style={{
        position: 'absolute', top: 54, left: 0, right: 0, padding: '14px 20px',
        display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between',
        color: '#f4ecdc', zIndex: 20,
      }}>
        <div>
          <div style={{
            fontFamily: '"Noto Serif JP", serif', fontSize: 11, letterSpacing: 4,
            textTransform: 'uppercase', opacity: 0.7, marginBottom: 2,
          }}>Collection No.</div>
          <div style={{
            fontFamily: '"Noto Serif JP", serif', fontSize: 22, fontWeight: 500,
            letterSpacing: 1,
          }}>なぜなに 博物誌</div>
          <div style={{
            width: 34, height: 1, background: '#f4ecdc', opacity: 0.5, marginTop: 6,
          }}/>
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <IconPill onClick={onOpenBook} label="図鑑" glyph="book"/>
          <IconPill onClick={onOpenSettings} glyph="dots"/>
        </div>
      </div>
    );
  }
  if (variant === 'notebook') {
    return (
      <div style={{
        position: 'absolute', top: 54, left: 0, right: 0, padding: '14px 18px',
        display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between',
        color: '#f4ecdc', zIndex: 20,
      }}>
        <div style={{
          background: '#f4ecdc', color: '#1a1612', padding: '6px 12px',
          transform: 'rotate(-1.5deg)',
          fontFamily: '"Kosugi Maru", "Noto Sans JP", sans-serif', fontSize: 15,
          boxShadow: '2px 3px 0 rgba(0,0,0,0.25)',
        }}>
          <div style={{ fontSize: 9, letterSpacing: 2, opacity: 0.6 }}>FIELD NOTES</div>
          <div style={{ fontWeight: 700, marginTop: -1 }}>なぜなに帳</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <IconPill onClick={onOpenBook} label="帳面" glyph="book"/>
          <IconPill onClick={onOpenSettings} glyph="dots"/>
        </div>
      </div>
    );
  }
  // encyclopedia
  return (
    <div style={{
      position: 'absolute', top: 54, left: 0, right: 0, padding: '14px 20px',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      color: '#f4ecdc', zIndex: 20,
    }}>
      <div>
        <div style={{
          fontFamily: 'ui-monospace, "SF Mono", monospace', fontSize: 10,
          letterSpacing: 3, opacity: 0.65,
        }}>VOL. Ⅰ · ENTRY</div>
        <div style={{
          fontFamily: '"Noto Serif JP", serif', fontSize: 20, fontWeight: 600,
          letterSpacing: 2, marginTop: 1,
        }}>百科カメラ</div>
      </div>
      <div style={{ display: 'flex', gap: 8 }}>
        <IconPill onClick={onOpenBook} label="索引" glyph="book"/>
        <IconPill onClick={onOpenSettings} glyph="dots"/>
      </div>
    </div>
  );
}

function IconPill({ onClick, label, glyph }) {
  const glyphs = {
    book: (
      <svg width="15" height="15" viewBox="0 0 15 15" fill="none">
        <path d="M2 2h5.5a2 2 0 012 2v9H4a2 2 0 01-2-2V2z" stroke="currentColor" strokeWidth="1.1"/>
        <path d="M13 2H7.5a2 2 0 00-2 2v9H11a2 2 0 002-2V2z" stroke="currentColor" strokeWidth="1.1"/>
      </svg>
    ),
    dots: (
      <svg width="15" height="4" viewBox="0 0 15 4" fill="currentColor">
        <circle cx="2" cy="2" r="1.5"/><circle cx="7.5" cy="2" r="1.5"/><circle cx="13" cy="2" r="1.5"/>
      </svg>
    ),
  };
  return (
    <button onClick={onClick} style={{
      background: 'rgba(255,255,255,0.12)', color: '#f4ecdc',
      border: '0.5px solid rgba(255,255,255,0.25)', borderRadius: 999,
      padding: label ? '7px 12px' : '7px 10px',
      display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer',
      backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)',
      fontFamily: '"Noto Serif JP", serif', fontSize: 12, letterSpacing: 2,
    }}>
      {glyphs[glyph]}
      {label && <span>{label}</span>}
    </button>
  );
}

function CameraBottomBar({ variant, onShutter }) {
  const accentMap = { museum: '#8b2920', notebook: '#5a6b4a', encyclopedia: '#1e3a5f' };
  const accent = accentMap[variant];

  const hintMap = {
    museum: '気になる資料にかざしてシャッターを',
    notebook: 'なんだろう？と思ったら撮ってメモ',
    encyclopedia: '被写体を捉えて項目を引く',
  };

  return (
    <div style={{
      position: 'absolute', bottom: 0, left: 0, right: 0,
      padding: '24px 20px 44px',
      background: 'linear-gradient(to top, rgba(0,0,0,0.7), transparent)',
      color: '#f4ecdc', zIndex: 20,
    }}>
      {/* Hint text */}
      <div style={{
        textAlign: 'center', marginBottom: 18,
        fontFamily: '"Noto Serif JP", serif', fontSize: 12, letterSpacing: 2,
        opacity: 0.85,
      }}>{hintMap[variant]}</div>

      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '0 20px',
      }}>
        {/* mode indicator */}
        <div style={{
          fontFamily: 'ui-monospace, "SF Mono", monospace',
          fontSize: 10, letterSpacing: 2, opacity: 0.7, width: 60,
        }}>
          {variant === 'museum' ? 'REC · 記録' : variant === 'notebook' ? 'SCOUT' : 'LOOKUP'}
        </div>

        {/* shutter */}
        <button onClick={onShutter} style={{
          width: 74, height: 74, borderRadius: '50%',
          border: `2px solid #f4ecdc`, padding: 4, background: 'transparent',
          cursor: 'pointer',
        }}>
          <div style={{
            width: '100%', height: '100%', borderRadius: '50%',
            background: '#f4ecdc',
            boxShadow: `inset 0 0 0 3px ${accent}33`,
          }}/>
        </button>

        {/* level indicator */}
        <div style={{
          fontFamily: 'ui-monospace, "SF Mono", monospace',
          fontSize: 10, letterSpacing: 2, opacity: 0.7, width: 60,
          textAlign: 'right',
        }}>LV · 高校</div>
      </div>
    </div>
  );
}

window.CameraView = CameraView;
