// Additional primitives: Drawer, Toast, Tooltip, Dropdown
const { useState: Sp2, useEffect: Ep2, useRef: Rp2 } = React;

// ─────────── Drawer (slide-in panel from right) ───────────
function Drawer({ t, open, onClose, title, width=520, children }) {
  Ep2(() => {
    if (!open) return;
    const k = (e) => e.key === 'Escape' && onClose && onClose();
    document.addEventListener('keydown', k);
    return () => document.removeEventListener('keydown', k);
  }, [open, onClose]);

  if (!open) return null;
  return (
    <div style={{
      position:'fixed', inset:0, zIndex: 2000,
      display:'flex', justifyContent:'flex-end',
      background:'rgba(0,0,0,0.42)',
      animation:'daev-fade 140ms ease-out',
    }} onClick={onClose}>
      <div onClick={e=>e.stopPropagation()} style={{
        width, maxWidth:'90vw', height:'100%',
        background: t.bg0,
        borderLeft:`1px solid ${t.line2}`,
        boxShadow:'-20px 0 40px rgba(0,0,0,0.4)',
        display:'flex', flexDirection:'column',
        animation:'daev-slide-l 220ms cubic-bezier(0.2,0.9,0.2,1)',
      }}>
        <div style={{
          padding:'12px 16px',
          borderBottom:`1px solid ${t.line}`,
          display:'flex', alignItems:'center', gap: 12,
          flexShrink:0,
        }}>
          <div style={{
            fontFamily: t.font.mono, fontSize: 10, color: t.fg2,
            letterSpacing: 1, textTransform:'uppercase', fontWeight: 600,
          }}>{title}</div>
          <div style={{ flex:1 }}/>
          <button onClick={onClose} style={{
            background:'transparent', border:`1px solid ${t.line}`,
            color: t.fg2, cursor:'pointer', padding:'4px 8px',
            borderRadius: t.radius.sm, fontFamily: t.font.mono, fontSize:10,
            letterSpacing: 0.5, display:'flex', alignItems:'center', gap: 4,
          }}>
            ESC <Icon name="x" size={11}/>
          </button>
        </div>
        <div style={{ flex:1, overflow:'auto' }}>{children}</div>
      </div>
      <style dangerouslySetInnerHTML={{__html:`
        @keyframes daev-fade { from { opacity: 0 } to { opacity: 1 } }
        @keyframes daev-slide-l { from { transform: translateX(30px); opacity:0 } to { transform: translateX(0); opacity:1 } }
      `}}/>
    </div>
  );
}

// ─────────── Tooltip ───────────
function Tooltip({ t, label, children, placement='top' }) {
  const [show, setShow] = Sp2(false);
  const ref = Rp2(null);
  return (
    <span ref={ref} onMouseEnter={()=>setShow(true)} onMouseLeave={()=>setShow(false)}
      style={{ position:'relative', display:'inline-flex' }}>
      {children}
      {show && (
        <span style={{
          position:'absolute',
          bottom: placement==='top' ? '100%' : 'auto',
          top: placement==='bottom' ? '100%' : 'auto',
          left: '50%', transform:`translateX(-50%) translateY(${placement==='top'?'-6px':'6px'})`,
          background: t.bg3, color: t.fg0,
          border:`1px solid ${t.line2}`,
          borderRadius: t.radius.sm,
          padding:'4px 8px',
          fontFamily: t.font.mono, fontSize: 10,
          whiteSpace:'nowrap', pointerEvents:'none', zIndex: 100,
          boxShadow:'0 4px 12px rgba(0,0,0,0.3)',
        }}>{label}</span>
      )}
    </span>
  );
}

