/* UI primitives — exported to window for cross-file use */

// ---- Icon (lucide) ----
function Icon({ name, size = 20, sw = 2, className = '', style }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const host = ref.current;
    if (!host || !window.lucide) return;
    const node = window.lucide.icons?.[name];
    let svg;
    if (node && window.lucide.createElement) {
      svg = window.lucide.createElement(node);
    }
    if (!svg) { // fallback
      host.innerHTML = `<i data-lucide="${name.replace(/([a-z])([A-Z])/g,'$1-$2').toLowerCase()}"></i>`;
      window.lucide.createIcons({ nameAttr: 'data-lucide' });
      svg = host.querySelector('svg');
      if (!svg) return;
    } else {
      host.replaceChildren(svg);
    }
    svg.setAttribute('width', size);
    svg.setAttribute('height', size);
    svg.setAttribute('stroke-width', sw);
  }, [name, size, sw]);
  return <span ref={ref} className={'lucide-wrap ' + className} style={{ display: 'inline-flex', lineHeight: 0, ...style }} />;
}

// ---- Status badge ----
function StatusBadge({ status, size = 'sm' }) {
  const s = CK.STATUS[status]; if (!s) return null;
  const pad = size === 'sm' ? 'text-[11px] px-2 py-0.5' : 'text-xs px-2.5 py-1';
  return (
    <span className={`inline-flex items-center gap-1.5 rounded-full ring-1 font-normal whitespace-nowrap ${pad} ${s.cls}`}>
      <span className="w-1.5 h-1.5 rounded-full" style={{ background: s.dot }} />
      {s.th}
    </span>
  );
}

function DayStatusBadge({ status, size='sm' }) {
  const s = CK.DAYSTATUS[status]; if (!s) return null;
  const pad = size === 'sm' ? 'text-[11px] px-2 py-0.5' : 'text-xs px-2.5 py-1';
  return <span className={`inline-flex items-center rounded-full ring-1 font-normal whitespace-nowrap ${pad} ${s.cls}`}>{s.th}</span>;
}

// ---- Buttons ----
function Btn({ children, variant = 'primary', size = 'md', icon, iconRight, className = '', ...rest }) {
  const sizes = { sm:'text-xs px-3 py-1.5 gap-1.5', md:'text-sm px-4 py-2.5 gap-2', lg:'text-base px-5 py-3 gap-2', xl:'text-base px-6 py-4 gap-2.5' };
  const variants = {
    primary:   'bg-brand-600 hover:bg-brand-700 text-white shadow-sm',
    dark:      'bg-slate-900 hover:bg-slate-800 text-white',
    outline:   'bg-white hover:bg-slate-50 text-slate-700 ring-1 ring-slate-300',
    ghost:     'hover:bg-slate-100 text-slate-600',
    softred:   'bg-brand-50 hover:bg-brand-100 text-brand-700 ring-1 ring-brand-200',
    danger:    'bg-white hover:bg-brand-50 text-brand-700 ring-1 ring-brand-200',
  };
  return (
    <button {...rest} className={`inline-flex items-center justify-center rounded-xl font-normal transition-colors active:scale-[.98] disabled:opacity-50 disabled:pointer-events-none ${sizes[size]} ${variants[variant]} ${className}`}>
      {icon && <Icon name={icon} size={size==='sm'?15:18} sw={2} />}
      {children}
      {iconRight && <Icon name={iconRight} size={size==='sm'?15:18} sw={2} />}
    </button>
  );
}

// ---- Card ----
function Card({ children, className = '', as: As = 'div', ...rest }) {
  return <As {...rest} className={`bg-white rounded-2xl ring-1 ring-slate-200 shadow-card ${className}`}>{children}</As>;
}

// ---- Section title ----
function SectionTitle({ icon, children, hint }) {
  return (
    <div className="flex items-center gap-2 mb-3">
      {icon && <span className="grid place-items-center w-7 h-7 rounded-lg bg-brand-50 text-brand-600"><Icon name={icon} size={16} /></span>}
      <h3 className="text-[15px] font-medium text-slate-800">{children}</h3>
      {hint && <span className="text-xs text-slate-400 font-light">{hint}</span>}
    </div>
  );
}

// ---- Form fields ----
function Field({ label, required, hint, children }) {
  return (
    <label className="block">
      <div className="flex items-center gap-1 mb-1.5">
        <span className="text-[13px] font-normal text-slate-600">{label}</span>
        {required && <span className="text-brand-600">*</span>}
        {hint && <span className="text-[11px] text-slate-400 font-light ml-1">{hint}</span>}
      </div>
      {children}
    </label>
  );
}
const inputCls = 'w-full rounded-xl ring-1 ring-slate-300 bg-white px-3.5 py-2.5 text-[15px] font-light text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-brand-500';
function TextInput(props){ return <input {...props} className={inputCls + ' ' + (props.className||'')} />; }
function TextArea(props){ return <textarea {...props} className={inputCls + ' resize-none ' + (props.className||'')} />; }
function Select({ children, ...props }){
  return (
    <div className="relative">
      <select {...props} className={inputCls + ' appearance-none pr-9 ' + (props.className||'')}>{children}</select>
      <span className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-slate-400"><Icon name="ChevronDown" size={16} /></span>
    </div>
  );
}

