// Top toolbar: compact, with a popover for background settings
const { useState: useStateTB, useRef: useRefTB, useEffect: useEffectTB } = React;

function Toolbar({
  title, setTitle, subtitle, setSubtitle,
  showTitleOnCanvas, setShowTitleOnCanvas,
  bgPattern, setBgPattern, bgColor, setBgColor,
  canUndo, canRedo, onUndo, onRedo,
  onAddNode, onAddWriting, onShotMode, onSaveProject, onLoadProject, onLoadDemo, onClear,
}){
  const [bgOpen, setBgOpen] = useStateTB(false);
  const [moreOpen, setMoreOpen] = useStateTB(false);
  const [fileOpen, setFileOpen] = useStateTB(false);
  const bgRef = useRefTB(null);
  const moreRef = useRefTB(null);
  const fileRef = useRefTB(null);

  useEffectTB(()=>{
    const onDoc = (e)=>{
      if (bgRef.current && !bgRef.current.contains(e.target)) setBgOpen(false);
      if (moreRef.current && !moreRef.current.contains(e.target)) setMoreOpen(false);
      if (fileRef.current && !fileRef.current.contains(e.target)) setFileOpen(false);
    };
    document.addEventListener('mousedown', onDoc);
    return ()=>document.removeEventListener('mousedown', onDoc);
  },[]);

  return (
    <div className="toolbar">
      <div className="brand">
        <div className="logo">♡</div>
        <input className="title-input" value={title} maxLength={60}
               onChange={e=>setTitle(e.target.value)}
               placeholder="相関図のタイトル"/>
      </div>

      <div className="tb-group" style={{background:'var(--bg-lav)'}}>
        <button className="btn sm" disabled={!canUndo} onClick={onUndo} title="元に戻す (Ctrl+Z)">↶</button>
        <button className="btn sm" disabled={!canRedo} onClick={onRedo} title="やり直し (Ctrl+Y)">↷</button>
      </div>

      <div className="tb-popover-wrap" ref={bgRef}>
        <button className="btn" onClick={()=>setBgOpen(v=>!v)} title="背景設定">
          <span className={`bg-swatch-mini ${bgPattern}`} style={{backgroundColor:bgColor}}/>
          背景 ▾
        </button>
        {bgOpen && (
          <div className="tb-popover">
            <div className="pop-section">
              <div className="pop-label">パターン</div>
              <div className="pop-row">
                {BG_PATTERNS.map(p=>(
                  <button key={p.id}
                          className={`bg-swatch ${p.className} ${bgPattern===p.className?'active':''}`}
                          style={{backgroundColor:p.color}}
                          onClick={()=>setBgPattern(p.className)}
                          title={p.label}/>
                ))}
              </div>
            </div>
            <div className="pop-section">
              <div className="pop-label">背景色</div>
              <div className="pop-row">
                {BG_COLORS.map(c=>(
                  <button key={c}
                          className={`bg-swatch ${bgColor===c?'active':''}`}
                          style={{backgroundColor:c}}
                          onClick={()=>setBgColor(c)}/>
                ))}
                <label className={'bg-swatch' + (BG_COLORS.indexOf(bgColor)<0 ? ' active' : '')}
                       title="カスタム色を選ぶ"
                       style={{
                         background:'conic-gradient(from 0deg, #f56a92, #ffd97a, #7dd8b4, #8ccbf0, #b7a0ee, #f56a92)',
                         position:'relative', cursor:'pointer',
                       }}>
                  <input type="color" value={bgColor || '#FFF7EC'}
                         onChange={e=>setBgColor(e.target.value)}
                         style={{position:'absolute', inset:0, width:'100%', height:'100%', opacity:0, cursor:'pointer', border:'none', padding:0}}/>
                </label>
              </div>
            </div>
            <div className="pop-section">
              <div className="pop-label">サブタイトル</div>
              <input type="text"
                     value={subtitle || ''}
                     maxLength={60}
                     placeholder="例: 第1期メインキャスト"
                     onChange={e=>setSubtitle(e.target.value)}
                     style={{border:'2px solid #fff', background:'#fff', borderRadius:10, padding:'6px 10px', fontSize:13, fontFamily:'inherit', outline:'none', color:'inherit'}}/>
            </div>
            <label className="pop-check">
              <input type="checkbox" checked={showTitleOnCanvas}
                     onChange={e=>setShowTitleOnCanvas(e.target.checked)}/>
              タイトル・サブタイトルを画像に入れる
            </label>
          </div>
        )}
      </div>

      <div className="tb-spacer"/>

      <button className="btn primary" onClick={onAddNode}>＋ ノード</button>
      <button className="btn" onClick={onAddWriting}
              style={{background:'var(--lav)', color:'#fff'}}
              title="書き込み（注釈テキスト）を追加">＋ 書き込み</button>

      <div className="tb-popover-wrap" ref={moreRef}>
        <button className="btn" onClick={()=>setMoreOpen(v=>!v)}>…</button>
        {moreOpen && (
          <div className="tb-popover right">
            <button className="btn block" onClick={()=>{onLoadDemo(); setMoreOpen(false);}}>🎀 サンプル読み込み</button>
            <button className="btn block" onClick={()=>{onClear(); setMoreOpen(false);}}>🧹 すべてクリア</button>
          </div>
        )}
      </div>

      <div className="tb-popover-wrap" ref={fileRef}>
        <button className="btn" onClick={()=>setFileOpen(v=>!v)}>💾 ▾</button>
        {fileOpen && (
          <div className="tb-popover right">
            <button className="btn block" onClick={()=>{onSaveProject(); setFileOpen(false);}}>💾 作業ファイルを保存</button>
            <button className="btn block" onClick={()=>{onLoadProject(); setFileOpen(false);}}>📂 作業ファイルを開く</button>
          </div>
        )}
      </div>

      <button className="btn primary" onClick={onShotMode}>📸 スクショ</button>
    </div>
  );
}

window.Toolbar = Toolbar;