// ─────────── Dropdown (grouped) ───────────
function Dropdown({ t, value, onChange, groups, placeholder='Select…', width=260 }) {
  const [open, setOpen] = Sp2(false);
  const ref = Rp2(null);
  Ep2(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [open]);

  const selected = groups.flatMap(g => g.items).find(i => i.value === value);

  return (
    <div ref={ref} style={{ position:'relative', width }}>
      <button onClick={()=>setOpen(!open)} style={{
        width:'100%', display:'flex', alignItems:'center', gap: 8,
        padding:'7px 10px',
        background: t.bg1, border:`1px solid ${open ? t.accent.base : t.line}`,
        borderRadius: t.radius.sm, cursor:'pointer',
        fontFamily: t.font.ui, fontSize: 12, color: t.fg0,
        textAlign:'left',
      }}>
        {selected?.icon && <Icon name={selected.icon} size={12} color={t.accent.base}/>}
        <span style={{ flex:1, color: selected ? t.fg0 : t.fg2 }}>
          {selected ? selected.label : placeholder}
        </span>
        {selected?.sub && <span style={{ fontFamily: t.font.mono, fontSize: 10, color: t.fg3 }}>{selected.sub}</span>}
        <Icon name={open?'chevU':'chevD'} size={12} color={t.fg2}/>
      </button>
      {open && (
        <div style={{
          position:'absolute', top:'calc(100% + 4px)', left:0, right:0,
          background: t.bg1, border:`1px solid ${t.line2}`,
          borderRadius: t.radius.sm, zIndex: 50,
          boxShadow:'0 8px 24px rgba(0,0,0,0.35)',
          maxHeight: 340, overflow:'auto',
        }}>
          {groups.map((g, gi) => (
            <div key={gi}>
              <div style={{
                padding:'6px 10px', fontFamily: t.font.mono, fontSize: 9,
                color: t.fg3, letterSpacing: 1, textTransform:'uppercase',
                borderTop: gi>0 ? `1px solid ${t.line}` : 'none',
                background: t.bg2,
              }}>{g.label}</div>
              {g.items.map(it => {
                const active = it.value === value;
                return (
                  <button key={it.value}
                    onClick={()=>{ onChange(it.value); setOpen(false); }}
                    style={{
                      width:'100%', display:'flex', alignItems:'center', gap: 8,
                      padding:'7px 10px',
                      background: active ? t.accent.ghost : 'transparent',
                      border:'none', cursor:'pointer', textAlign:'left',
                      fontFamily: t.font.ui, fontSize: 12,
                      color: active ? t.accent.base : t.fg0,
                    }}>
                    {it.icon && <Icon name={it.icon} size={12} color={active ? t.accent.base : t.fg2}/>}
                    <span style={{ flex:1 }}>{it.label}</span>
                    {it.sub && <span style={{ fontFamily: t.font.mono, fontSize: 10, color: t.fg3 }}>{it.sub}</span>}
                    {active && <Icon name="check" size={11} color={t.accent.base}/>}
                  </button>
                );
              })}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ─────────── Toast (global registry) ───────────
function ToastHost({ t }) {
  const [toasts, setToasts] = Sp2([]);
  Ep2(() => {
    window.__daev_toast = (msg, tone='neutral') => {
      const id = Math.random().toString(36).slice(2);
      setToasts(ts => [...ts, { id, msg, tone }]);
      setTimeout(() => setToasts(ts => ts.filter(x => x.id !== id)), 3200);
    };
    return () => { delete window.__daev_toast; };
  }, []);
  return (
    <div style={{
      position:'fixed', bottom: 20, right: 20, zIndex: 3000,
      display:'flex', flexDirection:'column', gap: 8, alignItems:'flex-end',
    }}>
      {toasts.map(x => {
        const color = x.tone === 'red' ? t.semantic.red
                    : x.tone === 'green' ? t.semantic.green
                    : x.tone === 'amber' ? t.semantic.amber : t.accent.base;
        return (
          <div key={x.id} style={{
            background: t.bg2,
            border:`1px solid ${color}`,
            borderLeft: `3px solid ${color}`,
            borderRadius: t.radius.sm,
            padding:'8px 14px',
            fontFamily: t.font.mono, fontSize: 11.5, color: t.fg0,
            boxShadow:'0 8px 20px rgba(0,0,0,0.3)',
            animation: 'daev-toast-in 180ms ease-out',
            minWidth: 220, maxWidth: 420,
          }}>{x.msg}</div>
        );
      })}
      <style dangerouslySetInnerHTML={{__html:`
        @keyframes daev-toast-in { from { transform: translateX(20px); opacity:0 } to { transform: translateX(0); opacity:1 } }
      `}}/>
    </div>
  );
}

Object.assign(window, { Drawer, Tooltip, Dropdown, ToastHost });