// ---- Chip selector (single/multi) ----
function ChipGroup({ options, value, onChange, multi, getKey = o=>o.id, getLabel = o=>o.th, getIcon }) {
  const isActive = (k) => multi ? (value||[]).includes(k) : value === k;
  function toggle(k){
    if (multi){ const set = new Set(value||[]); set.has(k)?set.delete(k):set.add(k); onChange([...set]); }
    else onChange(k);
  }
  return (
    <div className="flex flex-wrap gap-2">
      {options.map(o => { const k = getKey(o); const a = isActive(k);
        return (
          <button key={k} type="button" onClick={()=>toggle(k)}
            className={`inline-flex items-center gap-1.5 rounded-xl px-3 py-2 text-[13px] font-normal ring-1 transition-colors ${a ? 'bg-brand-600 text-white ring-brand-600' : 'bg-white text-slate-600 ring-slate-300 hover:bg-slate-50'}`}>
            {getIcon && <Icon name={getIcon(o)} size={15} sw={2} />}
            {getLabel(o)}
          </button>
        );
      })}
    </div>
  );
}

// ---- Stat card ----
function StatCard({ icon, label, value, sub, tone='slate', onClick }) {
  const tones = {
    slate:'text-slate-500 bg-slate-100', red:'text-brand-600 bg-brand-50', amber:'text-amber-600 bg-amber-50',
    green:'text-green-600 bg-green-50', blue:'text-blue-600 bg-blue-50', violet:'text-violet-600 bg-violet-50',
  };
  return (
    <Card as={onClick?'button':'div'} onClick={onClick} className={`p-4 text-left flex flex-col gap-2 ${onClick?'hover:ring-brand-300 transition':''}`}>
      <div className="flex items-center justify-between">
        <span className={`grid place-items-center w-9 h-9 rounded-xl ${tones[tone]}`}><Icon name={icon} size={18} /></span>
        {sub && <span className="text-[11px] font-light text-slate-400">{sub}</span>}
      </div>
      <div>
        <div className="text-[26px] leading-none font-medium text-slate-800 tnum">{value}</div>
        <div className="text-[12px] font-light text-slate-500 mt-1.5">{label}</div>
      </div>
    </Card>
  );
}

// ---- Avatar ----
function Avatar({ name, color='#dc2626', size=32 }) {
  const initials = (name||'?').trim().split(' ').slice(0,1)[0].slice(0,2);
  return <span className="grid place-items-center rounded-full text-white font-normal shrink-0" style={{ width:size, height:size, background:color, fontSize:size*0.4 }}>{initials}</span>;
}

// ---- Modal / Sheet ----
function Modal({ open, onClose, children, title, maxW='max-w-lg' }) {
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-[60] flex items-end sm:items-center justify-center p-0 sm:p-4">
      <div className="absolute inset-0 bg-slate-900/40 backdrop-blur-[1px]" onClick={onClose} />
      <div className={`relative bg-white w-full ${maxW} rounded-t-3xl sm:rounded-2xl shadow-pop max-h-[92dvh] flex flex-col`}>
        {title && (
          <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100 shrink-0">
            <h3 className="text-[15px] font-medium text-slate-800">{title}</h3>
            <button onClick={onClose} className="text-slate-400 hover:text-slate-700"><Icon name="X" size={20} /></button>
          </div>
        )}
        <div className="overflow-auto">{children}</div>
      </div>
    </div>
  );
}

// ---- Empty state ----
function Empty({ icon='Inbox', title, sub }) {
  return (
    <div className="flex flex-col items-center justify-center py-16 text-center">
      <span className="grid place-items-center w-14 h-14 rounded-2xl bg-slate-100 text-slate-300 mb-3"><Icon name={icon} size={28} /></span>
      <div className="text-slate-500 font-normal">{title}</div>
      {sub && <div className="text-xs text-slate-400 font-light mt-1">{sub}</div>}
    </div>
  );
}

// ---- Image placeholder slot ----
function PhotoSlot({ label, filled, onClick, h=96 }) {
  return (
    <button type="button" onClick={onClick}
      className="relative w-full rounded-xl ring-1 ring-dashed ring-slate-300 bg-slate-50 hover:bg-slate-100 hover:ring-brand-300 transition flex flex-col items-center justify-center gap-1 text-slate-400 overflow-hidden"
      style={{ height:h }}>
      {filled ? (
        <div className="absolute inset-0" style={{ background:'repeating-linear-gradient(45deg,#e2e8f0,#e2e8f0 8px,#eef2f6 8px,#eef2f6 16px)' }}>
          <div className="absolute inset-0 grid place-items-center text-slate-400"><Icon name="Image" size={22} /></div>
          <span className="absolute top-1.5 right-1.5 grid place-items-center w-5 h-5 rounded-full bg-green-500 text-white"><Icon name="Check" size={12} /></span>
        </div>
      ) : (<><Icon name="ImagePlus" size={20} /><span className="text-[11px] font-light">{label}</span></>)}
    </button>
  );
}

Object.assign(window, {
  Icon, StatusBadge, DayStatusBadge, Btn, Card, SectionTitle, Field, TextInput, TextArea,
  Select, ChipGroup, StatCard, Avatar, Modal, Empty, PhotoSlot, inputCls,
});
