/* global React */
const { useState, useEffect, useRef } = React;

// Read the current data-lang attr off <html> and re-render when it changes.
function useLangAttr() {
  const [lang, setLang] = useState(() =>
    (typeof document !== 'undefined' && document.documentElement.getAttribute('data-lang')) || 'ja');
  useEffect(() => {
    if (typeof document === 'undefined') return;
    const obs = new MutationObserver(() => {
      setLang(document.documentElement.getAttribute('data-lang') || 'ja');
    });
    obs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-lang'] });
    return () => obs.disconnect();
  }, []);
  return lang;
}

// ============================================
// Risograph Machine concept diagram
// ============================================
function RisoMachineDiagram() {
  return (
    <svg viewBox="0 0 600 320" style={{width:'100%', maxWidth:520, display:'block', margin:'0 auto'}}>
      {/* Outer machine body */}
      <rect x="40" y="60" width="520" height="200" rx="14" fill="var(--ui-card-2)" stroke="var(--ui-line)" strokeWidth="2"/>
      {/* Top control panel */}
      <rect x="60" y="78" width="160" height="44" rx="6" fill="var(--paper)" stroke="var(--ui-line)" strokeWidth="1.5"/>
      <circle cx="80" cy="100" r="6" fill="var(--ink-pink)"/>
      <circle cx="100" cy="100" r="6" fill="var(--ink-blue)"/>
      <rect x="118" y="92" width="86" height="16" rx="3" fill="var(--ui-card)" stroke="var(--ui-line)"/>

      {/* Drum 1 (left) */}
      <g>
        <circle cx="220" cy="180" r="58" fill="none" stroke="var(--ui-line)" strokeWidth="2" strokeDasharray="3 3"/>
        <circle cx="220" cy="180" r="46" fill="var(--ink-pink)" opacity="0.85"/>
        <circle cx="220" cy="180" r="46" fill="none" stroke="var(--ui-line)" strokeWidth="1.5"/>
        <text x="220" y="186" textAnchor="middle" fontFamily="var(--font-mono)" fontWeight="700" fontSize="14" fill="#fff">DRUM 1</text>
        <text x="220" y="252" textAnchor="middle" fontSize="11" fill="var(--ui-text-dim)" fontWeight="700" letterSpacing="0.1em">PINK</text>
      </g>

      {/* Drum 2 (right) */}
      <g>
        <circle cx="380" cy="180" r="58" fill="none" stroke="var(--ui-line)" strokeWidth="2" strokeDasharray="3 3"/>
        <circle cx="380" cy="180" r="46" fill="var(--ink-blue)" opacity="0.85"/>
        <circle cx="380" cy="180" r="46" fill="none" stroke="var(--ui-line)" strokeWidth="1.5"/>
        <text x="380" y="186" textAnchor="middle" fontFamily="var(--font-mono)" fontWeight="700" fontSize="14" fill="#fff">DRUM 2</text>
        <text x="380" y="252" textAnchor="middle" fontSize="11" fill="var(--ui-text-dim)" fontWeight="700" letterSpacing="0.1em">BLUE</text>
      </g>

      {/* Paper input tray */}
      <path d="M 30 240 L 70 220 L 70 260 L 30 280 Z" fill="var(--paper)" stroke="var(--ui-line)" strokeWidth="1.5"/>
      <text x="20" y="298" fontSize="10" fill="var(--ui-text-mut)" fontWeight="700" letterSpacing="0.1em">FEED</text>

      {/* Paper output tray */}
      <path d="M 530 240 L 570 220 L 570 260 L 530 280 Z" fill="var(--paper)" stroke="var(--ui-line)" strokeWidth="1.5"/>
      <text x="546" y="298" fontSize="10" fill="var(--ui-text-mut)" fontWeight="700" letterSpacing="0.1em">OUT</text>

      {/* Paper path arrow */}
      <path d="M 75 215 Q 150 195 220 195" fill="none" stroke="var(--ink-flo-orange)" strokeWidth="2" strokeDasharray="4 3"/>
      <path d="M 380 195 Q 460 195 525 215" fill="none" stroke="var(--ink-flo-orange)" strokeWidth="2" strokeDasharray="4 3"/>
      <polygon points="525,215 518,212 519,219" fill="var(--ink-flo-orange)"/>

      {/* Side label */}
      <text x="300" y="40" textAnchor="middle" fontSize="11" fill="var(--ui-text-mut)" fontWeight="700" letterSpacing="0.18em">2-DRUM RISOGRAPH (MZ / MD)</text>
    </svg>
  );
}

