/* BLOCKS F — DATA-VIZ (area / bars / table) for Empire UI v2.
   Premium, well-spaced, style-agnostic. Chart colors ALWAYS from s.chart. */
(function(){
  const { cx, Slot, Spark, Bars, Ring, Glyph, G } = window;
  const head=(s,x='')=>cx(s.cls.display,s.cls.glow,x);
  const div='rgba(128,128,128,.18)';
  const UP='#22c55e', DN='#ef4444';

  function SmoothArea({colors,w=260,h=90,data}){
    const d=data||[12,18,15,26,22,33,28,40,36,48,44,58];
    const mx=Math.max(...d),mn=Math.min(...d);
    const X=i=>i/(d.length-1)*w,Y=v=>h-((v-mn)/((mx-mn)||1))*(h-10)-5;
    let p=`M${X(0)},${Y(d[0])}`;
    for(let i=1;i<d.length;i++){const x0=X(i-1),y0=Y(d[i-1]),x1=X(i),y1=Y(d[i]),cx=(x0+x1)/2;p+=` C${cx},${y0} ${cx},${y1} ${x1},${y1}`;}
    const id='g'+Math.random().toString(36).slice(2,7);
    return(<svg width="100%" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{display:'block'}}><defs><linearGradient id={id} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor={colors[0]} stopOpacity=".45"/><stop offset="1" stopColor={colors[0]} stopOpacity="0"/></linearGradient></defs><path d={`${p} L${w},${h} L0,${h} Z`} fill={`url(#${id})`}/><path d={p} fill="none" stroke={colors[0]} strokeWidth="2.4" strokeLinecap="round"/></svg>);
  }

  const blocks = [

    /* ===================== AREA (2) ===================== */
    { id:'fD-area-single', type:'data', subtype:'area', title:'Smooth area card', w:1,
      Render:(s)=>(
        <div className={cx(s.cls.surface,'w-full max-w-[300px] p-5')}>
          <div className={cx('text-xs font-semibold uppercase tracking-wider',s.cls.muted)}>Monthly revenue</div>
          <div className="flex items-end gap-2 mt-1.5">
            <div className={head(s,'text-2xl font-extrabold')}>$52,840</div>
            <span className="text-[11px] font-bold mb-1 inline-flex items-center gap-0.5" style={{color:UP}}><Glyph d="M12 19V5M5 12l7-7 7 7" size={12}/>14.2%</span>
          </div>
          <div className="mt-4"><SmoothArea colors={[s.chart[0]]} h={92} data={[18,24,21,30,27,38,34,46,42,55,50,64]}/></div>
          <div className={cx('flex justify-between text-[10px] mt-2',s.cls.muted)}><span>Jan</span><span>Apr</span><span>Jul</span><span>Oct</span></div>
        </div>) },

    { id:'fD-area-multi', type:'data', subtype:'area', title:'Smooth multi-series area', w:2,
      Render:(s)=>(
        <div className={cx(s.cls.surface,'w-full max-w-[540px] p-5')}>
          <div className="flex items-center justify-between mb-3">
            <div>
              <div className={head(s,'font-extrabold')}>Engagement overview</div>
              <div className={cx('text-xs mt-0.5',s.cls.muted)}>Sessions vs. conversions · 12 weeks</div>
            </div>
            <span className="text-[11px] font-bold inline-flex items-center gap-0.5" style={{color:UP}}><Glyph d="M12 19V5M5 12l7-7 7 7" size={12}/>9.8%</span>
          </div>
          <div className="relative h-44">
            <div className="absolute inset-0"><SmoothArea colors={[s.chart[0]]} w={520} h={176} data={[40,48,44,58,62,59,72,68,82,86,94,104]}/></div>
            <div className="absolute inset-0"><SmoothArea colors={[s.chart[1]||s.chart[0]]} w={520} h={176} data={[18,22,20,28,26,34,31,40,38,46,50,58]}/></div>
          </div>
          <div className="flex gap-6 mt-3 text-[11px]">
            <span className="inline-flex items-center gap-2"><span className="w-3 h-3 rounded-full" style={{background:s.chart[0]}}/><span className={s.cls.sub}>Sessions</span></span>
            <span className="inline-flex items-center gap-2"><span className="w-3 h-3 rounded-full" style={{background:s.chart[1]||s.chart[0]}}/><span className={s.cls.sub}>Conversions</span></span>
          </div>
        </div>) },

    /* ===================== BARS (4) ===================== */
    { id:'fD-bars-vertical', type:'data', subtype:'bars', title:'Vertical bars + axis', w:1,
      Render:(s)=>{
        const data=[42,58,36,72,54,88,66];const labels=['M','T','W','T','F','S','S'];const mx=Math.max(...data);
        return(
        <div className={cx(s.cls.surface,'w-full max-w-[300px] p-5')}>
          <div className={cx('text-xs font-semibold uppercase tracking-wider',s.cls.muted)}>Weekly orders</div>
          <div className={head(s,'text-2xl font-extrabold mt-1')}>3,418</div>
          <div className="flex items-end gap-2.5 h-32 mt-4" style={{borderBottom:`1px solid ${div}`}}>
            {data.map((v,i)=>(
              <div key={i} className="flex-1 rounded-t-md transition-all" style={{height:`${v/mx*100}%`,background:s.chart[0],opacity:i===5?1:.55}}/>
            ))}
          </div>
          <div className={cx('flex gap-2.5 mt-2',s.cls.muted)}>
            {labels.map((l,i)=>(<div key={i} className="flex-1 text-center text-[10px]">{l}</div>))}
          </div>
        </div>); } },

    { id:'fD-bars-horizontal', type:'data', subtype:'bars', title:'Horizontal bars + labels', w:1,
      Render:(s)=>{
        const rows=[['Direct',86],['Organic',64],['Referral',48],['Social',31],['Email',22]];
        return(
        <div className={cx(s.cls.surface,'w-full max-w-[300px] p-5')}>
          <div className={head(s,'font-extrabold')}>Traffic sources</div>
          <div className={cx('text-xs mb-4',s.cls.muted)}>Share of visits</div>
          <div className="flex flex-col gap-3.5">
            {rows.map(([l,v],i)=>(
              <div key={i}>
                <div className="flex justify-between text-[12px] mb-1.5">
                  <span className={s.cls.sub}>{l}</span><span className={cx('font-semibold',s.cls.text)}>{v}%</span>
                </div>
                <div className="h-2 rounded-full overflow-hidden" style={{background:div}}>
                  <div className="h-full rounded-full" style={{width:`${v}%`,background:i%2?s.chart[1]||s.chart[0]:s.chart[0]}}/>
                </div>
              </div>
            ))}
          </div>
        </div>); } },

    { id:'fD-bars-grouped', type:'data', subtype:'bars', title:'Grouped bars (2 series)', w:2,
      Render:(s)=>{
        const groups=[['Q1',54,38],['Q2',68,46],['Q3',49,58],['Q4',82,64]];const mx=90;
        return(
        <div className={cx(s.cls.surface,'w-full max-w-[540px] p-5')}>
          <div className="flex items-center justify-between mb-4">
            <div>
              <div className={head(s,'font-extrabold')}>Plan vs. actual</div>
              <div className={cx('text-xs mt-0.5',s.cls.muted)}>Quarterly performance</div>
            </div>
            <div className="flex gap-5 text-[11px]">
              <span className="inline-flex items-center gap-2"><span className="w-3 h-3 rounded-sm" style={{background:s.chart[0]}}/><span className={s.cls.sub}>Plan</span></span>
              <span className="inline-flex items-center gap-2"><span className="w-3 h-3 rounded-sm" style={{background:s.chart[1]||s.chart[0]}}/><span className={s.cls.sub}>Actual</span></span>
            </div>
          </div>
          <div className="flex items-end justify-around gap-6 h-40" style={{borderBottom:`1px solid ${div}`}}>
            {groups.map(([l,a,b],i)=>(
              <div key={i} className="flex flex-col items-center gap-2 flex-1">
                <div className="flex items-end gap-1.5 w-full justify-center h-36">
                  <div className="w-1/3 max-w-[28px] rounded-t-md" style={{height:`${a/mx*100}%`,background:s.chart[0]}}/>
                  <div className="w-1/3 max-w-[28px] rounded-t-md" style={{height:`${b/mx*100}%`,background:s.chart[1]||s.chart[0]}}/>
                </div>
              </div>
            ))}
          </div>
          <div className="flex justify-around mt-2">
            {groups.map(([l],i)=>(<div key={i} className={cx('flex-1 text-center text-[11px]',s.cls.muted)}>{l}</div>))}
          </div>
        </div>); } },

    { id:'fD-bars-radial', type:'data', subtype:'bars', title:'Radial bars', w:1,
      Render:(s)=>{
        const rings=[['Move',82,s.chart[0],44],['Active',64,s.chart[1]||s.chart[0],34],['Goal',48,s.cls.accent,24]];
        const C=60,SW=8;
        const arc=(r,pct)=>{const len=2*Math.PI*r;return{dash:`${len*pct/100} ${len}`,r};};
        return(
        <div className={cx(s.cls.surface,'w-full max-w-[300px] p-5')}>
          <div className={head(s,'font-extrabold')}>Daily goals</div>
          <div className={cx('text-xs mb-3',s.cls.muted)}>Completion by activity</div>
          <div className="flex items-center gap-5">
            <svg width="124" height="124" viewBox="0 0 124 124">
              {rings.map(([l,v,c,r],i)=>{const a=arc(r,v);return(
                <g key={i} transform={`rotate(-90 ${C} ${C})`}>
                  <circle cx={C} cy={C} r={r} fill="none" stroke={c} strokeWidth={SW} strokeOpacity=".15"/>
                  <circle cx={C} cy={C} r={r} fill="none" stroke={c} strokeWidth={SW} strokeLinecap="round" strokeDasharray={a.dash}/>
                </g>);})}
            </svg>
            <div className="flex flex-col gap-2.5">
              {rings.map(([l,v,c],i)=>(
                <div key={i} className="flex items-center gap-2 text-[12px]">
                  <span className="w-2.5 h-2.5 rounded-full" style={{background:c}}/>
                  <span className={s.cls.sub}>{l}</span>
                  <span className={cx('font-bold ml-auto',s.cls.text)}>{v}%</span>
                </div>
              ))}
            </div>
          </div>
        </div>); } },

    /* ===================== TABLE (6) ===================== */
    { id:'fD-table-basic', type:'data', subtype:'table', title:'Basic table', w:2,
      Render:(s)=>{
        const rows=[['Aurora Pro','Active','$4,200'],['Nimbus Lite','Trial','$0'],['Helix Cloud','Active','$1,850'],['Vertex One','Paused','$960']];
        return(
        <div className={cx(s.cls.surface,'w-full max-w-[540px] p-5')}>
          <div className={head(s,'font-extrabold mb-4')}>Accounts</div>
          <table className="w-full text-[13px]">
            <thead><tr className={cx('text-left',s.cls.muted)} style={{borderBottom:`1px solid ${div}`}}>
              <th className="pb-2.5 font-semibold">Workspace</th><th className="pb-2.5 font-semibold">Status</th><th className="pb-2.5 font-semibold text-right">MRR</th>
            </tr></thead>
            <tbody>
              {rows.map((r,i)=>(
                <tr key={i} style={{borderBottom:i<rows.length-1?`1px solid ${div}`:'none'}}>
                  <td className={cx('py-3 font-medium',s.cls.text)}>{r[0]}</td>
                  <td className={cx('py-3',s.cls.sub)}>{r[1]}</td>
                  <td className={cx('py-3 text-right font-semibold',s.cls.text)}>{r[2]}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>); } },

    { id:'fD-table-sortable', type:'data', subtype:'table', title:'Sortable header', w:2,
      Render:(s)=>{
        const [sort,setSort]=React.useState({k:'mrr',dir:-1});
        const base=[['Aurora Pro',4200,98],['Nimbus Lite',1200,71],['Helix Cloud',1850,86],['Vertex One',960,64]];
        const cols=[['name','Workspace'],['mrr','MRR'],['score','Health']];
        const idx={name:0,mrr:1,score:2};
        const sorted=[...base].sort((a,b)=>(a[idx[sort.k]]>b[idx[sort.k]]?1:-1)*sort.dir);
        const click=k=>setSort(p=>({k,dir:p.k===k?-p.dir:-1}));
        return(
        <div className={cx(s.cls.surface,'w-full max-w-[540px] p-5')}>
          <div className={head(s,'font-extrabold mb-4')}>Customers</div>
          <table className="w-full text-[13px]">
            <thead><tr className={cx('text-left',s.cls.muted)} style={{borderBottom:`1px solid ${div}`}}>
              {cols.map(([k,l],i)=>(
                <th key={k} onClick={()=>click(k)} className={cx('pb-2.5 font-semibold cursor-pointer select-none',i>0&&'text-right')}>
                  <span className={cx('inline-flex items-center gap-1',sort.k===k&&s.cls.text)}>{l}
                    <Glyph d={sort.k===k?(sort.dir<0?'M6 14l6-6 6 6':'M6 10l6 6 6-6'):'M8 9l4-4 4 4M8 15l4 4 4-4'} size={12}/>
                  </span>
                </th>
              ))}
            </tr></thead>
            <tbody>
              {sorted.map((r,i)=>(
                <tr key={r[0]} style={{borderBottom:i<sorted.length-1?`1px solid ${div}`:'none'}}>
                  <td className={cx('py-3 font-medium',s.cls.text)}>{r[0]}</td>
                  <td className={cx('py-3 text-right',s.cls.sub)}>${r[1].toLocaleString()}</td>
                  <td className={cx('py-3 text-right font-semibold',s.cls.text)}>{r[2]}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>); } },

    { id:'fD-table-actions', type:'data', subtype:'table', title:'Table with row actions', w:2,
      Render:(s)=>{
        const rows=[['Sofia Reyes','Owner'],['Liam Chen','Editor'],['Ada Okoro','Viewer']];
        return(
        <div className={cx(s.cls.surface,'w-full max-w-[540px] p-5')}>
          <div className={head(s,'font-extrabold mb-4')}>Team members</div>
          <table className="w-full text-[13px]">
            <thead><tr className={cx('text-left',s.cls.muted)} style={{borderBottom:`1px solid ${div}`}}>
              <th className="pb-2.5 font-semibold">Member</th><th className="pb-2.5 font-semibold">Role</th><th className="pb-2.5"/>
            </tr></thead>
            <tbody>
              {rows.map((r,i)=>(
                <tr key={i} style={{borderBottom:i<rows.length-1?`1px solid ${div}`:'none'}}>
                  <td className={cx('py-3 font-medium',s.cls.text)}>{r[0]}</td>
                  <td className={cx('py-3',s.cls.sub)}>{r[1]}</td>
                  <td className="py-3 text-right">
                    <div className="inline-flex gap-1.5">
                      <button className={cx('w-8 h-8 rounded-lg inline-flex items-center justify-center',s.cls.surface2,s.cls.sub)}><Glyph d="M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" size={14}/></button>
                      <button className="w-8 h-8 rounded-lg inline-flex items-center justify-center" style={{color:DN,background:'rgba(239,68,68,.12)'}}><Glyph d="M3 6h18M8 6V4h8v2M6 6l1 14h10l1-14" size={14}/></button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>); } },

    { id:'fD-table-selectable', type:'data', subtype:'table', title:'Selectable rows', w:2,
      Render:(s)=>{
        const rows=[['#1042','Invoice paid','$320'],['#1043','Refund issued','$80'],['#1044','Invoice paid','$540'],['#1045','Pending','$210']];
        const [sel,setSel]=React.useState([0,2]);
        const toggle=i=>setSel(p=>p.includes(i)?p.filter(x=>x!==i):[...p,i]);
        const all=sel.length===rows.length;
        const Box=({on})=>(<span className="w-[18px] h-[18px] rounded-[5px] inline-flex items-center justify-center" style={{background:on?s.cls.accent:'transparent',border:on?'none':`1.5px solid ${div}`}}>{on&&<Glyph d="M5 12l4 4 10-10" size={12} className="text-white"/>}</span>);
        return(
        <div className={cx(s.cls.surface,'w-full max-w-[540px] p-5')}>
          <div className="flex items-center justify-between mb-4">
            <div className={head(s,'font-extrabold')}>Transactions</div>
            <span className={cx('text-[11px]',s.cls.muted)}>{sel.length} selected</span>
          </div>
          <table className="w-full text-[13px]">
            <thead><tr className={cx('text-left',s.cls.muted)} style={{borderBottom:`1px solid ${div}`}}>
              <th className="pb-2.5 w-8 cursor-pointer" onClick={()=>setSel(all?[]:rows.map((_,i)=>i))}><Box on={all}/></th>
              <th className="pb-2.5 font-semibold">Ref</th><th className="pb-2.5 font-semibold">Activity</th><th className="pb-2.5 font-semibold text-right">Amount</th>
            </tr></thead>
            <tbody>
              {rows.map((r,i)=>{const on=sel.includes(i);return(
                <tr key={i} onClick={()=>toggle(i)} className="cursor-pointer" style={{borderBottom:i<rows.length-1?`1px solid ${div}`:'none',background:on?'rgba(128,128,128,.06)':'transparent'}}>
                  <td className="py-3"><Box on={on}/></td>
                  <td className={cx('py-3 font-medium',s.cls.text)}>{r[0]}</td>
                  <td className={cx('py-3',s.cls.sub)}>{r[1]}</td>
                  <td className={cx('py-3 text-right font-semibold',s.cls.text)}>{r[2]}</td>
                </tr>);})}
            </tbody>
          </table>
        </div>); } },

    { id:'fD-table-expandable', type:'data', subtype:'table', title:'Expandable row', w:2,
      Render:(s)=>{
        const rows=[
          {ref:'ORD-7781',cust:'Sofia Reyes',total:'$420',items:'3 items · Express shipping · Paid via card'},
          {ref:'ORD-7782',cust:'Liam Chen',total:'$96',items:'1 item · Standard shipping · Paid via PayPal'},
          {ref:'ORD-7783',cust:'Ada Okoro',total:'$1,240',items:'8 items · Express shipping · Net-30 invoice'}];
        const [open,setOpen]=React.useState(0);
        return(
        <div className={cx(s.cls.surface,'w-full max-w-[540px] p-5')}>
          <div className={head(s,'font-extrabold mb-4')}>Orders</div>
          <table className="w-full text-[13px]">
            <thead><tr className={cx('text-left',s.cls.muted)} style={{borderBottom:`1px solid ${div}`}}>
              <th className="pb-2.5 w-6"/><th className="pb-2.5 font-semibold">Order</th><th className="pb-2.5 font-semibold">Customer</th><th className="pb-2.5 font-semibold text-right">Total</th>
            </tr></thead>
            <tbody>
              {rows.map((r,i)=>{const on=open===i;return(
                <React.Fragment key={i}>
                <tr onClick={()=>setOpen(on?-1:i)} className="cursor-pointer" style={{borderBottom:`1px solid ${div}`}}>
                  <td className="py-3"><Glyph d="M9 6l6 6-6 6" size={14} className={s.cls.muted} style={{transform:on?'rotate(90deg)':'none',transition:'transform .2s'}}/></td>
                  <td className={cx('py-3 font-medium',s.cls.text)}>{r.ref}</td>
                  <td className={cx('py-3',s.cls.sub)}>{r.cust}</td>
                  <td className={cx('py-3 text-right font-semibold',s.cls.text)}>{r.total}</td>
                </tr>
                {on&&(<tr style={{borderBottom:`1px solid ${div}`}}><td/><td colSpan={3} className={cx('pb-3.5 pt-0 text-[12px]',s.cls.sub)}>{r.items}</td></tr>)}
                </React.Fragment>);})}
            </tbody>
          </table>
        </div>); } },

    { id:'fD-table-comparison', type:'data', subtype:'table', title:'Comparison table', w:2,
      Render:(s)=>{
        const feats=[['Unlimited projects',1,1,1],['Advanced analytics',0,1,1],['Priority support',0,1,1],['SSO & SAML',0,0,1],['Audit logs',0,0,1]];
        const plans=['Starter','Pro','Scale'];
        const Mark=({on})=> on
          ? <span className="inline-flex items-center justify-center w-6 h-6 rounded-full" style={{color:UP,background:'rgba(34,197,94,.12)'}}><Glyph d="M5 12l4 4 10-10" size={13}/></span>
          : <span className={cx('inline-flex items-center justify-center w-6 h-6 rounded-full',s.cls.muted)} style={{background:'rgba(128,128,128,.1)'}}><Glyph d="M6 6l12 12M18 6L6 18" size={12}/></span>;
        return(
        <div className={cx(s.cls.surface,'w-full max-w-[540px] p-5')}>
          <div className={head(s,'font-extrabold mb-4')}>Compare plans</div>
          <table className="w-full text-[13px]">
            <thead><tr style={{borderBottom:`1px solid ${div}`}}>
              <th/>{plans.map((p,i)=>(
                <th key={p} className="pb-2.5 text-center font-bold">
                  <span className={i===1?s.cls.glow:s.cls.text}>{p}</span>
                  {i===1&&<div className="text-[10px] font-semibold mt-0.5" style={{color:s.cls.accent}}>Popular</div>}
                </th>))}
            </tr></thead>
            <tbody>
              {feats.map((f,i)=>(
                <tr key={i} style={{borderBottom:i<feats.length-1?`1px solid ${div}`:'none'}}>
                  <td className={cx('py-3',s.cls.sub)}>{f[0]}</td>
                  {[f[1],f[2],f[3]].map((v,j)=>(<td key={j} className="py-3 text-center"><Mark on={v}/></td>))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>); } },

  ];
  blocks.forEach(b=>window.BLOCKS.push(b));
})();
