// ─── Design Tokens ───────────────────────────────────────────────
const T = {
  blue800:'#0D2D6B', blue600:'#1B4FA8', blue500:'#2E6BCC',
  blue50:'#EEF4FF', blue100:'#DAE8FB',
  red600:'#C8102E', red100:'#FDEAED',
  gold500:'#F5A623', gold100:'#FEF3D7',
  gray900:'#1A1A2E', gray700:'#3A4158', gray600:'#5A6478',
  gray400:'#9BA5B5', gray200:'#D0D7E3', gray100:'#E8ECF2', gray50:'#F4F6FA',
  success:'#2E8B57', successBg:'#E2F5EA',
  warning:'#E87722', warningBg:'#FEF0E0',
  error:'#D32F2F', errorBg:'#FDEAEA',
  white:'#FFFFFF',
};

// ─── Badge ────────────────────────────────────────────────────────
function Badge({ type='default', children }) {
  const map = {
    success:{bg:'#E2F5EA',color:'#2E8B57'},
    warning:{bg:'#FEF0E0',color:'#E87722'},
    error:{bg:'#FDEAEA',color:'#D32F2F'},
    info:{bg:'#EEF4FF',color:'#1B4FA8'},
    default:{bg:'#E8ECF2',color:'#5A6478'},
    gold:{bg:'#FEF3D7',color:'#B87800'},
  };
  const s = map[type]||map.default;
  return <span style={{display:'inline-block',padding:'2px 8px',borderRadius:2,background:s.bg,color:s.color,fontSize:12,fontWeight:500,whiteSpace:'nowrap'}}>{children}</span>;
}

// ─── Button ───────────────────────────────────────────────────────
function Btn({ variant='primary', size='md', onClick, children, disabled, style={} }) {
  const vars = {
    primary:{background:T.blue600,color:'white',border:'none'},
    danger:{background:T.red600,color:'white',border:'none'},
    ghost:{background:'white',color:T.blue600,border:`1px solid ${T.blue600}`},
    default:{background:'white',color:T.gray700,border:`1px solid ${T.gray200}`},
    text:{background:'transparent',color:T.blue600,border:'none'},
  };
  return (
    <button onClick={!disabled?onClick:undefined} style={{
      ...vars[variant||'primary'], cursor:disabled?'not-allowed':'pointer',
      borderRadius:4, fontFamily:'inherit', fontWeight:500,
      fontSize:size==='sm'?12:14, padding:size==='sm'?'3px 10px':'6px 16px',
      opacity:disabled?.5:1, display:'inline-flex', alignItems:'center', gap:4,
      transition:'all 150ms', ...style,
    }}>{children}</button>
  );
}

// ─── Input ────────────────────────────────────────────────────────
function Input({ value, onChange, placeholder, type='text', style={}, ...rest }) {
  return <input type={type} value={value} onChange={onChange} placeholder={placeholder}
    style={{border:`1px solid ${T.gray200}`,borderRadius:4,padding:'6px 10px',fontSize:14,outline:'none',width:'100%',background:'white',color:T.gray900,...style}} {...rest}/>;
}

// ─── Select ───────────────────────────────────────────────────────
function Select({ value, onChange, options, style={} }) {
  return (
    <select value={value} onChange={onChange} style={{border:`1px solid ${T.gray200}`,borderRadius:4,padding:'6px 10px',fontSize:14,background:'white',color:T.gray900,cursor:'pointer',...style}}>
      {options.map(o=><option key={o.value||o} value={o.value||o}>{o.label||o}</option>)}
    </select>
  );
}

// ─── FormRow ──────────────────────────────────────────────────────
function FormRow({ label, required, children, style={} }) {
  return (
    <div style={{display:'grid',gridTemplateColumns:'90px 1fr',gap:12,alignItems:'center',marginBottom:12,...style}}>
      <label style={{fontSize:13,color:T.gray600,textAlign:'right'}}>
        {required&&<span style={{color:T.red600}}>* </span>}{label}
      </label>
      <div>{children}</div>
    </div>
  );
}