// ============================================
// Color separation simulator
// ============================================
function SeparationSim() {
  const [layers, setLayers] = useState({ Y: true, P: true, B: true, K: true });
  const [combo, setCombo] = useState('YPBK');

  const palettes = {
    YPBK: { Y:'#ffe600', P:'#ff5294', B:'#2c5fff', K:'#1a1a1a', label:'Y + P + B + K (Standard)' },
    FLOR: { Y:'#fff04a', P:'#ff3982', B:'#1a1a1a', K:'#0aa3a0', label:'Flo Yellow + Flo Pink + K + Teal' },
    DUO:  { Y:'#ff7a32', P:'#ff5294', B:'#2c5fff', K:'#1a1a1a', label:'Flo Orange + Pink + Blue + K' },
  };
  const c = palettes[combo];

  const ToggleBtn = ({k, name, hex}) => (
    <button className={`sim-toggle ${layers[k] ? '' : 'off'}`} onClick={() => setLayers(s => ({...s, [k]: !s[k]}))}>
      <span className="chip" style={{background: hex}}/>
      <span className="name">{name}</span>
      <span className="pct">{layers[k] ? 'ON' : 'OFF'}</span>
      <span className="dot"/>
    </button>
  );

  // Each "layer" is an SVG of a hibiscus-like simple poster shape, in flat color, mix-blend multiply
  return (
    <div>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:10, gap:10, flexWrap:'wrap'}}>
        <div style={{fontSize:11, fontWeight:700, letterSpacing:'0.14em', textTransform:'uppercase', color:'var(--ui-text-dim)'}}>
          <span className="lang-ja">分版シミュレーター</span>
          <span className="lang-en">Color Separation Simulator</span>
        </div>
        <div className="seg" role="tablist">
          {Object.keys(palettes).map(k => (
            <button key={k} className={combo===k?'on':''} onClick={() => setCombo(k)}>{k}</button>
          ))}
        </div>
      </div>

      <div className="sim">
        <div className="sim-canvas">
          {/* Yellow layer — sun shape */}
          <svg className="sim-layer" viewBox="0 0 400 300" style={{opacity: layers.Y ? 1 : 0}}>
            <circle cx="120" cy="100" r="70" fill={c.Y}/>
            <g fill={c.Y}>
              {[0,45,90,135,180,225,270,315].map(deg => (
                <rect key={deg} x="118" y="20" width="4" height="20" transform={`rotate(${deg} 120 100)`}/>
              ))}
            </g>
            <rect x="0" y="240" width="400" height="60" fill={c.Y} opacity="0.6"/>
          </svg>
          {/* Pink layer — flower + RISO */}
          <svg className="sim-layer" viewBox="0 0 400 300" style={{opacity: layers.P ? 1 : 0}}>
            <g fill={c.P}>
              {[0,72,144,216,288].map(deg => (
                <ellipse key={deg} cx="270" cy="160" rx="28" ry="50" transform={`rotate(${deg} 270 200)`}/>
              ))}
              <circle cx="270" cy="200" r="18" fill={c.Y}/>
            </g>
            <text x="20" y="120" fontFamily="serif" fontWeight="900" fontSize="60" fill={c.P}>RISO</text>
          </svg>
          {/* Blue layer — wave + SHOP (offset/indented under RISO) */}
          <svg className="sim-layer" viewBox="0 0 400 300" style={{opacity: layers.B ? 1 : 0}}>
            <path d="M 0 220 Q 100 180 200 220 T 400 220 L 400 300 L 0 300 Z" fill={c.B} opacity="0.85"/>
            <text x="60" y="180" fontFamily="serif" fontWeight="900" fontSize="60" fill={c.B}>SHOP</text>
            <circle cx="60" cy="200" r="6" fill={c.B}/>
            <circle cx="180" cy="80" r="4" fill={c.B}/>
          </svg>
          {/* Black layer — outlines on RISO + caption */}
          <svg className="sim-layer" viewBox="0 0 400 300" style={{opacity: layers.K ? 1 : 0}}>
            <text x="22" y="120" fontFamily="serif" fontWeight="900" fontSize="60" fill="none" stroke={c.K} strokeWidth="1">RISO</text>
            <text x="20" y="240" fontSize="11" fill={c.K} letterSpacing="0.2em">PRESS · WORKSHOP · 2026</text>
            <line x1="20" y1="252" x2="200" y2="252" stroke={c.K} strokeWidth="1"/>
            {/* halftone */}
            {Array.from({length:48}).map((_,i)=>{
              const x = 240 + (i%8)*18;
              const y = 30 + Math.floor(i/8)*12;
              const r = 1 + ((i*7) % 4);
              return <circle key={i} cx={x} cy={y} r={r} fill={c.K}/>;
            })}
          </svg>
        </div>

        <div className="sim-controls">
          <ToggleBtn k="Y" name="Yellow" hex={c.Y}/>
          <ToggleBtn k="P" name="Pink" hex={c.P}/>
          <ToggleBtn k="B" name="Blue" hex={c.B}/>
          <ToggleBtn k="K" name="Black" hex={c.K}/>

          <div style={{fontSize:10, color:'var(--ui-text-mut)', marginTop:6, lineHeight:1.5, letterSpacing:'0.04em'}}>
            <span className="lang-ja">トグルで版を重ねて、データ作成時の色分解を確認できます。</span>
            <span className="lang-en">Toggle layers to see how color separation works.</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================
