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

// Lucide icon helper
function Icon({ name, size = 16, color, style, strokeWidth = 1.8 }) {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current || !window.lucide) return;
    ref.current.innerHTML = '';
    const icons = window.lucide.icons;
    // lucide bundle exposes PascalCase keys (e.g. "LayoutDashboard")
    const key = name.split('-').map(p => p[0].toUpperCase() + p.slice(1)).join('');
    const iconDef = icons[key] || icons[name];
    if (!iconDef) return;
    const svg = window.lucide.createElement(iconDef);
    svg.setAttribute('width', size);
    svg.setAttribute('height', size);
    svg.setAttribute('stroke-width', strokeWidth);
    if (color) svg.setAttribute('stroke', color);
    ref.current.appendChild(svg);
  }, [name, size, color, strokeWidth]);
  return <span ref={ref} style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', ...style }} />;
}

function Badge({ kind, children }) {
  return <span className={`badge ${kind}`}>{children}</span>;
}

function CategoryBadge({ cat }) {
  const map = {
    cold: 'سرد',
    warm: 'گرم',
    ready: 'آماده',
    sold: 'فروخته شده',
    unfit: 'نامناسب',
  };
  return <Badge kind={cat}>{map[cat] || cat}</Badge>;
}

function ProductTypeBadge({ type }) {
  const map = { online: ['آنلاین', 'online'], workshop: ['کارگاه', 'workshop'], free: ['رایگان', 'free'] };
  const [label, cls] = map[type] || [type, ''];
  return <Badge kind={cls}>{label}</Badge>;
}

function Toggle({ on, onChange, ariaLabel }) {
  return <button
    aria-label={ariaLabel || 'toggle'}
    className={`toggle ${on ? 'on' : ''}`}
    onClick={(e) => { e.stopPropagation(); onChange?.(!on); }} />;
}

function Button({ kind = 'ghost', size, icon, children, onClick, type = 'button', disabled, loading }) {
  return (
    <button type={type} disabled={disabled} onClick={onClick} className={`btn btn-${kind} ${size === 'sm' ? 'btn-sm' : ''}`}>
      {loading ? <span className="spinner" /> : (icon ? <Icon name={icon} size={size === 'sm' ? 13 : 15} /> : null)}
      {children}
    </button>
  );
}

// Toast system
const ToastCtx = createContext({ toast: () => {} });
function useToast() { return useContext(ToastCtx).toast; }
function ToastHost({ children }) {
  const [toasts, setToasts] = useState([]);
  const toast = (msg, kind = 'info') => {
    const id = Math.random().toString(36).slice(2);
    setToasts(t => [...t, { id, msg, kind }]);
    setTimeout(() => setToasts(t => t.filter(x => x.id !== id)), 3000);
  };
  const iconFor = { success: 'check', error: 'x', info: 'info' };
  return (
    <ToastCtx.Provider value={{ toast }}>
      {children}
      <div className="toast-zone">
        {toasts.map(t => (
          <div key={t.id} className={`toast ${t.kind}`}>
            <div className="toast-icon"><Icon name={iconFor[t.kind]} size={14} strokeWidth={2.4} /></div>
            <div style={{ flex: 1, fontSize: 13 }}>{t.msg}</div>
          </div>
        ))}
      </div>
    </ToastCtx.Provider>
  );
}

// Modal
function Modal({ open, title, onClose, children, footer, width = 540 }) {
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (e.key === 'Escape') onClose?.(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [open]);
  if (!open) return null;
  return (
    <div className="modal-shell" onClick={onClose}>
      <div className="modal" style={{ maxWidth: width }} onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div className="bold" style={{ fontSize: 15 }}>{title}</div>
          <button className="icon-btn" onClick={onClose} style={{ width: 30, height: 30 }}><Icon name="x" size={15} /></button>
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-foot">{footer}</div>}
      </div>
    </div>
  );
}

// Slide-over
function SlidePanel({ open, onClose, children, width = 540 }) {
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (e.key === 'Escape') onClose?.(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [open]);
  if (!open) return null;
  return (
    <>
      <div className="scrim" onClick={onClose} />
      <div className="slide-panel" style={{ width: `min(${width}px, 92vw)` }}>{children}</div>
    </>
  );
}

// Skeleton
function Skeleton({ w = '100%', h = 14, style }) {
  return <div className="skel" style={{ width: w, height: h, ...style }} />;
}