// ─── Card ─────────────────────────────────────────────────────────
function Card({ title, extra, children, style={}, noPad=false }) {
  return (
    <div style={{background:'white',borderRadius:4,border:`1px solid ${T.gray200}`,boxShadow:'0 2px 8px rgba(0,0,0,.06)',...style}}>
      {title&&(
        <div style={{padding:'11px 16px',borderBottom:`1px solid ${T.gray100}`,display:'flex',alignItems:'center',justifyContent:'space-between',borderTop:`3px solid ${T.blue600}`,borderRadius:'4px 4px 0 0'}}>
          <span style={{fontSize:14,fontWeight:500,color:T.gray900}}>{title}</span>
          {extra&&<div style={{display:'flex',gap:8,alignItems:'center'}}>{extra}</div>}
        </div>
      )}
      <div style={{padding:noPad?0:16}}>{children}</div>
    </div>
  );
}

// ─── StatCard ─────────────────────────────────────────────────────
function StatCard({ label, value, unit='', color=T.blue600, sub, icon }) {
  return (
    <div style={{background:'white',borderRadius:4,border:`1px solid ${T.gray200}`,boxShadow:'0 2px 8px rgba(0,0,0,.06)',padding:16,borderTop:`3px solid ${color}`,display:'flex',flexDirection:'column',gap:8}}>
      <div style={{fontSize:13,color:T.gray600}}>{label}</div>
      <div style={{fontSize:30,fontWeight:700,color,lineHeight:1}}>
        {value}<span style={{fontSize:13,fontWeight:400,marginLeft:4,color:T.gray400}}>{unit}</span>
      </div>
      {sub&&<div style={{fontSize:12,color:T.gray400}}>{sub}</div>}
    </div>
  );
}

