// ─────────────────────────────────────────────────────────────────
// Work detail · inline edit mode
// ─────────────────────────────────────────────────────────────────
// Wraps the work-detail Overview tab in editable widgets when
// `editing` is true. State is held locally — no real persistence;
// changes are pushed onto a history stack rendered in a side drawer.
// ─────────────────────────────────────────────────────────────────

const { useState, useRef, useEffect, useMemo } = React;

// ───────── undo history ─────────
function useEditHistory(initial) {
  const [data, setData] = useState(initial);
  // history entries: { ts, label, before, after }
  const [history, setHistory] = useState([]);
  const [cursor, setCursor] = useState(0); // points to "current" snapshot index

  const commit = (label, mutator) => {
    setData(prev => {
      const before = prev;
      const next = typeof mutator === 'function' ? mutator(prev) : mutator;
      // truncate any redo branches when committing new
      setHistory(h => {
        const trimmed = h.slice(0, cursor);
        return [...trimmed, { ts: Date.now(), label, before, after: next }];
      });
      setCursor(c => c + 1);
      return next;
    });
  };

  const undo = () => {
    if (cursor <= 0) return;
    const entry = history[cursor - 1];
    setData(entry.before);
    setCursor(c => c - 1);
  };

  const redo = () => {
    if (cursor >= history.length) return;
    const entry = history[cursor];
    setData(entry.after);
    setCursor(c => c + 1);
  };

  const revertTo = (idx) => {
    // idx is into history[]; revert to the "before" of history[idx],
    // i.e. the state as it was at history[idx].before
    if (idx < 0 || idx >= history.length) return;
    setData(history[idx].before);
    setCursor(idx);
  };

  return { data, setData, commit, history, cursor, undo, redo, revertTo };
}

// ───────── editable text (inline contenteditable) ─────────
function InlineText({ value, onCommit, multiline=false, className='', style={}, placeholder='', as='span' }) {
  const ref = useRef(null);
  const [editing, setEditing] = useState(false);
  const [local, setLocal] = useState(value);

  useEffect(() => { setLocal(value); }, [value]);

  const finish = () => {
    setEditing(false);
    const trimmed = (local || '').trim();
    if (trimmed !== (value||'').trim()) onCommit(trimmed);
  };

  const Tag = as;
  return (
    <Tag
      ref={ref}
      contentEditable
      suppressContentEditableWarning
      onFocus={()=>setEditing(true)}
      onBlur={(e)=>{ setLocal(e.currentTarget.textContent); finish(); }}
      onInput={(e)=>setLocal(e.currentTarget.textContent)}
      onKeyDown={(e)=>{
        if (!multiline && e.key==='Enter') { e.preventDefault(); e.currentTarget.blur(); }
        if (e.key==='Escape') { e.currentTarget.textContent = value; e.currentTarget.blur(); }
      }}
      data-placeholder={placeholder}
      className={(className || '') + ' inline-edit'}
      style={{
        padding: '2px 6px',
        margin: '-2px -6px',
        borderRadius: 3,
        cursor: 'text',
        background: editing ? 'var(--bg)' : 'var(--edit-fill)',
        boxShadow: editing ? 'inset 0 0 0 1.5px var(--ink)' : 'none',
        outline: 'none',
        transition: 'background .12s ease',
        ...style,
      }}
      onMouseEnter={(e)=>{ if (!editing) e.currentTarget.style.background='var(--edit-fill-hover)'; }}
      onMouseLeave={(e)=>{ if (!editing) e.currentTarget.style.background='var(--edit-fill)'; }}>
      {value || ''}
    </Tag>
  );
}

// ───────── editable select ─────────
function InlineSelect({ value, options, onCommit, className='ff-mono', style={} }) {
  return (
    <select
      value={value}
      onChange={e=>onCommit(e.target.value)}
      className={className}
      style={{
        padding:'3px 8px',
        background:'var(--edit-fill)',
        border:'none',
        borderRadius:3,
        fontSize:11,
        color:'var(--ink)',
        cursor:'pointer',
        appearance:'none',
        WebkitAppearance:'none',
        backgroundImage:'linear-gradient(45deg, transparent 50%, var(--ink-3) 50%), linear-gradient(135deg, var(--ink-3) 50%, transparent 50%)',
        backgroundPosition:'calc(100% - 12px) 50%, calc(100% - 8px) 50%',
        backgroundSize:'4px 4px, 4px 4px',
        backgroundRepeat:'no-repeat',
        paddingRight:22,
        ...style,
      }}>
      {options.map(o => (
        typeof o === 'string'
          ? <option key={o} value={o}>{o}</option>
          : <option key={o.value} value={o.value}>{o.label}</option>
      ))}
    </select>
  );
}

