// App primitives
const { useState, useEffect, useRef } = React;

function Icon({ name }) {
  const ref = useRef(null);
  useEffect(() => {
    if (ref.current && window.lucide) {
      ref.current.innerHTML = '';
      const i = document.createElement('i');
      i.setAttribute('data-lucide', name);
      ref.current.appendChild(i);
      try { window.lucide.createIcons(); } catch (e) {}
    }
  }, [name]);
  return <span ref={ref} style={{ display: 'inline-flex' }} />;
}

function Chip({ kind, children }) {
  return <span className={`chip ${kind}`}><span className="d" />{children}</span>;
}

const HEALTH = { resolved: '#33D499', warning: '#E8B23E', urgent: '#E2574A' };

/* ---------------------------------------------------------------------------
   Global overlays: toasts + a generic modal sheet. Exposed on window so any
   component (and any wired button) can fire feedback without prop-drilling:
     window.opsToast('Vendor dispatched', { kind:'resolved', sub:'ASE Fire notified' })
     window.opsModal({ title, body })  /  window.opsCloseModal()
     window.opsNav('intake')  /  window.opsBuilding('Harbourview')   (set by App)
--------------------------------------------------------------------------- */
let _toastSeq = 0;
function ToastHost() {
  const [toasts, setToasts] = useState([]);
  useEffect(() => {
    window.opsToast = (msg, opts = {}) => {
      const id = ++_toastSeq;
      const t = { id, msg, kind: opts.kind || 'resolved', sub: opts.sub || '', icon: opts.icon };
      setToasts(list => [...list, t]);
      setTimeout(() => setToasts(list => list.filter(x => x.id !== id)), opts.duration || 3600);
    };
    return () => { delete window.opsToast; };
  }, []);
  const ice = { resolved: 'check-circle-2', info: 'info', warning: 'alert-triangle', urgent: 'alert-octagon', auto: 'sparkles' };
  return (
    <div className="toast-host" role="status" aria-live="polite">
      {toasts.map(t => (
        <div key={t.id} className={`toast ${t.kind}`} onClick={() => setToasts(l => l.filter(x => x.id !== t.id))}>
          <span className="ti"><Icon name={t.icon || ice[t.kind] || 'check-circle-2'} /></span>
          <div className="tt"><div className="tm">{t.msg}</div>{t.sub && <div className="ts">{t.sub}</div>}</div>
        </div>
      ))}
    </div>
  );
}

// Generic modal sheet. content: { title, sub, body (JSX), wide }
function ModalHost() {
  const [content, setContent] = useState(null);
  useEffect(() => {
    window.opsModal = (c) => setContent(c);
    window.opsCloseModal = () => setContent(null);
    return () => { delete window.opsModal; delete window.opsCloseModal; };
  }, []);
  useEffect(() => {
    const onKey = e => { if (e.key === 'Escape') setContent(null); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);
  if (!content) return null;
  return ReactDOM.createPortal(
    <div className="modal-scrim" onClick={() => setContent(null)}>
      <div className={`modal ${content.wide ? 'wide' : ''}`} onClick={e => e.stopPropagation()} role="dialog" aria-modal="true">
        <div className="modal-h">
          <div>
            <h3>{content.title}</h3>
            {content.sub && <div className="modal-sub">{content.sub}</div>}
          </div>
          <button className="icon-btn" onClick={() => setContent(null)} aria-label="Close"><Icon name="x" /></button>
        </div>
        <div className="modal-body">{content.body}</div>
      </div>
    </div>, document.body);
}

// convenience used by wired buttons
function act(msg, opts) { if (window.opsToast) window.opsToast(msg, opts); }

// responsive hook — true under `bp` px (default 820 = tablet/phone)
function useIsMobile(bp = 820) {
  const [m, setM] = useState(() => typeof window !== 'undefined' && window.innerWidth <= bp);
  useEffect(() => {
    const on = () => setM(window.innerWidth <= bp);
    window.addEventListener('resize', on);
    return () => window.removeEventListener('resize', on);
  }, [bp]);
  return m;
}

Object.assign(window, { Icon, Chip, HEALTH, ToastHost, ModalHost, act, useIsMobile });
