// components.jsx — shared UI primitives
const { useState, useEffect, useRef, createContext, useContext } = React;

/* ---------- App context (nav + toast + open helpers) ---------- */
const AppCtx = createContext(null);
const useApp = () => useContext(AppCtx);

/* ---------- Button ---------- */
function Button({ variant = 'default', size, icon, iconR, children, className = '', ...rest }) {
  const cls = ['btn', 'btn-' + variant, size && 'btn-' + size, !children && 'btn-icon', className].filter(Boolean).join(' ');
  return (
    <button className={cls} {...rest}>
      {icon && <Icon name={icon} size={size === 'sm' ? 15 : 16} />}
      {children}
      {iconR && <Icon name={iconR} size={size === 'sm' ? 15 : 16} />}
    </button>
  );
}

/* ---------- Brand logo chip ---------- */
function BrandLogo({ brand, size = 24 }) {
  const b = typeof brand === 'string' ? brandOf(brand) : brand;
  return (
    <div className="brand-logo" style={{ background: b.color, width: size, height: size, minWidth: size, fontSize: size * 0.42 }}
         title={b.name}>{b.name[0]}</div>
  );
}

/* ---------- Image placeholder (striped, labelled) ---------- */
function Placeholder({ label, brand, ratio = '3/4', className = '', style = {}, tag, big }) {
  return (
    <div className={'ph ' + className} style={{ aspectRatio: ratio, ...style }}>
      {brand && <div className="ph-brandtag"><BrandLogo brand={brand} size={big ? 26 : 20} /></div>}
      {tag && <div className="ph-brandtag">{tag}</div>}
      <div className="ph-label">{label || 'product shot'}</div>
    </div>
  );
}

/* ---------- Score + status pills ---------- */
function Score({ value }) {
  const cls = value >= 70 ? 'score-hi' : value >= 40 ? 'score-mid' : 'score-lo';
  return <span className={'score ' + cls} title={'Điểm: ' + value + '/100'}>{value}</span>;
}
function StatusPill({ status }) {
  const s = STATUS[status] || STATUS.ready;
  return <span className={'badge ' + s.cls}><span className="dot"></span>{s.label}</span>;
}
function Badge({ variant = 'neutral', children, icon }) {
  return <span className={'badge badge-' + variant}>{icon && <Icon name={icon} size={12} />}{children}</span>;
}

/* ---------- Checkbox / Toggle ---------- */
function Checkbox({ on, onChange }) {
  return (
    <div className={'cbx ' + (on ? 'on' : '')} role="checkbox" aria-checked={on}
         onClick={(e) => { e.stopPropagation(); onChange && onChange(!on); }}>
      {on && <Icon name="check" size={12} stroke={3} />}
    </div>
  );
}
function Toggle({ on, onChange }) {
  return <div className={'switch ' + (on ? 'on' : '')} role="switch" aria-checked={on}
              onClick={() => onChange && onChange(!on)}><span className="knob"></span></div>;
}

/* ---------- Segmented ---------- */
function Seg({ value, options, onChange }) {
  return (
    <div className="seg">
      {options.map(o => {
        const val = typeof o === 'string' ? o : o.value;
        const lbl = typeof o === 'string' ? o : o.label;
        return <button key={val} className={value === val ? 'active' : ''} onClick={() => onChange(val)}>{lbl}</button>;
      })}
    </div>
  );
}

/* ---------- Empty state ---------- */
function Empty({ icon = 'inbox', title, desc, cta, onCta }) {
  return (
    <div className="empty">
      <div className="empty-art"><Icon name={icon} size={34} stroke={1.5} /></div>
      <div><h3>{title}</h3></div>
      {desc && <p>{desc}</p>}
      {cta && <Button variant="primary" icon="plus" onClick={onCta}>{cta}</Button>}
    </div>
  );
}

/* ---------- Drawer ---------- */
function Drawer({ title, sub, onClose, children, foot, head }) {
  useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, []);
  return (
    <>
      <div className="scrim" onClick={onClose}></div>
      <aside className="drawer" role="dialog" aria-modal="true">
        <div className="drawer-head">
          {head || (<>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="t-h2 clip-1">{title}</div>
              {sub && <div className="t-xs dimmer clip-1">{sub}</div>}
            </div>
          </>)}
          <Button variant="ghost" size="sm" icon="x" onClick={onClose} aria-label="Đóng" />
        </div>
        <div className="drawer-body">{children}</div>
        {foot && <div className="drawer-foot">{foot}</div>}
      </aside>
    </>
  );
}

/* ---------- Modal ---------- */
function Modal({ title, sub, onClose, children, foot, width }) {
  useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, []);
  return (
    <div className="modal-wrap">
      <div className="scrim" onClick={onClose}></div>
      <div className="modal" style={width ? { width } : {}} role="dialog" aria-modal="true">
        <div className="modal-head">
          <div className="between">
            <div>
              <div className="t-h1">{title}</div>
              {sub && <div className="t-sm dim" style={{ marginTop: 4 }}>{sub}</div>}
            </div>
            <Button variant="ghost" size="sm" icon="x" onClick={onClose} aria-label="Đóng" />
          </div>
        </div>
        <div className="modal-body">{children}</div>
        {foot && <div className="modal-foot">{foot}</div>}
      </div>
    </div>
  );
}

/* ---------- Toast region ---------- */
function ToastRegion({ toasts }) {
  return (
    <div className="toast-region">
      {toasts.map(t => (
        <div className="toast" key={t.id}>
          <Icon name={t.icon || 'checkCircle'} size={17} style={{ color: t.color || 'var(--green)' }} />
          {t.msg}
        </div>
      ))}
    </div>
  );
}

/* ---------- Tabs ---------- */
function Tabs({ tabs, active, onChange }) {
  return (
    <div className="tabs">
      {tabs.map(t => {
        const val = typeof t === 'string' ? t : t.value;
        const lbl = typeof t === 'string' ? t : t.label;
        return <button key={val} className={'tab ' + (active === val ? 'active' : '')} onClick={() => onChange(val)}>{lbl}</button>;
      })}
    </div>
  );
}

/* ---------- Field ---------- */
function Field({ label, hint, children }) {
  return (
    <div className="field">
      {label && <label className="label">{label}</label>}
      {children}
      {hint && <div className="hint">{hint}</div>}
    </div>
  );
}

Object.assign(window, {
  AppCtx, useApp, Button, BrandLogo, Placeholder, Score, StatusPill, Badge,
  Checkbox, Toggle, Seg, Empty, Drawer, Modal, ToastRegion, Tabs, Field,
});