// ───────── saved-pulse marker (briefly highlights an edited node) ─────────
function useSavedPulse() {
  const [pulseId, setPulseId] = useState(null);
  const trigger = (id) => {
    setPulseId(id);
    setTimeout(() => setPulseId(p => p===id ? null : p), 900);
  };
  return { pulseId, trigger };
}

// ───────── history drawer ─────────
function HistoryDrawer({ open, onClose, history, cursor, onRevert, onUndo, onRedo }) {
  if (!open) return null;
  return (
    <>
      <div onClick={onClose} style={{position:'fixed',inset:0,background:'rgba(0,0,0,.18)',zIndex:70}}/>
      <aside style={{
        position:'fixed',top:0,right:0,bottom:0,width:380,background:'var(--bg)',
        borderLeft:'1px solid var(--ink)',zIndex:71,display:'flex',flexDirection:'column',
        boxShadow:'-20px 0 40px rgba(0,0,0,.18)'}}>
        <div style={{padding:'18px 20px',borderBottom:'1px solid var(--rule)',display:'flex',alignItems:'center',justifyContent:'space-between'}}>
          <div>
            <div className="ff-mono upper" style={{fontSize:9,letterSpacing:'.14em',color:'var(--ink-3)',marginBottom:2}}>EDIT HISTORY</div>
            <div className="ff-display" style={{fontSize:18,fontWeight:600,letterSpacing:'-0.01em'}}>{history.length} change{history.length===1?'':'s'}</div>
          </div>
          <button onClick={onClose} style={{background:'transparent',border:0,padding:6,cursor:'pointer'}}>
            <Ic.X width={18} height={18}/>
          </button>
        </div>

        <div style={{padding:'10px 20px',borderBottom:'1px solid var(--rule)',display:'flex',gap:8}}>
          <button onClick={onUndo} disabled={cursor<=0}
            className="ff-mono upper" style={{fontSize:10,letterSpacing:'.08em',padding:'8px 12px',
              background: cursor<=0 ? 'var(--bg-2)' : 'var(--bg)',
              border:'1px solid var(--rule)',color: cursor<=0 ? 'var(--ink-4)' : 'var(--ink)',
              cursor: cursor<=0 ? 'default' : 'pointer'}}>
            ⌘Z UNDO
          </button>
          <button onClick={onRedo} disabled={cursor>=history.length}
            className="ff-mono upper" style={{fontSize:10,letterSpacing:'.08em',padding:'8px 12px',
              background: cursor>=history.length ? 'var(--bg-2)' : 'var(--bg)',
              border:'1px solid var(--rule)',color: cursor>=history.length ? 'var(--ink-4)' : 'var(--ink)',
              cursor: cursor>=history.length ? 'default' : 'pointer'}}>
            ⌘⇧Z REDO
          </button>
        </div>

        <div style={{flex:1,overflowY:'auto',padding:'10px 0'}}>
          {history.length === 0 ? (
            <div className="ff-mono" style={{padding:'40px 24px',textAlign:'center',fontSize:12,color:'var(--ink-3)',fontStyle:'italic',lineHeight:1.6}}>
              No changes yet. Edits will appear here as you make them.
            </div>
          ) : (
            history.slice().reverse().map((h, ridx) => {
              const idx = history.length - 1 - ridx;
              const isCurrent = idx === cursor - 1;
              const isFuture = idx >= cursor;
              return (
                <div key={idx} onClick={()=>onRevert(idx)}
                  style={{padding:'10px 20px',borderBottom:'1px solid var(--rule-soft)',cursor:'pointer',
                    background: isCurrent ? 'var(--bg-2)' : 'transparent',
                    opacity: isFuture ? 0.4 : 1,
                    borderLeft: isCurrent ? '3px solid var(--ink)' : '3px solid transparent'}}>
                  <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',gap:8}}>
                    <span style={{fontSize:13,fontWeight:isCurrent?600:500,color:'var(--ink)'}}>{h.label}</span>
                    <span className="ff-mono" style={{fontSize:9,color:'var(--ink-4)',whiteSpace:'nowrap'}}>{relTime(h.ts)}</span>
                  </div>
                  <div className="ff-mono upper" style={{fontSize:9,color:'var(--ink-3)',marginTop:2,letterSpacing:'.06em'}}>
                    {isCurrent ? '· CURRENT' : isFuture ? '· REDOABLE' : '· CLICK TO REVERT'}
                  </div>
                </div>
              );
            })
          )}
        </div>
      </aside>
    </>
  );
}

