// 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="Itinerary / Business trip title (e.g. : Osaka Meeting1 night2Day)"/>
      </div>

      <div className="tb-group">
        <button className="btn icon sm" disabled={!canUndo} onClick={onUndo} title="Undo (Ctrl+Z)">
          <window.TourIcon name="undo-2" size={14}/>
        </button>
        <button className="btn icon sm" disabled={!canRedo} onClick={onRedo} title="Redo (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="Background settings">
          <span className={`bg-swatch-mini ${bgPattern}`} style={{backgroundColor:bgColor}}/>
          Background <window.TourIcon name="chevron-down" size={12}/>
        </button>
        {bgOpen && (
          <div className="tb-popover">
            <div className="pop-section">
              <div className="pop-label">Pattern</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">Background color</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="CustomColorchoose"
                       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">Subtitle</div>
              <input type="text"
                     value={subtitle || ''}
                     maxLength={80}
                     placeholder="e.g. Hakone 2-day trip / NYC business trip"
                     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)}/>
              Show title / subtitle on canvas
            </label>
            <label className="pop-check">
              <input type="checkbox" checked={showSeq !== false}
                     onChange={e=>setShowSeq(e.target.checked)}/>
              Sequence numbers ① ② ③ on arrows
            </label>
            <label className="pop-check">
              <input type="checkbox" checked={showNotes !== false}
                     onChange={e=>setShowNotes(e.target.checked)}/>
              <window.TourIcon name="sticky-note" size={12}/> Notes (sticky)
            </label>
            <label className="pop-check">
              <input type="checkbox" checked={showAnnotations !== false}
                     onChange={e=>setShowAnnotations(e.target.checked)}/>
              <window.TourIcon name="clock" size={12}/> Time / fare chips
            </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="Currency (auto-prefix on bare numbers)">
          <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">Currency (auto-prefix)</div>
              <div style={{fontSize:11, color:'var(--ink-soft)', lineHeight:1.55, marginBottom:6}}>
                Bare numbers get this symbol auto-attached on blur.<br/>
                Costs you typed with an explicit symbol (e.g. <code>¥</code>, <code>€</code>) are preserved as-is.
              </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="Schedule view — see the itinerary as a timeline or table">
        <window.TourIcon name="list" size={14}/> Schedule
      </button>

      <div className="tb-spacer"/>

      {/* Add menu — picks a node type. The "+ node" 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="Add new place">
          <window.TourIcon name="plus" size={14} stroke="#fff"/> node
        </button>
        <button className="btn primary sm" onClick={()=>setAddOpen(v=>!v)}
                title="Pick type to add" 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">Place type</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={`Add ${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}/>
                NoteAdd
              </button>
            </div>
          </div>
        )}
      </div>

      <div className="tb-popover-wrap" ref={fileRef}>
        <button className="btn sm" onClick={()=>setFileOpen(v=>!v)} title="Project file">
          <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}/> Save project file
            </button>
            <button className="btn block sm" onClick={()=>{onLoadProject(); setFileOpen(false);}}>
              <window.TourIcon name="folder-open" size={14}/> Open project file
            </button>
          </div>
        )}
      </div>

      <div className="tb-popover-wrap" ref={moreRef}>
        <button className="btn sm" onClick={()=>setMoreOpen(v=>!v)} title="Other">
          <window.TourIcon name="more-horizontal" size={14}/>
        </button>
        {moreOpen && (
          <div className="tb-popover right">
            <div className="pop-label">Auto by time</div>
            <button className="btn block sm" onClick={()=>{onAutoConnectByTime && onAutoConnectByTime(); setMoreOpen(false);}}
                    title="Re-route arrows automatically by node times">
              <window.TourIcon name="zap" size={14}/> Auto-connect by time
            </button>
            <button className="btn block sm" onClick={()=>{onAutoGroupByDate && onAutoGroupByDate(); setMoreOpen(false);}}
                    title="Generate Day 1 / Day 2 / … groups from each node's arrival / departure dates">
              <window.TourIcon name="calendar" size={14}/> Auto-group by date
            </button>
            <div style={{height:1, background:'var(--line)', margin:'6px 0'}}/>
            <div className="pop-label">Load sample</div>
            <button className="btn block sm" onClick={()=>{onLoadDemo('travel'); setMoreOpen(false);}}>
              <window.TourIcon name="sparkles" size={14}/> Travel (Hakone, 2 days / 1 night)
            </button>
            <button className="btn block sm" onClick={()=>{onLoadDemo('business'); setMoreOpen(false);}}>
              <window.TourIcon name="briefcase" size={14}/> Business trip (Osaka, 2 days / 1 night)
            </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}/> Clear all
            </button>
          </div>
        )}
      </div>

      <button className="btn primary sm" onClick={onShotMode} title="Screenshot mode">
        <window.TourIcon name="camera" size={14} stroke="#fff"/> Screenshot
      </button>
    </div>
  );
}

window.Toolbar = Toolbar;
