/* global React, Icon, cn */
const { useState: _useState, useEffect: _useEffect, useRef: _useRef } = React;

// ---- Extra icons (extend the core set)
const ExtraIcons = {
  trash:   (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><path d="M3 6h18"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/></svg>,
  edit:    (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>,
  phone:   (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><path d="M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6 19.8 19.8 0 0 1-3.1-8.7A2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7 13 13 0 0 0 .7 2.8 2 2 0 0 1-.5 2.1L8.1 9.9a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.5 13 13 0 0 0 2.8.7 2 2 0 0 1 1.7 2Z"/></svg>,
  x:       (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><path d="M18 6 6 18M6 6l12 12"/></svg>,
  filter:  (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><path d="M22 3H2l8 9.5V19l4 2v-8.5L22 3z"/></svg>,
  grid:    (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>,
  list:    (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/></svg>,
  dl:      (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/></svg>,
  play:    (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><polygon points="6 4 20 12 6 20 6 4"/></svg>,
  pause:   (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/></svg>,
  eye:     (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>,
  copy:    (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>,
  send:    (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><path d="m22 2-7 20-4-9-9-4 20-7Z"/></svg>,
  pin:     (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><path d="M12 22s-8-7.5-8-13a8 8 0 1 1 16 0c0 5.5-8 13-8 13z"/><circle cx="12" cy="9" r="3"/></svg>,
  box:     (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><path d="M21 16V8l-9-5-9 5v8l9 5 9-5z"/><path d="M3.3 7 12 12l8.7-5M12 22V12"/></svg>,
  truck:   (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><path d="M1 3h15v13H1zM16 8h4l3 3v5h-7"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/></svg>,
  zap:     (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>,
  robot:   (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><rect x="3" y="8" width="18" height="12" rx="2"/><path d="M12 8V4M8 4h8"/><circle cx="8.5" cy="14" r="1"/><circle cx="15.5" cy="14" r="1"/></svg>,
  dollar:  (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><path d="M12 1v22M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>,
  trend:   (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><path d="m22 7-8.5 8.5-5-5L2 17"/><path d="M16 7h6v6"/></svg>,
  link:    (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><path d="M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1"/><path d="M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1"/></svg>,
  calendar:(p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>,
  flask:   (p)=><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={p.c}><path d="M9 3h6M10 3v6L4 20a2 2 0 0 0 2 3h12a2 2 0 0 0 2-3L14 9V3"/></svg>,
};

// ---- Tabs
function Tabs({tabs, active, onChange, counts={}}) {
  return <div className="border-b border-slate-200 flex items-center gap-1 px-1">
    {tabs.map(t => {
      const key = typeof t === 'string' ? t : t.key;
      const label = typeof t === 'string' ? t : t.label;
      const isActive = key === active;
      return <button key={key} onClick={()=>onChange(key)}
        className={['relative px-3 py-2.5 text-[12.5px] font-medium transition-colors flex items-center gap-1.5',
          isActive ? 'text-helios-700' : 'text-ink-500 hover:text-ink-800'].join(' ')}>
        {label}
        {counts[key] !== undefined && <span className={['text-[10px] font-mono px-1.5 rounded-full',
          isActive?'bg-helios-100 text-helios-700':'bg-slate-100 text-ink-500'].join(' ')}>{counts[key]}</span>}
        {isActive && <span className="absolute left-2 right-2 -bottom-px h-0.5 bg-helios-600 rounded-full"/>}
      </button>;
    })}
  </div>;
}

// ---- Modal
function Modal({open, onClose, title, subtitle, children, footer, width='w-[520px]'}) {
  if (!open) return null;
  return <div className="fixed inset-0 z-50 flex items-center justify-center px-4" onClick={onClose}>
    <div className="absolute inset-0 bg-ink-900/40 backdrop-blur-[1px]" style={{animation:'fadeIn 180ms'}}/>
    <div onClick={e=>e.stopPropagation()}
      className={'relative bg-white rounded-2xl shadow-pop border border-slate-100 overflow-hidden '+width}
      style={{boxShadow:'0 12px 40px -12px rgba(8,11,18,0.25), 0 4px 12px -4px rgba(8,11,18,0.08)', animation:'slideUp 220ms'}}>
      <div className="px-5 pt-4 pb-3 border-b border-slate-100 flex items-start justify-between gap-3">
        <div>
          <h3 className="font-display font-semibold text-[15px] text-ink-800">{title}</h3>
          {subtitle && <p className="text-[11.5px] text-ink-400 mt-0.5">{subtitle}</p>}
        </div>
        <button onClick={onClose} className="text-ink-400 hover:text-ink-800 p-1 -m-1"><ExtraIcons.x c="w-4 h-4"/></button>
      </div>
      <div className="px-5 py-4 max-h-[70vh] overflow-y-auto">{children}</div>
      {footer && <div className="px-5 py-3 border-t border-slate-100 bg-slate-50 flex items-center justify-end gap-2">{footer}</div>}
    </div>
  </div>;
}

// ---- Drawer (right-side slide-in)
function Drawer({open, onClose, title, subtitle, children, width='w-[480px]'}) {
  if (!open) return null;
  return <div className="fixed inset-0 z-50" onClick={onClose}>
    <div className="absolute inset-0 bg-ink-900/30" style={{animation:'fadeIn 180ms'}}/>
    <div onClick={e=>e.stopPropagation()}
      className={'absolute right-0 top-0 bottom-0 bg-white border-l border-slate-100 overflow-hidden flex flex-col '+width}
      style={{boxShadow:'-20px 0 40px -20px rgba(8,11,18,0.25)', animation:'slideLeft 220ms'}}>
      <div className="px-5 pt-4 pb-3 border-b border-slate-100 flex items-start justify-between gap-3">
        <div>
          <h3 className="font-display font-semibold text-[15px] text-ink-800">{title}</h3>
          {subtitle && <p className="text-[11.5px] text-ink-400 mt-0.5">{subtitle}</p>}
        </div>
        <button onClick={onClose} className="text-ink-400 hover:text-ink-800 p-1 -m-1"><ExtraIcons.x c="w-4 h-4"/></button>
      </div>
      <div className="flex-1 overflow-y-auto">{children}</div>
    </div>
  </div>;
}

// ---- Input, Select, Textarea
function Field({label, children, hint, error}) {
  return <label className="block">
    {label && <div className="text-[11px] font-medium text-ink-600 mb-1">{label}</div>}
    {children}
    {hint && <div className="text-[10.5px] text-ink-400 mt-1">{hint}</div>}
    {error && <div className="text-[10.5px] text-[#B93535] mt-1">{error}</div>}
  </label>;
}
function Input(props) {
  return <input {...props} className={'w-full px-3 py-2 text-[12.5px] bg-white border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-helios-400/50 focus:border-helios-400 '+(props.className||'')}/>;
}
function Select({children, ...props}) {
  return <select {...props} className={'w-full px-3 py-2 text-[12.5px] bg-white border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-helios-400/50 '+(props.className||'')}>{children}</select>;
}
function Textarea(props) {
  return <textarea {...props} className={'w-full px-3 py-2 text-[12.5px] bg-white border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-helios-400/50 min-h-[80px] '+(props.className||'')}/>;
}

// ---- Toast system
function useToast() {
  const [toasts, setToasts] = _useState([]);
  const push = (msg, tone='ok') => {
    const id = Math.random().toString(36).slice(2);
    setToasts(t => [...t, {id, msg, tone}]);
    setTimeout(()=>setToasts(t => t.filter(x=>x.id!==id)), 3200);
  };
  const ToastHost = () => <div className="fixed bottom-5 right-5 z-[60] flex flex-col gap-2">
    {toasts.map(t => <div key={t.id}
      className={'px-3.5 py-2.5 rounded-xl shadow-pop border text-[12.5px] font-medium flex items-center gap-2 bg-white '+(
        t.tone==='danger'?'border-[#E04B4B]/30 text-[#B93535]':
        t.tone==='warn'?'border-[#EEA028]/30 text-[#D28513]':
        'border-[#2EA571]/30 text-[#1E8057]'
      )} style={{boxShadow:'0 12px 40px -12px rgba(8,11,18,0.25)', animation:'slideUp 220ms'}}>
      <span className={'w-2 h-2 rounded-full '+(t.tone==='danger'?'bg-[#E04B4B]':t.tone==='warn'?'bg-[#EEA028]':'bg-[#2EA571]')}/>
      {t.msg}
    </div>)}
  </div>;
  return {push, ToastHost};
}

// Resolve icon by string name from either Icon or ExtraIcons set
function IconOf({name, c='w-4 h-4'}) {
  const Cmp = (window.ExtraIcons && window.ExtraIcons[name]) || (window.Icon && window.Icon[name]) || null;
  if (!Cmp) return null;
  return <Cmp c={c}/>;
}

// ---- FilterSelect: custom dropdown with consistent design system styling
// Use for inline/toolbar filters. `align`: 'left' (default) or 'right' to anchor panel from the right.
function FilterSelect({label, value, onChange, options, align='left', minWidth=140}) {
  const [open, setOpen] = _useState(false);
  const ref = _useRef(null);
  _useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => { document.removeEventListener('mousedown', onDoc); document.removeEventListener('keydown', onKey); };
  }, [open]);

  return <div className="inline-flex items-center gap-1.5 text-[11px] text-ink-500 relative" ref={ref}>
    {label && <span className="font-mono uppercase tracking-wider text-[9.5px] font-semibold">{label}</span>}
    <button type="button" onClick={()=>setOpen(o=>!o)}
      className={'inline-flex items-center gap-1.5 pl-2.5 pr-2 py-1 text-[11.5px] bg-white border rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-helios-400/50 cursor-pointer transition-colors '+(open?'border-helios-400 text-ink-800 ring-2 ring-helios-400/50':'border-slate-200 text-ink-700 hover:border-slate-300')}>
      <span>{value}</span>
      <svg className={'w-3 h-3 text-ink-400 transition-transform '+(open?'rotate-180':'')} viewBox="0 0 12 12" fill="none"><path d="M3 4.5L6 7.5L9 4.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
    </button>
    {open && <div className={'absolute top-full mt-1 z-30 bg-white border border-slate-200 rounded-lg shadow-[0_8px_24px_-6px_rgba(15,23,42,0.18),0_2px_6px_-2px_rgba(15,23,42,0.08)] py-1 animate-[fadeIn_120ms_ease-out] max-h-[280px] overflow-auto '+(align==='right'?'right-0':'left-auto')}
      style={{minWidth, [align==='right'?'right':'left']:0}}>
      {options.map(o => {
        const sel = o === value;
        return <button key={o} type="button" onClick={()=>{onChange(o); setOpen(false);}}
          className={'w-full flex items-center justify-between gap-2 px-2.5 py-1.5 text-[12px] text-left transition-colors '+(sel?'bg-helios-50 text-helios-700 font-semibold':'text-ink-700 hover:bg-slate-50')}>
          <span className="truncate">{o}</span>
          {sel && <svg className="w-3.5 h-3.5 shrink-0" viewBox="0 0 14 14" fill="none"><path d="M3 7.5L6 10.5L11 4.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>}
        </button>;
      })}
    </div>}
  </div>;
}

Object.assign(window, {ExtraIcons, IconOf, Tabs, Modal, Drawer, Field, Input, Select, Textarea, useToast, FilterSelect});