// ─── Table ────────────────────────────────────────────────────────
function Table({ columns, data, onRowClick, emptyText='暂无数据' }) {
  return (
    <div style={{overflowX:'auto'}}>
      <table style={{width:'100%',borderCollapse:'collapse',fontSize:14}}>
        <thead>
          <tr style={{background:'#EEF2F9'}}>
            {columns.map(col=>(
              <th key={col.key} style={{padding:'9px 12px',textAlign:col.align||'left',color:T.gray700,fontWeight:500,fontSize:13,borderBottom:`1px solid ${T.gray200}`,whiteSpace:'nowrap',width:col.width}}>{col.title}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {!data.length&&<tr><td colSpan={columns.length} style={{textAlign:'center',padding:36,color:T.gray400,fontSize:13}}>{emptyText}</td></tr>}
          {data.map((row,i)=>(
            <tr key={row.id||i} onClick={onRowClick?()=>onRowClick(row):undefined}
              style={{borderBottom:`1px solid ${T.gray100}`,cursor:onRowClick?'pointer':'default',background:'white',transition:'background 120ms'}}
              onMouseEnter={e=>{if(onRowClick)e.currentTarget.style.background=T.blue50;}}
              onMouseLeave={e=>e.currentTarget.style.background='white'}>
              {columns.map(col=>(
                <td key={col.key} style={{padding:'9px 12px',color:T.gray900,textAlign:col.align||'left'}}>
                  {col.render?col.render(row[col.key],row):(row[col.key]??'—')}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ─── Modal ────────────────────────────────────────────────────────
function Modal({ open, title, onClose, children, footer, width=540 }) {
  if (!open) return null;
  return (
    <div style={{position:'fixed',inset:0,background:'rgba(13,45,107,.5)',display:'flex',alignItems:'center',justifyContent:'center',zIndex:1000}}
      onClick={e=>e.target===e.currentTarget&&onClose()}>
      <div style={{background:'white',borderRadius:4,width,maxWidth:'90vw',boxShadow:'0 8px 32px rgba(0,0,0,.18)',maxHeight:'85vh',display:'flex',flexDirection:'column'}}>
        <div style={{padding:'12px 20px',borderBottom:`1px solid ${T.gray100}`,display:'flex',alignItems:'center',justifyContent:'space-between',borderTop:`3px solid ${T.blue600}`,borderRadius:'4px 4px 0 0'}}>
          <span style={{fontWeight:500,fontSize:15}}>{title}</span>
          <button onClick={onClose} style={{background:'none',border:'none',cursor:'pointer',fontSize:18,color:T.gray400,lineHeight:1,padding:'0 4px'}}>✕</button>
        </div>
        <div style={{padding:20,overflowY:'auto',flex:1}}>{children}</div>
        {footer&&<div style={{padding:'12px 20px',borderTop:`1px solid ${T.gray100}`,display:'flex',justifyContent:'flex-end',gap:8}}>{footer}</div>}
      </div>
    </div>
  );
}

// ─── PageHeader ───────────────────────────────────────────────────
function PageHeader({ title, crumb, extra }) {
  return (
    <div style={{marginBottom:16}}>
      {crumb&&<div style={{fontSize:12,color:T.gray400,marginBottom:3}}>{crumb}</div>}
      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between'}}>
        <h1 style={{fontSize:18,fontWeight:700,color:T.gray900,display:'flex',alignItems:'center',gap:8}}>
          <span style={{width:4,height:18,background:T.blue600,borderRadius:2,display:'inline-block'}}/>
          {title}
        </h1>
        {extra&&<div style={{display:'flex',gap:8}}>{extra}</div>}
      </div>
    </div>
  );
}

// ─── Pagination ───────────────────────────────────────────────────
function Pagination({ total, page, pageSize=10, onChange }) {
  const tp = Math.max(1,Math.ceil(total/pageSize));
  return (
    <div style={{display:'flex',alignItems:'center',justifyContent:'flex-end',gap:6,marginTop:12,fontSize:13}}>
      <span style={{color:T.gray400}}>共 {total} 条记录</span>
      {Array.from({length:Math.min(tp,5)},(_,i)=>i+1).map(p=>(
        <button key={p} onClick={()=>onChange(p)} style={{width:28,height:28,border:`1px solid ${p===page?T.blue600:T.gray200}`,borderRadius:4,background:p===page?T.blue600:'white',color:p===page?'white':T.gray700,cursor:'pointer',fontSize:13}}>{p}</button>
      ))}
    </div>
  );
}

// ─── SearchBar ────────────────────────────────────────────────────
function SearchBar({ children, onSearch, onReset }) {
  return (
    <div style={{background:'white',border:`1px solid ${T.gray200}`,borderRadius:4,padding:'12px 16px',marginBottom:12,display:'flex',flexWrap:'wrap',gap:10,alignItems:'center'}}>
      {children}
      <Btn size="sm" onClick={onSearch}>查询</Btn>
      <Btn size="sm" variant="default" onClick={onReset}>重置</Btn>
    </div>
  );
}

// ─── Tabs ─────────────────────────────────────────────────────────
function Tabs({ tabs, active, onChange }) {
  return (
    <div style={{display:'flex',borderBottom:`1px solid ${T.gray200}`,marginBottom:16}}>
      {tabs.map(t=>(
        <div key={t} onClick={()=>onChange(t)} style={{padding:'8px 20px',fontSize:14,cursor:'pointer',borderBottom:`2px solid ${active===t?T.blue600:'transparent'}`,color:active===t?T.blue600:T.gray600,fontWeight:active===t?500:400,transition:'all 150ms',marginBottom:-1}}>{t}</div>
      ))}
    </div>
  );
}

Object.assign(window, { T, Badge, Btn, Input, Select, FormRow, Card, StatCard, Table, Modal, PageHeader, Pagination, SearchBar, Tabs });
