// ============ ICONS ============
const Icon = {
  Dashboard: (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="3" width="7" height="9"/><rect x="14" y="3" width="7" height="5"/><rect x="14" y="12" width="7" height="9"/><rect x="3" y="16" width="7" height="5"/></svg>,
  Income:    (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 1v22"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>,
  Expense:   (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 6h18l-2 13H5z"/><path d="M16 10a4 4 0 0 1-8 0"/></svg>,
  Salary:    (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="2" y="6" width="20" height="12" rx="2"/><circle cx="12" cy="12" r="3"/><path d="M6 12h.01M18 12h.01"/></svg>,
  Reports:   (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 3v18h18"/><path d="M7 14l4-4 4 4 5-6"/></svg>,
  Stock:     (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M20 7L12 3 4 7v10l8 4 8-4V7z"/><path d="M12 11L4 7m8 4l8-4m-8 4v10"/></svg>,
  Phone:     (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="5" y="2" width="14" height="20" rx="2"/><path d="M12 18h.01"/></svg>,
  Plus:      (p) => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 5v14M5 12h14"/></svg>,
  Search:    (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>,
  Bell:      (p) => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/></svg>,
  Filter:    (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M22 3H2l8 9.5V19l4 2v-8.5L22 3z"/></svg>,
  Download:  (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="M7 10l5 5 5-5M12 15V3"/></svg>,
  Trend:     (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg>,
  Wrench:    (p) => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>,
  Box:       (p) => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/></svg>,
  Coin:      (p) => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5v14a9 3 0 0 0 18 0V5"/><path d="M3 12a9 3 0 0 0 18 0"/></svg>,
  Card:      (p) => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="2" y="5" width="20" height="14" rx="2"/><path d="M2 10h20"/></svg>,
  Close:     (p) => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M18 6L6 18M6 6l12 12"/></svg>,
  Alert:     (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>,
  Trash:     (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>,
  Check:     (p) => <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" {...p}><polyline points="20 6 9 17 4 12"/></svg>,
  Menu:      (p) => <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>,
};

// ============ HOOKS ============
function useCountUp(target, duration = 900) {
  const [val, setVal] = React.useState(0);
  React.useEffect(() => {
    let raf, start;
    const from = 0;
    const step = (t) => {
      if (!start) start = t;
      const p = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(from + (target - from) * eased);
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [target]);
  return val;
}

function formatBaht(n, decimals = 0) {
  return '₭' + Math.round(n).toLocaleString('en-US', { maximumFractionDigits: decimals, minimumFractionDigits: decimals });
}
function formatNumber(n) {
  return Math.round(n).toLocaleString('en-US');
}

// ============ SIDEBAR ============
function Sidebar({ active, onChange, open, onClose }) {
  const items = [
    { key: 'dashboard', label: 'ໜ້າຫຼັກ', icon: <Icon.Dashboard className="icon"/> },
    { key: 'income',    label: 'ລາຍຮັບ / ວຽກສ້ອມ', icon: <Icon.Income className="icon"/> },
    { key: 'expense',   label: 'ລາຍຈ່າຍ', icon: <Icon.Expense className="icon"/> },
    { key: 'salary',    label: 'ເງິນເດືອນພະນັກງານ', icon: <Icon.Salary className="icon"/> },
    { key: 'reports',   label: 'ລາຍງານ / ວິເຄາະ', icon: <Icon.Reports className="icon"/> },
    { key: 'stock',     label: 'ສະຕັອກອາໄຫຼ່', icon: <Icon.Stock className="icon"/> },
  ];
  const handlePick = (key) => {
    onChange(key);
    if (onClose) onClose();
  };
  return (
    <React.Fragment>
      <aside className={`sidebar ${open ? 'open' : ''}`}>
        <button className="sidebar-close" type="button" aria-label="ປິດເມນູ" onClick={onClose}><Icon.Close/></button>
        <div className="brand">
          <img className="brand-logo-img" src="logo.png" alt="PAENG DEE logo"/>
          <div className="brand-title">
            <b>PAENG DEE</b>
            <span>Shop · Salary</span>
          </div>
        </div>
        <div className="nav-label">ເມນູຫຼັກ</div>
        {items.map(it => (
          <div key={it.key}
            className={`nav-item ${active === it.key ? 'active' : ''}`}
            onClick={() => handlePick(it.key)}>
            {it.icon}<span>{it.label}</span>
          </div>
        ))}
        <div className="sidebar-footer">
          <div className="avatar">PD</div>
          <div className="user-meta">
            <b>ທ້າວແພງດີ</b>
            <span>ເຈົ້າຂອງຮ້ານ</span>
          </div>
        </div>
      </aside>
      {open && <div className="sidebar-backdrop open" onClick={onClose}/>}
    </React.Fragment>
  );
}

// ============ TOPBAR ============
function Topbar({ title, subtitle, actions, onMenuClick }) {
  return (
    <div className="topbar">
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
        {onMenuClick && (
          <button className="menu-btn" type="button" aria-label="ເປີດເມນູ" onClick={onMenuClick}>
            <Icon.Menu/>
          </button>
        )}
        <div style={{ minWidth: 0 }}>
          <h1>{title}</h1>
          <div className="sub">{subtitle}</div>
        </div>
      </div>
      <div className="topbar-actions">
        <div className="search">
          <Icon.Search />
          <input placeholder="ຄົ້ນຫາ ໃບງານ / ລູກຄ້າ / ອາໄຫຼ່..." />
        </div>
        <button className="btn btn-icon" title="ແຈ້ງເຕືອນ"><Icon.Bell /></button>
        {actions}
      </div>
    </div>
  );
}

// ============ STAT CARD ============
function StatCard({ label, value, suffix, prefix, icon, color, trend, isCurrency }) {
  const animated = useCountUp(value);
  const display = isCurrency ? formatBaht(animated) : formatNumber(animated);
  return (
    <div className={`stat ${color}`}>
      <div className="stat-h">
        <div className="stat-label">{label}</div>
        <div className="stat-icon">{icon}</div>
      </div>
      <div className="stat-val">{prefix}{display}{suffix}</div>
      {trend && (
        <div className={`stat-trend ${trend.dir === 'down' ? 'down' : ''}`}>
          <Icon.Trend style={{ transform: trend.dir === 'down' ? 'scaleY(-1)' : 'none' }}/>
          <b>{trend.value}</b>
          <span>{trend.label}</span>
        </div>
      )}
    </div>
  );
}

// ============ CHART: AREA / BARS ============
function RevenueChart({ data, height = 240 }) {
  const [hover, setHover] = React.useState(null);
  const W = 100; // %
  const H = height;
  const padY = 30;
  const max = Math.max(...data.map(d => Math.max(d.rev, d.exp))) * 1.15;
  const barW = 80 / data.length / 2.4;
  const pts = (key) => data.map((d, i) => {
    const x = ((i + 0.5) / data.length) * W;
    const y = padY + (1 - d[key] / max) * (H - padY * 1.5);
    return [x, y];
  });
  const revPts = pts('rev');
  const expPts = pts('exp');
  const toPath = (ps) => ps.map((p, i) => `${i ? 'L' : 'M'} ${p[0]} ${p[1]}`).join(' ');
  const toArea = (ps) => `${toPath(ps)} L ${ps[ps.length-1][0]} ${H-10} L ${ps[0][0]} ${H-10} Z`;

  return (
    <div style={{ position: 'relative', width: '100%', height: H }}>
      <svg viewBox={`0 0 100 ${H}`} preserveAspectRatio="none" style={{ width: '100%', height: H, overflow: 'visible' }}>
        <defs>
          <linearGradient id="gRev" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="#7c3aed" stopOpacity="0.45"/>
            <stop offset="100%" stopColor="#7c3aed" stopOpacity="0"/>
          </linearGradient>
          <linearGradient id="gExp" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="#06b6d4" stopOpacity="0.30"/>
            <stop offset="100%" stopColor="#06b6d4" stopOpacity="0"/>
          </linearGradient>
        </defs>
        {/* grid */}
        {[0.25, 0.5, 0.75].map(g => (
          <line key={g} x1="0" x2="100" y1={padY + g * (H - padY * 1.5)} y2={padY + g * (H - padY * 1.5)}
            stroke="rgba(255,255,255,0.04)" strokeWidth="0.3" vectorEffect="non-scaling-stroke"/>
        ))}
        {/* areas */}
        <path d={toArea(revPts)} fill="url(#gRev)" />
        <path d={toArea(expPts)} fill="url(#gExp)" />
        {/* lines */}
        <path d={toPath(revPts)} stroke="#a855f7" strokeWidth="2" fill="none" vectorEffect="non-scaling-stroke"/>
        <path d={toPath(expPts)} stroke="#22d3ee" strokeWidth="2" fill="none" strokeDasharray="3 3" vectorEffect="non-scaling-stroke"/>
        {/* dots */}
        {revPts.map((p, i) => (
          <circle key={i} cx={p[0]} cy={p[1]} r={hover === i ? 3 : 1.6} fill="#a855f7"
            stroke="#0a0e1a" strokeWidth="0.6" vectorEffect="non-scaling-stroke"
            onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}
            style={{ cursor: 'pointer', transition: 'r 0.15s' }}/>
        ))}
        {/* invisible hit areas */}
        {data.map((d, i) => (
          <rect key={i} x={(i / data.length) * 100} y="0" width={100 / data.length} height={H} fill="transparent"
            onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}/>
        ))}
      </svg>
      {/* x labels */}
      <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 10.5, color: 'var(--ink-3)' }}>
        {data.map((d, i) => <span key={i} style={{ width: `${100/data.length}%`, textAlign: 'center' }}>{d.d}</span>)}
      </div>
      {hover !== null && (
        <div className="bar-tip" style={{ left: `${((hover+0.5)/data.length)*100}%`, top: revPts[hover][1] }}>
          <div>ວັນທີ {data[hover].d} ພ.ສ.</div>
          <div>ລາຍຮັບ: <b style={{color:'#a78bfa'}}>{formatBaht(data[hover].rev)}</b></div>
          <div>ລາຍຈ່າຍ: <b>{formatBaht(data[hover].exp)}</b></div>
        </div>
      )}
    </div>
  );
}

// ============ RING CHART ============
function Ring({ percent, size = 140, color = 'url(#ringGrad)' }) {
  const r = (size - 18) / 2;
  const c = 2 * Math.PI * r;
  const [anim, setAnim] = React.useState(0);
  React.useEffect(() => {
    requestAnimationFrame(() => setAnim(percent));
  }, [percent]);
  return (
    <div className="ring" style={{ width: size, height: size }}>
      <svg width={size} height={size}>
        <defs>
          <linearGradient id="ringGrad" x1="0" x2="1" y1="0" y2="1">
            <stop offset="0%" stopColor="#7c3aed"/>
            <stop offset="100%" stopColor="#06b6d4"/>
          </linearGradient>
        </defs>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="10"/>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color} strokeWidth="10"
          strokeDasharray={c} strokeDashoffset={c - (anim/100)*c}
          strokeLinecap="round"
          style={{ transition: 'stroke-dashoffset 1s cubic-bezier(0.16,1,0.3,1)' }}/>
      </svg>
    </div>
  );
}

// ============ DONUT ============
function Donut({ data, size = 160 }) {
  const total = data.reduce((s, d) => s + d.value, 0);
  const r = (size - 24) / 2;
  const c = 2 * Math.PI * r;
  let acc = 0;
  const [anim, setAnim] = React.useState(false);
  React.useEffect(() => { requestAnimationFrame(() => setAnim(true)); }, []);
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ overflow: 'visible' }}>
      <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="rgba(255,255,255,0.04)" strokeWidth="14"/>
      {data.map((d, i) => {
        const len = (d.value / total) * c;
        const off = anim ? (acc / total) * c : 0;
        const dash = anim ? `${len} ${c - len}` : `0 ${c}`;
        const el = (
          <circle key={i} cx={size/2} cy={size/2} r={r}
            fill="none" stroke={d.color} strokeWidth="14"
            strokeDasharray={dash}
            strokeDashoffset={-off}
            transform={`rotate(-90 ${size/2} ${size/2})`}
            style={{ transition: `stroke-dasharray 0.9s cubic-bezier(0.16,1,0.3,1) ${i*0.08}s` }}/>
        );
        acc += d.value;
        return el;
      })}
    </svg>
  );
}

// ============ MODAL SHELL ============
function Modal({ title, subtitle, onClose, children, footer }) {
  React.useEffect(() => {
    const k = (e) => e.key === 'Escape' && onClose();
    window.addEventListener('keydown', k);
    return () => window.removeEventListener('keydown', k);
  }, [onClose]);
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <h2>{title}</h2>
            <div className="modal-sub">{subtitle}</div>
          </div>
          <button className="btn btn-icon btn-ghost" onClick={onClose}><Icon.Close/></button>
        </div>
        {children}
        {footer && <div className="modal-actions">{footer}</div>}
      </div>
    </div>
  );
}

window.UI = { Icon, useCountUp, formatBaht, formatNumber, Sidebar, Topbar, StatCard, RevenueChart, Ring, Donut, Modal };