function relTime(ts) {
  const s = Math.floor((Date.now()-ts)/1000);
  if (s<5) return 'just now';
  if (s<60) return s+'s ago';
  if (s<3600) return Math.floor(s/60)+'m ago';
  return Math.floor(s/3600)+'h ago';
}

// ───────── splits-bar drag handle ─────────
function DragSplits({ writers, onCommit }) {
  // Each writer has a share. Total must = 100. Drag the divider between two
  // writers to redistribute share between them.
  const total = writers.reduce((a,w)=>a+(+w.share||0),0);
  const containerRef = useRef(null);

  const startDrag = (i, e) => {
    e.preventDefault();
    const rect = containerRef.current.getBoundingClientRect();
    const startX = e.clientX;
    const a = +writers[i].share;
    const b = +writers[i+1].share;
    const onMove = (ev) => {
      const dx = ev.clientX - startX;
      const dPct = (dx / rect.width) * 100;
      let newA = Math.round(a + dPct);
      let newB = Math.round(b - dPct);
      newA = Math.max(0, Math.min(a+b, newA));
      newB = (a+b) - newA;
      const next = writers.map((w,j) => j===i ? {...w, share:newA} : j===i+1 ? {...w, share:newB} : w);
      onCommit(next, false); // intermediate, no history entry
    };
    const onUp = () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
      onCommit(null, true); // final commit (snapshot to history)
    };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
  };

  // Distinct, harmonious palette for writer slices
  const PALETTE = [
    'oklch(0.62 0.16 50)',   // burnt orange
    'oklch(0.55 0.13 240)',  // slate blue
    'oklch(0.68 0.14 140)',  // sage green
    'oklch(0.58 0.17 25)',   // terracotta
    'oklch(0.50 0.10 290)',  // muted violet
    'oklch(0.65 0.12 85)',   // ochre
  ];

  return (
    <div ref={containerRef} style={{
      display:'flex',height:18,background:'var(--bg-2)',position:'relative',
      border:'1px solid var(--rule)',userSelect:'none',marginBottom:14,overflow:'hidden'}}>
      {writers.map((w,i) => {
        const pct = total ? ((+w.share||0)/total*100) : 0;
        const color = PALETTE[i % PALETTE.length];
        return (
          <React.Fragment key={i}>
            <div style={{
              width:`${pct}%`,
              background: color,
              transition:'background .15s',
              position:'relative',
              display:'flex',alignItems:'center',justifyContent:'center',
              color:'#fff',fontSize:10,fontWeight:600,letterSpacing:'.06em',
              textShadow:'0 1px 0 rgba(0,0,0,.15)'}}
              className="ff-mono">
              {pct >= 10 && `${Math.round(pct)}%`}
            </div>
            {i < writers.length-1 && (
              <div onMouseDown={(e)=>startDrag(i,e)}
                style={{width:6,marginLeft:-3,marginRight:-3,cursor:'col-resize',background:'transparent',
                  position:'relative',zIndex:2,
                  display:'flex',alignItems:'center',justifyContent:'center'}}>
                <div style={{width:2,height:18,background:'var(--accent, #d97757)',marginTop:-2}}/>
              </div>
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

// Export
Object.assign(window, {
  useEditHistory,
  InlineText,
  InlineSelect,
  useSavedPulse,
  HistoryDrawer,
  DragSplits,
  relTime,
});
