// Toolbar — top strip with title, undo/redo, background popover, add-node menu,
// add-note button, save/load, and screenshot.
const { useState: useStateTB, useRef: useRefTB, useEffect: useEffectTB } = React;

function Toolbar({
  title, setTitle, subtitle, setSubtitle,
  defaultCurrency, setDefaultCurrency,
  showTitleOnCanvas, setShowTitleOnCanvas,
  bgPattern, setBgPattern, bgColor, setBgColor,
  showSeq, setShowSeq,
  showNotes, setShowNotes,
  showAnnotations, setShowAnnotations,
  canUndo, canRedo, onUndo, onRedo,
  onAddNode, onAddNote,
  onShotMode, onSaveProject, onLoadProject, onLoadDemo, onClear,
  onShowSchedule, onAutoGroupByDate, onAutoConnectByTime,
}){
  const [bgOpen, setBgOpen] = useStateTB(false);
  const [moreOpen, setMoreOpen] = useStateTB(false);
  const [fileOpen, setFileOpen] = useStateTB(false);
  const [addOpen, setAddOpen] = useStateTB(false);
  const [curOpen, setCurOpen] = useStateTB(false);
  const bgRef = useRefTB(null);
  const moreRef = useRefTB(null);
  const fileRef = useRefTB(null);
  const addRef = useRefTB(null);
  const curRef = 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);
      if (addRef.current && !addRef.current.contains(e.target)) setAddOpen(false);
      if (curRef.current && !curRef.current.contains(e.target)) setCurOpen(false);
    };
    document.addEventListener('mousedown', onDoc);
    return ()=>document.removeEventListener('mousedown', onDoc);
  },[]);

  return (
    <div className="toolbar">
      <div className="brand">
        <div className="logo">
          <window.TourIcon name="route" size={20} stroke="#fff"/>
        </div>
        <input className="title-input" value={title} maxLength={60}
               onChange={e=>setTitle(e.target.value)}
               placeholder="旅程・出張のタイトル（例: 大阪 商談1泊2日）"/>
      </div>

      <div className="tb-group">
        <button className="btn icon sm" disabled={!canUndo} onClick={onUndo} title="元に戻す (Ctrl+Z)">
          <window.TourIcon name="undo-2" size={14}/>
        </button>
        <button className="btn icon sm" disabled={!canRedo} onClick={onRedo} title="やり直し (Ctrl+Y)">
          <window.TourIcon name="redo-2" size={14}/>
        </button>
      </div>

      <div className="tb-popover-wrap" ref={bgRef}>
        <button className="btn sm" onClick={()=>setBgOpen(v=>!v)} title="背景設定">
          <span className={`bg-swatch-mini ${bgPattern}`} style={{backgroundColor:bgColor}}/>
          背景 <window.TourIcon name="chevron-down" size={12}/>
        </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, #10A37F, #3B82F6, #7C3AED, #F59E0B, #EF4444, #10A37F)',
                         position:'relative', cursor:'pointer',
                       }}>
                  <input type="color" value={bgColor || '#FFFFFF'}
                         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={80}
                     placeholder="例: 1泊2日 箱根ルート"
                     onChange={e=>setSubtitle(e.target.value)}
                     style={{border:'1px solid var(--line)', background:'var(--paper)', borderRadius:8, 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>
            <label className="pop-check">
              <input type="checkbox" checked={showSeq !== false}
                     onChange={e=>setShowSeq(e.target.checked)}/>
              矢印に番号 ① ② ③ … を表示
            </label>
            <label className="pop-check">
              <input type="checkbox" checked={showNotes !== false}
                     onChange={e=>setShowNotes(e.target.checked)}/>
              <window.TourIcon name="sticky-note" size={12}/> メモ（付箋）を表示
            </label>
            <label className="pop-check">
              <input type="checkbox" checked={showAnnotations !== false}
                     onChange={e=>setShowAnnotations(e.target.checked)}/>
              <window.TourIcon name="clock" size={12}/> 時刻・運賃ラベルを表示
            </label>
          </div>
        )}
      </div>

      {/* (Sequence-swap toggle removed — numbering is auto-derived from
          each node's arrival/departure times.) */}

      {/* Currency picker — sets the symbol auto-prefixed onto bare numbers
          in the cost field. Existing entries with explicit symbols are
          preserved verbatim and surface as separate per-currency totals
          in the SummaryBar. */}
      <div className="tb-popover-wrap" ref={curRef}>
        <button className="btn sm" onClick={()=>setCurOpen(v=>!v)}
                title="費用入力時に自動付与する通貨記号を選択">
          <window.TourIcon name="coins" size={14}/>
          <span style={{fontWeight:800, marginLeft:2, minWidth:14, textAlign:'center'}}>
            {defaultCurrency || '¥'}
          </span>
          <window.TourIcon name="chevron-down" size={12}/>
        </button>
        {curOpen && (
          <div className="tb-popover">
            <div className="pop-section">
              <div className="pop-label">通貨（自動付与）</div>
              <div style={{fontSize:11, color:'var(--ink-soft)', lineHeight:1.55, marginBottom:6}}>
                数字だけ入力すると、この記号が自動で付きます。<br/>
                既に <code>$</code> や <code>€</code> を含む費用はそのまま保持されます。
              </div>
              <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:4}}>
                {(window.CURRENCIES || []).map(c=>(
                  <button key={c.symbol}
                          className={`btn sm${(defaultCurrency || '¥')===c.symbol?' primary':''}`}
                          onClick={()=>{ setDefaultCurrency(c.symbol); setCurOpen(false); }}
                          style={{padding:'6px 8px', justifyContent:'flex-start'}}
                          title={c.label}>
                    <span style={{fontWeight:800, minWidth:24, textAlign:'center'}}>{c.symbol}</span>
                    <span style={{fontSize:11, color:'var(--ink-soft)', fontWeight:600}}>{c.label}</span>
                  </button>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Schedule (工程表) view */}
      <button className="btn sm" onClick={onShowSchedule}
              title="工程表モード — 旅程を表形式で確認">
        <window.TourIcon name="list" size={14}/> 工程表
      </button>

      <div className="tb-spacer"/>

      {/* Add menu — picks a node type. The "+ ノード" main button defaults to a
          generic pin; the chevron opens the type picker for stations / airports
          / hotels / etc. */}
      <div className="tb-popover-wrap" ref={addRef}>
        <button className="btn primary" onClick={()=>{onAddNode({type:'pin'}); setAddOpen(false);}}
                title="新しい地点を追加">
          <window.TourIcon name="plus" size={14} stroke="#fff"/> ノード
        </button>
        <button className="btn primary sm" onClick={()=>setAddOpen(v=>!v)}
                title="種類を選んで追加" style={{marginLeft:2, padding:'7px 7px'}}>
          <window.TourIcon name="chevron-down" size={12} stroke="#fff"/>
        </button>
        {addOpen && (
          <div className="tb-popover right" style={{minWidth:240}}>
            <div className="pop-section">
              <div className="pop-label">地点タイプ</div>
              <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:4}}>
                {NODE_TYPES.map(t=>(
                  <button key={t.id} className="btn block sm"
                          onClick={()=>{onAddNode({type:t.id}); setAddOpen(false);}}
                          title={`${t.label}を追加`}>
                    <window.TourIcon name={t.icon} size={16}/>
                    {t.label}
                  </button>
                ))}
              </div>
            </div>
            <div className="pop-section" style={{borderTop:'1px solid var(--line)', paddingTop:10}}>
              <button className="btn block sm" onClick={()=>{onAddNote(); setAddOpen(false);}}>
                <window.TourIcon name="sticky-note" size={16}/>
                メモを追加
              </button>
            </div>
          </div>
        )}
      </div>

      <div className="tb-popover-wrap" ref={fileRef}>
        <button className="btn sm" onClick={()=>setFileOpen(v=>!v)} title="作業ファイル">
          <window.TourIcon name="save" size={14}/>
          <window.TourIcon name="chevron-down" size={12}/>
        </button>
        {fileOpen && (
          <div className="tb-popover right">
            <button className="btn block sm" onClick={()=>{onSaveProject(); setFileOpen(false);}}>
              <window.TourIcon name="save" size={14}/> 作業ファイルを保存
            </button>
            <button className="btn block sm" onClick={()=>{onLoadProject(); setFileOpen(false);}}>
              <window.TourIcon name="folder-open" size={14}/> 作業ファイルを開く
            </button>
          </div>
        )}
      </div>

      <div className="tb-popover-wrap" ref={moreRef}>
        <button className="btn sm" onClick={()=>setMoreOpen(v=>!v)} title="その他">
          <window.TourIcon name="more-horizontal" size={14}/>
        </button>
        {moreOpen && (
          <div className="tb-popover right">
            <div className="pop-label">時刻から自動</div>
            <button className="btn block sm" onClick={()=>{onAutoConnectByTime && onAutoConnectByTime(); setMoreOpen(false);}}
                    title="ノードの時刻順に矢印を自動で引き直す（既存の矢印は削除）">
              <window.TourIcon name="zap" size={14}/> 時刻順に自動接続
            </button>
            <button className="btn block sm" onClick={()=>{onAutoGroupByDate && onAutoGroupByDate(); setMoreOpen(false);}}
                    title="各ノードの到着・出発日時から「1日目／2日目…」のグループを自動生成">
              <window.TourIcon name="calendar" size={14}/> 日付でグループ自動生成
            </button>
            <div style={{height:1, background:'var(--line)', margin:'6px 0'}}/>
            <div className="pop-label">サンプルを読み込む</div>
            <button className="btn block sm" onClick={()=>{onLoadDemo('travel'); setMoreOpen(false);}}>
              <window.TourIcon name="sparkles" size={14}/> 旅行（箱根 1泊2日）
            </button>
            <button className="btn block sm" onClick={()=>{onLoadDemo('business'); setMoreOpen(false);}}>
              <window.TourIcon name="briefcase" size={14}/> 出張（大阪 1泊2日）
            </button>
            <div style={{height:1, background:'var(--line)', margin:'6px 0'}}/>
            <button className="btn block sm" onClick={()=>{onClear(); setMoreOpen(false);}}>
              <window.TourIcon name="eraser" size={14}/> すべてクリア
            </button>
          </div>
        )}
      </div>

      <button className="btn primary sm" onClick={onShotMode} title="スクリーンショットモード">
        <window.TourIcon name="camera" size={14} stroke="#fff"/> スクショ
      </button>
    </div>
  );
}

window.Toolbar = Toolbar;
