// UI primitives, helpers
const { useState, useEffect, useRef, useMemo, useCallback, createContext, useContext } = React;

function fmt(n) {
  return 'Rs ' + Math.round(n).toLocaleString('en-PK');
}

function uniqBy(arr, key) {
  const seen = new Set();
  return arr.filter(x => { const k = key(x); if (seen.has(k)) return false; seen.add(k); return true; });
}

// Stars row (display)
function Stars({ value, count, showCount = true }) {
  const full = Math.round(value);
  return (
    <span className="stars" aria-label={`${value} of 5 stars`}>
      {[1,2,3,4,5].map(i => (
        <Ic.star key={i} fill={i <= full ? 'currentColor' : 'none'} stroke={i <= full ? 'none' : 'currentColor'} strokeWidth="1" />
      ))}
      {showCount && count != null && <span className="count">({count})</span>}
    </span>
  );
}

// Toast hook + component
const ToastCtx = createContext(null);
function ToastProvider({ children }) {
  const [msg, setMsg] = useState(null);
  const timer = useRef();
  const show = useCallback((m) => {
    setMsg(m);
    clearTimeout(timer.current);
    timer.current = setTimeout(() => setMsg(null), 2400);
  }, []);
  return (
    <ToastCtx.Provider value={show}>
      {children}
      <div className={'toast' + (msg ? ' is-show' : '')}>
        {msg && <Ic.check />}
        <span>{msg}</span>
      </div>
    </ToastCtx.Provider>
  );
}
const useToast = () => useContext(ToastCtx);

// Reusable: empty state
function Empty({ title, hint, cta, onCta }) {
  return (
    <div className="empty-state">
      <Ic.bag />
      <h3>{title}</h3>
      <p>{hint}</p>
      {cta && <button className="btn btn-primary" onClick={onCta}>{cta}</button>}
    </div>
  );
}

// useEsc
function useEscape(handler, active) {
  useEffect(() => {
    if (!active) return;
    const fn = (e) => { if (e.key === 'Escape') handler(); };
    window.addEventListener('keydown', fn);
    return () => window.removeEventListener('keydown', fn);
  }, [handler, active]);
}

// Lock body scroll when an overlay is open
function useScrollLock(active) {
  useEffect(() => {
    if (!active) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, [active]);
}

window.fmt = fmt;
window.uniqBy = uniqBy;
window.Stars = Stars;
window.ToastProvider = ToastProvider;
window.useToast = useToast;
window.Empty = Empty;
window.useEscape = useEscape;
window.useScrollLock = useScrollLock;
