// 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,
  showNotes, setShowNotes,
  showFlow, setShowFlow,
  bgPattern, setBgPattern, bgColor, setBgColor,
  canUndo, canRedo, onUndo, onRedo,
  onAddNode, onShotMode, onSaveProject, onLoadProject, onLoadDemo, onClear,
  branchNodeMode, onToggleBranchMode, branchModeAvailable,
}){
  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="Combo title"/>
      </div>

      <div className="tb-group" style={{background:'var(--bg-lav)'}}>
        <button className="btn sm" disabled={!canUndo} onClick={onUndo} title="Undo (Ctrl+Z)">↶</button>
        <button className="btn sm" disabled={!canRedo} onClick={onRedo} title="Redo (Ctrl+Y)">↷</button>
      </div>

      <div className="tb-popover-wrap" ref={bgRef}>
        <button className="btn" onClick={()=>setBgOpen(v=>!v)} title="Background & display settings">
          <span className={`bg-swatch-mini ${bgPattern}`} style={{backgroundColor:bgColor}}/>
          Background ▾
        </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="Pick a custom color"
                       style={{
                         background:'conic-gradient(from 0deg, #f56a92, #ffd97a, #7dd8b4, #8ccbf0, #b7a0ee, #f56a92)',
                         position:'relative', cursor:'pointer',
                       }}>
                  <input type="color" value={bgColor || '#161922'}
                         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={60}
                     placeholder="e.g. From a single starter to the final board"
                     onChange={e=>setSubtitle(e.target.value)}
                     style={{border:'1px solid var(--line)', background:'var(--bg)', borderRadius:10, padding:'6px 10px', fontSize:13, fontFamily:'inherit', outline:'none', color:'var(--ink)'}}/>
            </div>
            <label className="pop-check">
              <input type="checkbox" checked={showTitleOnCanvas}
                     onChange={e=>setShowTitleOnCanvas(e.target.checked)}/>
              Include title & subtitle on export
            </label>
            <label className="pop-check" title="Applies to both the canvas and screenshots">
              <input type="checkbox" checked={showNotes !== false}
                     onChange={e=>setShowNotes && setShowNotes(e.target.checked)}/>
              💬 Show note boxes
            </label>
            <label className="pop-check" title="Can slow down with many arrows — turn on only when needed">
              <input type="checkbox" checked={showFlow === true}
                     onChange={e=>setShowFlow && setShowFlow(e.target.checked)}/>
              Animate arrow flow
            </label>
          </div>
        )}
      </div>

      <div className="tb-spacer"/>

      <button className="btn primary" onClick={onAddNode}>＋ Card</button>
      <button className={`btn${branchNodeMode?' primary branch-active':''}`}
              onClick={onToggleBranchMode}
              disabled={!branchNodeMode && branchModeAvailable === false}
              title={
                branchNodeMode
                  ? 'Branch-node placement mode — click again or press Esc to exit'
                  : (branchModeAvailable === false
                      ? 'Add an arrow or a zone first to place a branch node'
                      : 'Place a small branch node on an arrow or inside a zone')
              }>
        {branchNodeMode ? '✓ Placing branch' : '● Branch node'}
      </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);}}>💎 Load sample combo</button>
            <button className="btn block" onClick={()=>{onClear(); setMoreOpen(false);}}>🧹 Clear all</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);}}>💾 Save project file</button>
            <button className="btn block" onClick={()=>{onLoadProject(); setFileOpen(false);}}>📂 Open project file</button>
          </div>
        )}
      </div>

      <button className="btn primary" onClick={onShotMode}>📸 Screenshot</button>
    </div>
  );
}

window.Toolbar = Toolbar;
