/* ============================================================
   Shipstar — app components (build on ui.jsx)
   ============================================================ */
const { useState:useStateC, useEffect:useEffectC, useRef:useRefC } = React;

/* nav icon set (extends the base Icon set) */
const NAV_ICONS = {
  home:'M3 11l9-7 9 7M5 10v10h5v-6h4v6h5V10',
  inbound:'M3 8l9-5 9 5v8l-9 5-9-5zM3 8l9 5 9-5M12 13v8',
  inventory:'M4 7h16v13H4zM4 11h16M9 7V4h6v3',
  orders:'M6 4h9l3 3v13H6zM9 4v3h6M9 12h6M9 16h4',
  bolt:'M13 2L4 14h6l-1 8 9-12h-6z',
  flag:'M5 21V4M5 4h11l-2 4 2 4H5',
  map:'M9 4L3 6v14l6-2 6 2 6-2V4l-6 2-6-2zM9 4v14M15 6v14',
  inbox:'M3 13h5l1 3h6l1-3h5M3 13l3-8h12l3 8v6H3z',
  returns:'M9 14l-4-4 4-4M5 10h9a5 5 0 015 5v1',
  sellers:'M16 7a4 4 0 11-8 0 4 4 0 018 0zM3 21a7 7 0 0118 0',
  billing:'M3 7h18v12H3zM3 11h18M7 15h4',
  team:'M9 11a3.5 3.5 0 100-7 3.5 3.5 0 000 7zM2 21a7 7 0 0114 0M17 11a3 3 0 100-6M22 21a6 6 0 00-7-5.9',
  chart:'M4 20V10M10 20V4M16 20v-7M22 20H2',
  settings:'M12 15a3 3 0 100-6 3 3 0 000 6zM19.4 15a1.6 1.6 0 00.3 1.8l.1.1a2 2 0 11-2.8 2.8l-.1-.1a1.6 1.6 0 00-2.7 1.1V21a2 2 0 11-4 0v-.1A1.6 1.6 0 005.6 19a2 2 0 11-2.8-2.8l.1-.1A1.6 1.6 0 003 13.4 2 2 0 113 9.4h.1A1.6 1.6 0 005 6.6a2 2 0 112.8-2.8l.1.1a1.6 1.6 0 002.7-1.1V3a2 2 0 114 0v.1A1.6 1.6 0 0019 5.6a2 2 0 112.8 2.8l-.1.1a1.6 1.6 0 00-.3 1.8',
  trend:'M3 17l6-6 4 4 8-8M21 7v5M21 7h-5',
  dollar:'M12 2v20M17 6a4 4 0 00-4-3H11a3.5 3.5 0 000 7h2a3.5 3.5 0 010 7h-2a4 4 0 01-4-3',
  warehouse:'M3 21V8l9-4 9 4v13M3 21h18M7 21v-7h10v7',
};
function NavIcon({ name, size=18 }){
  const d = NAV_ICONS[name] || NAV_ICONS.home;
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
      strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" className="ni-ic" aria-hidden="true">
      {d.split('M').filter(Boolean).map((s,i)=><path key={i} d={'M'+s} />)}
    </svg>
  );
}

const LOGO_TONES = {
  brand:['var(--brand-soft)','var(--brand-deep)'], green:['var(--green-soft)','#0f6b40'],
  blue:['var(--blue-soft)','#1a40b0'], amber:['var(--amber-soft)','#9a5b16'], red:['var(--red-soft)','#a82a24'],
};
function SellerLogo({ tone='brand', text, size=26 }){
  const [bg,fg]=LOGO_TONES[tone]||LOGO_TONES.brand;
  return <span className="slogo" style={{background:bg,color:fg,width:size,height:size,fontSize:size*0.42}}>{text}</span>;
}