// 2-pass timeline animation
// ============================================
function PassAnimation() {
  const lang = useLangAttr();
  const isEn = lang === 'en';
  const [stage, setStage] = useState(0); // 0 idle, 1 pass1, 2 dry, 3 pass2, 4 done
  const [playing, setPlaying] = useState(false);
  const [dryHours, setDryHours] = useState(0);
  const tRef = useRef();

  useEffect(() => {
    if (!playing) return;
    if (stage === 0) { setStage(1); return; }
    if (stage === 1) {
      const t = setTimeout(() => setStage(2), 2000);
      return () => clearTimeout(t);
    }
    if (stage === 2) {
      const t = setInterval(() => setDryHours(h => {
        if (h >= 6) { clearInterval(t); setStage(3); return h; }
        return h + 0.5;
      }), 250);
      return () => clearInterval(t);
    }
    if (stage === 3) {
      const t = setTimeout(() => setStage(4), 2000);
      return () => clearTimeout(t);
    }
  }, [stage, playing]);

  function reset() {
    setStage(0); setPlaying(false); setDryHours(0);
  }
  function play() {
    if (stage === 4) reset();
    setPlaying(true);
    if (stage === 0) setStage(1);
  }

  const Pass = ({n, ttl, en, desc, active, drums}) => (
    <div className={`pass-card ${active?'active':''}`}>
      <div className="pass-tag">PASS {n}</div>
      <div className="pass-title">{ttl}</div>
      <div style={{display:'flex', gap:10, margin:'10px 0 8px'}}>
        {drums.map((d,i)=>(
          <div key={i} style={{
            width:38, height:38, borderRadius:'50%',
            background:d, border:'1.5px solid var(--ui-line)',
            display:'flex', alignItems:'center', justifyContent:'center',
            color:'#fff', fontSize:9, fontWeight:700, fontFamily:'var(--font-mono)'
          }}>D{i+1}</div>
        ))}
      </div>
      <div className="pass-desc">{en}</div>
      <div className="pass-desc" style={{marginTop:4}}>{desc}</div>
    </div>
  );

  return (
    <div>
      <div className="pass-timeline">
        <Pass n={1} ttl={isEn ? 'Colors 1 & 2' : '1色目・2色目'}
          en={isEn ? '例：Yellow → Pink' : 'Print first two colors'}
          desc={isEn ? 'Print first two colors' : '例：Yellow → Pink'}
          active={stage===1}
          drums={['#ffe600','#ff5294']}/>
        <div className={`pass-card ${stage===2?'active':''}`}>
          <div className="pass-tag">INTERVAL</div>
          <div className="pass-title">{isEn ? 'Drying' : '乾燥'}</div>
          <div className="dry-strip" style={{height:50, marginTop:10, padding:'0 10px'}}>
            <div className="dry-fill" style={{width: `${(dryHours/6)*100}%`}}/>
            <span className="lbl">DRY</span>
            <span className="v" style={{fontSize:14}}>{dryHours.toFixed(1)}h</span>
          </div>
          <div className="pass-desc" style={{marginTop:8}}>{isEn ? 'Wait several hours' : '数時間〜半日'}</div>
        </div>
        <Pass n={2} ttl={isEn ? 'Colors 3 & 4' : '3色目・4色目'}
          en={isEn ? '例：Blue → Black' : 'Print second pair'}
          desc={isEn ? 'Print second pair' : '例：Blue → Black'}
          active={stage===3}
          drums={['#2c5fff','#1a1a1a']}/>
      </div>

      <div className="pass-controls">
        <button className="pass-btn" onClick={play} disabled={playing && stage !== 4}>
          <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg>
          {stage === 4 ? (isEn ? 'Replay' : 'もう一度') : (playing ? (isEn ? 'Playing…' : '再生中…') : (isEn ? 'Play' : '再生'))}
        </button>
        <button className="pass-btn ghost" onClick={reset}>{isEn ? 'Reset' : 'リセット'}</button>
        <span style={{fontFamily:'var(--font-mono)', fontSize:11, color:'var(--ui-text-mut)', marginLeft:'auto'}}>
          STAGE {stage}/4
        </span>
      </div>

      <PaperFlow stage={stage}/>
    </div>
  );
}