// Field
function Field({ label, children }) {
  return <div><label className="label">{label}</label>{children}</div>;
}

// Section header
function SectionH({ title, sub, right }) {
  return (
    <div className="section-h">
      <div>
        <h2>{title}</h2>
        {sub && <div className="h-sub mt-4">{sub}</div>}
      </div>
      {right}
    </div>
  );
}

// Empty state
function Empty({ icon = 'inbox', title, sub, action }) {
  return (
    <div className="empty">
      <div className="empty-icon"><Icon name={icon} size={28} /></div>
      <div className="bold" style={{ fontSize: 14, color: 'var(--text-2)' }}>{title}</div>
      {sub && <div className="text-xs" style={{ maxWidth: 320 }}>{sub}</div>}
      {action}
    </div>
  );
}

// Donut SVG
function Donut({ segments, size = 160, stroke = 22 }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  let acc = 0;
  const total = segments.reduce((s, x) => s + x.value, 0);
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform: 'rotate(-90deg)' }}>
      <circle cx={size/2} cy={size/2} r={r} fill="none" className="donut-bg" strokeWidth={stroke} />
      {segments.map((s, i) => {
        const len = (s.value / total) * c;
        const dash = `${len} ${c - len}`;
        const off = -acc;
        acc += len;
        return <circle key={i} cx={size/2} cy={size/2} r={r} fill="none"
          stroke={s.color} strokeWidth={stroke} strokeDasharray={dash} strokeDashoffset={off} strokeLinecap="butt" />;
      })}
    </svg>
  );
}

// Mini line chart
function LineChart({ data, width = 560, height = 200, color = '#6C63FF', color2 }) {
  const max = Math.max(...data) * 1.15;
  const min = 0;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * (width - 40) + 30;
    const y = height - 30 - ((v - min) / (max - min)) * (height - 60);
    return [x, y];
  });
  const path = pts.map((p, i) => (i === 0 ? `M ${p[0]} ${p[1]}` : `L ${p[0]} ${p[1]}`)).join(' ');
  const fillPath = `${path} L ${pts[pts.length-1][0]} ${height - 30} L ${pts[0][0]} ${height - 30} Z`;
  const gid = useMemo(() => 'g_' + Math.random().toString(36).slice(2), []);
  return (
    <svg width="100%" height={height} viewBox={`0 0 ${width} ${height}`}>
      <defs>
        <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.3" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      {/* gridlines */}
      {[0.25, 0.5, 0.75].map((t, i) => (
        <line key={i} x1={30} x2={width - 10} y1={30 + t * (height - 60)} y2={30 + t * (height - 60)} stroke="#2A2A4A" strokeOpacity="0.4" strokeDasharray="3 4" />
      ))}
      <path d={fillPath} fill={`url(#${gid})`} />
      <path d={path} fill="none" stroke={color} strokeWidth="2.4" strokeLinejoin="round" strokeLinecap="round" />
      {pts.map((p, i) => (
        <circle key={i} cx={p[0]} cy={p[1]} r="3.5" fill={color} stroke="#0F0F1A" strokeWidth="2" />
      ))}
      {/* x labels */}
      {['ش', 'ی', 'د', 'س', 'چ', 'پ', 'ج'].map((lbl, i) => {
        const x = (i / 6) * (width - 40) + 30;
        return <text key={i} x={x} y={height - 8} fill="#6B6B8C" fontSize="11" textAnchor="middle" fontFamily="Vazirmatn">{lbl}</text>;
      })}
    </svg>
  );
}

// Bar comparison
function BarH({ value, max, color = '#6C63FF', label, right }) {
  const pct = Math.min(100, (value / max) * 100);
  return (
    <div className="cmp-bar">
      <div className="row between">
        <span className="text-sm">{label}</span>
        <span className="text-sm mono" style={{ color: 'var(--text-2)' }}>{right}</span>
      </div>
      <div className="bar"><div style={{ width: pct + '%', height: '100%', background: color, borderRadius: 999 }} /></div>
    </div>
  );
}

window.SB_UI = { Icon, Badge, CategoryBadge, ProductTypeBadge, Toggle, Button, ToastHost, useToast, Modal, SlidePanel, Skeleton, Field, SectionH, Empty, Donut, LineChart, BarH };