function Delta({ value, suffix='%', invert=false }){
  const up = value>0; const tone = value===0?'flat':((up&&!invert)||(!up&&invert)?'up':'down');
  const arrow = value===0?'→':(up?'↑':'↓');
  return <span className={'delta '+tone}>{arrow} {Math.abs(value)}{suffix}</span>;
}

/* Sparkline — static drawn line + soft area fill (capture-safe) */
function Sparkline({ data=[], tone='green', w=92, h=30 }){
  if(!data.length) return null;
  const min=Math.min(...data), max=Math.max(...data), range=(max-min)||1;
  const pts = data.map((v,i)=>[ (i/(data.length-1))*w, h-2-((v-min)/range)*(h-5) ]);
  const line = pts.map((p,i)=>(i?'L':'M')+p[0].toFixed(1)+' '+p[1].toFixed(1)).join(' ');
  const area = line+` L ${w} ${h} L 0 ${h} Z`;
  const col = tone==='red'?'var(--red)':tone==='blue'?'var(--blue)':tone==='amber'?'var(--amber)':'var(--green)';
  const id = 'sg'+Math.random().toString(36).slice(2,7);
  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} className="kpi-spark" aria-hidden="true">
      <defs><linearGradient id={id} x1="0" x2="0" y1="0" y2="1">
        <stop offset="0%" stopColor={col} stopOpacity="0.18" /><stop offset="100%" stopColor={col} stopOpacity="0" />
      </linearGradient></defs>
      <path d={area} fill={`url(#${id})`} />
      <path d={line} fill="none" stroke={col} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

/* KPI card with count-up */
function KPI({ label, value, prefix='', suffix='', decimals=0, delta, deltaInvert=false, spark, tone='green', onClick }){
  const shown = useCountUp(value, { prefix, suffix, decimals });
  return (
    <div className="kpi" onClick={onClick} role={onClick?'button':null}>
      <div className="kpi-lbl">{label}</div>
      <div className="kpi-val">{shown}</div>
      <div className="kpi-bottom">
        {delta!==undefined ? <Delta value={delta} invert={deltaInvert} /> : <span />}
        {spark && <Sparkline data={spark} tone={tone} />}
      </div>
    </div>
  );
}

/* Section card */
function Section({ title, sub, action, children, flush=false, style }){
  return (
    <div className="section" style={style}>
      {(title||action) &&
        <div className="section-head">
          <div>{title && <h3>{title}</h3>}{sub && <div className="sh-sub">{sub}</div>}</div>
          {action}
        </div>}
      <div className={'section-body'+(flush?' flush':'')}>{children}</div>
    </div>
  );
}

/* status pill helper using DATA.STATUSES */
function StatusPill({ kind, status }){
  const st = status==null ? '' : String(status);            // real rows can have null status
  const tone = (DATA.STATUSES[kind]||{})[st] || 'gray';
  const label = st ? st.replace(/_/g,' ').replace(/\b\w/g,c=>c.toUpperCase()) : '—';
  return <Pill tone={tone} dot>{label}</Pill>;
}

/* Generic data table */
function DataTable({ columns, rows, onRowClick }){
  return (
    <div className="tbl-wrap">
      <table className="dtbl">
        <thead><tr>{columns.map((c,i)=><th key={i} style={c.align==='right'?{textAlign:'right'}:null}>{c.header}</th>)}</tr></thead>
        <tbody>
          {(rows||[]).map((r,ri)=>(
            <tr key={ri} onClick={()=>onRowClick&&onRowClick(r)}>
              {columns.map((c,ci)=>(
                <td key={ci} className={[c.mono?'mono':'', c.align==='right'?'num':'', c.strong?'row-strong':''].join(' ')}>
                  {c.render? c.render(r) : r[c.key]}
                </td>))}
            </tr>))}
        </tbody>
      </table>
    </div>
  );
}

Object.assign(window, { NavIcon, NAV_ICONS, SellerLogo, Delta, Sparkline, KPI, Section, StatusPill, DataTable, LOGO_TONES });