// Paper flow visualization — paper slides through machine
function PaperFlow({stage}) {
  const lang = useLangAttr();
  const isEn = lang === 'en';
  return (
    <div className="diagram diagram-bg" style={{marginTop:10, padding:'24px 20px'}}>
      <svg viewBox="0 0 600 140" style={{width:'100%', display:'block'}}>
        {/* tray in */}
        <rect x="10" y="80" width="60" height="40" rx="4" fill="var(--paper-edge)" stroke="var(--ui-line)" strokeWidth="1.5"/>
        <text x="40" y="138" textAnchor="middle" fontSize="9" fill="var(--ui-text-mut)" fontWeight="700">FEED</text>

        {/* drum 1 */}
        <circle cx="180" cy="70" r="34"
          fill={stage===3 ? '#2c5fff' : '#ff5294'}
          opacity={stage===0?0.3:0.85}
          stroke="var(--ui-line)" strokeWidth="1.5"/>
        <text x="180" y="74" textAnchor="middle" fontSize="10" fontWeight="700" fill="#fff" fontFamily="var(--font-mono)">D1</text>

        {/* drum 2 */}
        <circle cx="320" cy="70" r="34"
          fill={stage===3 ? '#1a1a1a' : '#ffe600'}
          opacity={stage===0?0.3:0.85}
          stroke="var(--ui-line)" strokeWidth="1.5"/>
        <text x="320" y="74" textAnchor="middle" fontSize="10" fontWeight="700" fill={stage===3?'#fff':'#1a1a1a'} fontFamily="var(--font-mono)">D2</text>

        {/* tray out */}
        <rect x="530" y="80" width="60" height="40" rx="4" fill="var(--paper-edge)" stroke="var(--ui-line)" strokeWidth="1.5"/>
        <text x="560" y="138" textAnchor="middle" fontSize="9" fill="var(--ui-text-mut)" fontWeight="700">OUT</text>

        {/* paper */}
        {(stage===1 || stage===3) && (
          <g style={{animation:'paperSlide 1.6s linear infinite'}}>
            <rect x="-50" y="100" width="40" height="22" rx="2"
              fill="var(--paper)" stroke="var(--ui-line)" strokeWidth="1"/>
          </g>
        )}
        {/* path */}
        <path d="M 70 110 Q 250 110 530 110" fill="none" stroke="var(--ink-flo-orange)" strokeWidth="1.5" strokeDasharray="3 3" opacity="0.6"/>

        {/* dry icon */}
        {stage===2 && (
          <g>
            <text x="300" y="30" textAnchor="middle" fontSize="11" fill="var(--ink-flo-orange)" fontWeight="700" letterSpacing="0.14em">{isEn ? 'DRYING' : '乾燥中 / DRYING'}</text>
          </g>
        )}
      </svg>
    </div>
  );
}

