// Global toast + modal system. Exposes: window.toast(msg, opts), window.confirmDialog({...}), window.openModal(node)
const { createContext, useContext, useCallback } = React;

const NotifyCtx = createContext(null);

function NotifyProvider({ children }){
  const [toasts, setToasts] = useState([]);
  const [modal, setModal]   = useState(null);

  const toast = useCallback((message, opts={}) => {
    const id = Math.random().toString(36).slice(2);
    const t = { id, message, tone: opts.tone || 'info', title: opts.title, ttl: opts.ttl || 3200 };
    setToasts(ts => [...ts, t]);
    setTimeout(()=> setToasts(ts => ts.filter(x => x.id !== id)), t.ttl);
  }, []);

  const closeModal = useCallback(()=> setModal(null), []);

  const openModal = useCallback((opts) => {
    setModal({ ...opts, _id: Math.random().toString(36).slice(2) });
  }, []);

  const confirmDialog = useCallback(({ title='Confirm', message, tone='primary', okLabel='Confirm', cancelLabel='Cancel', onOk }) => {
    setModal({
      _id: Math.random().toString(36).slice(2),
      title, message, tone,
      actions: [
        { label: cancelLabel, kind:'ghost' },
        { label: okLabel, kind: tone, onClick: ()=>{ onOk && onOk(); } },
      ]
    });
  }, []);

  // expose globally for convenience
  useEffect(()=>{
    window.toast = toast;
    window.openModal = openModal;
    window.confirmDialog = confirmDialog;
    window.closeModal = closeModal;
  }, [toast, openModal, confirmDialog, closeModal]);

  return (
    <NotifyCtx.Provider value={{ toast, openModal, confirmDialog, closeModal }}>
      {children}
      {/* Toasts */}
      <div className="toasts">
        {toasts.map(t => (
          <div key={t.id} className={"toast toast-"+t.tone}>
            <div className="toast-ico">
              {t.tone==='success' ? <I.CheckCircle size={18}/>
                : t.tone==='danger' ? <I.AlertCircle size={18}/>
                : t.tone==='warn'   ? <I.AlertCircle size={18}/>
                : <I.Bell size={18}/>}
            </div>
            <div style={{flex:1,minWidth:0}}>
              {t.title && <div className="toast-title">{t.title}</div>}
              <div className="toast-msg">{t.message}</div>
            </div>
            <button className="toast-x" onClick={()=> setToasts(ts => ts.filter(x => x.id !== t.id))}>×</button>
          </div>
        ))}
      </div>

      {/* Modal */}
      {modal && (
        <div className="modal-backdrop" onClick={(e)=> { if (e.target===e.currentTarget) closeModal(); }}>
          <div className="modal" style={{maxWidth: modal.size==='lg' ? 720 : modal.size==='md'?540:440}}>
            <div className="modal-head">
              <div className="modal-title">{modal.title}</div>
              <button className="modal-x" onClick={closeModal}>×</button>
            </div>
            <div className="modal-body">
              {typeof modal.message === 'string'
                ? <p style={{margin:0,color:'var(--ink-2)',fontSize:14,lineHeight:1.55}}>{modal.message}</p>
                : modal.message}
            </div>
            {modal.actions && (
              <div className="modal-foot">
                {modal.actions.map((a,i) => (
                  <button key={i}
                          className={"btn "+(a.kind==='ghost'?'':a.kind==='danger'?'danger':a.kind==='success'?'success':a.kind==='teal'?'teal':'primary')}
                          onClick={()=>{ a.onClick && a.onClick(); closeModal(); }}>
                    {a.label}
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>
      )}
    </NotifyCtx.Provider>
  );
}

// CSV helper exposed globally
function downloadCSV(filename, rows){
  const csv = rows.map(r => r.map(c => {
    const s = c == null ? '' : String(c);
    return /[",\n]/.test(s) ? `"${s.replace(/"/g,'""')}"` : s;
  }).join(',')).join('\n');
  const blob = new Blob(["\uFEFF"+csv], { type:'text/csv;charset=utf-8' });
  const url  = URL.createObjectURL(blob);
  const a    = document.createElement('a');
  a.href = url; a.download = filename;
  document.body.appendChild(a); a.click(); a.remove();
  setTimeout(()=>URL.revokeObjectURL(url), 1500);
}

window.NotifyProvider = NotifyProvider;
window.NotifyCtx = NotifyCtx;
window.downloadCSV = downloadCSV;