// ============================================
// Drum swap diagram
// ============================================
function DrumSwapDiagram() {
  const lang = useLangAttr();
  const isEn = lang === 'en';
  const [step, setStep] = useState(0); // 0 = before, 1 = remove, 2 = insert, 3 = ready
  return (
    <div>
      <div className="drum-diagram">
        <div className="diagram diagram-bg" style={{margin:0}}>
          <svg viewBox="0 0 300 240" style={{width:'100%'}}>
            {/* Machine slot */}
            <rect x="40" y="100" width="220" height="100" rx="8" fill="var(--ui-card-2)" stroke="var(--ui-line)" strokeWidth="1.5"/>
            <rect x="50" y="110" width="200" height="80" rx="4" fill="var(--paper)" stroke="var(--ui-line)" strokeWidth="1" strokeDasharray="3 3"/>
            <text x="150" y="156" textAnchor="middle" fontSize="11" fill="var(--ui-text-mut)" fontWeight="700" letterSpacing="0.1em">DRUM SLOT</text>

            {/* Drum (positioned by step) */}
            {step !== 1 && (
              <g transform={step >= 2 ? 'translate(150 150)' : 'translate(150 150)'}>
                <circle cx="0" cy="0" r="38"
                  fill={step >= 2 ? 'var(--ink-blue)' : 'var(--ink-pink)'}
                  stroke="var(--ui-line)" strokeWidth="1.5"
                  opacity="0.92"/>
                <text x="0" y="4" textAnchor="middle" fontSize="11" fontWeight="800" fill="#fff" fontFamily="var(--font-mono)">
                  {step >= 2 ? 'BLUE' : 'PINK'}
                </text>
                {/* handle */}
                <rect x="-20" y="-58" width="40" height="14" rx="3" fill="var(--ui-card)" stroke="var(--ui-line)" strokeWidth="1.2"/>
              </g>
            )}
            {/* Removed drum (hovering above) */}
            {step === 1 && (
              <g transform="translate(150 60)">
                <circle cx="0" cy="0" r="34" fill="var(--ink-pink)" stroke="var(--ui-line)" strokeWidth="1.5" opacity="0.92"/>
                <text x="0" y="4" textAnchor="middle" fontSize="10" fontWeight="800" fill="#fff" fontFamily="var(--font-mono)">PINK</text>
                <rect x="-20" y="-50" width="40" height="14" rx="3" fill="var(--ui-card)" stroke="var(--ui-line)"/>
                <path d="M 0 18 L 0 80" stroke="var(--ink-flo-orange)" strokeWidth="1.5" strokeDasharray="3 3"/>
                <polygon points="0,80 -4,72 4,72" fill="var(--ink-flo-orange)"/>
              </g>
            )}
            {step === 3 && (
              <g>
                <circle cx="240" cy="40" r="14" fill="var(--ink-blue)" opacity="0.2"/>
                <text x="240" y="44" textAnchor="middle" fontSize="11" fontWeight="800" fill="var(--ink-blue)">✓</text>
              </g>
            )}
          </svg>
        </div>

        <div style={{display:'flex', flexDirection:'column', gap:10}}>
          {[
            ['1', '電源OFF / インクキャップ', 'Power off · Cap ink'],
            ['2', '取手を握って引き抜く', 'Grip handle · Pull out'],
            ['3', '次色ドラムを差し込む', 'Insert next drum'],
            ['4', 'ロック確認 / 電源ON', 'Lock · Power on'],
          ].map(([n, ja, en], i) => (
            <button key={n} className="sim-toggle" style={{borderColor: step===i?'var(--ink-pink)':'var(--ui-line)'}} onClick={()=>setStep(i)}>
              <span style={{
                width:24, height:24, borderRadius:'50%',
                background: step>=i?'var(--ink-pink)':'transparent',
                border: '1.5px solid '+(step>=i?'var(--ink-pink)':'var(--ui-line)'),
                color: step>=i?'#fff':'var(--ui-text)',
                display:'flex', alignItems:'center', justifyContent:'center',
                fontFamily:'var(--font-mono)', fontWeight:700, fontSize:11, flexShrink:0
              }}>{n}</span>
              <div style={{flex:1, minWidth:0}}>
                <div style={{fontWeight:700, fontSize:13}}>{isEn ? en : ja}</div>
                <div style={{fontSize:10, color:'var(--ui-text-mut)', letterSpacing:'0.06em'}}>{isEn ? ja : en}</div>
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ============================================
// Trapping illustration
// ============================================
function TrappingDiagram() {
  const lang = useLangAttr();
  const isEn = lang === 'en';
  return (
    <svg viewBox="0 0 500 180" style={{width:'100%', maxWidth:480, display:'block', margin:'0 auto'}}>
      {/* No trapping */}
      <text x="20" y="22" fontSize="11" fontWeight="700" letterSpacing="0.14em" fill="var(--ui-text-dim)">{isEn ? 'NO TRAP — white gap' : 'NO TRAP — 白抜け'}</text>
      <rect x="20" y="32" width="80" height="60" fill="#ff5294"/>
      <rect x="103" y="32" width="80" height="60" fill="#2c5fff"/>
      {/* gap */}
      <rect x="100" y="32" width="3" height="60" fill="var(--paper)"/>
      <text x="100" y="110" fontSize="10" fill="var(--ink-flo-orange)" fontWeight="700">{isEn ? '↑ misregistration shows paper' : '↑ 版ズレで白い隙間'}</text>

      {/* With trapping */}
      <text x="240" y="22" fontSize="11" fontWeight="700" letterSpacing="0.14em" fill="var(--ui-text-dim)">{isEn ? 'WITH TRAP — overlap' : 'WITH TRAP — 重ね'}</text>
      <rect x="240" y="32" width="82" height="60" fill="#ff5294"/>
      <rect x="320" y="32" width="80" height="60" fill="#2c5fff" style={{mixBlendMode:'multiply'}}/>
      {/* overlap zone visualization */}
      <rect x="320" y="32" width="2" height="60" fill="#7a3aa8" opacity="0.8"/>
      <text x="240" y="110" fontSize="10" fill="var(--ink-blue)" fontWeight="700">{isEn ? '↑ overlap by 0.1–0.5mm' : '↑ 0.1〜0.5mm 重ねる'}</text>

      {/* labels */}
      <text x="20" y="146" fontSize="11" fill="var(--ui-text-dim)">{isEn ? 'Slightly overlap adjacent color plates so misregistration cannot reveal a strip of paper between them.' : '隣接する版データを少しオーバーラップさせ、版ズレによる白抜けを防止する。'}</text>
      <text x="20" y="164" fontSize="10" fill="var(--ui-text-mut)" fontStyle="italic">{isEn ? '隣接する版データを少しオーバーラップさせ、版ズレによる白抜けを防止する。' : 'Slightly overlap adjacent color plates to compensate for misregistration.'}</text>
    </svg>
  );
}

// Expose to window
Object.assign(window, { RisoMachineDiagram, SeparationSim, PassAnimation, DrumSwapDiagram, TrappingDiagram });
