// components.jsx — shared building blocks: Widget, KpiCard, StatusBadge, Avatar, Sparkline, Donut, BarChart, NotificationsPanel.

function Widget({ title, action, children, padding = 24, style = {} }) {
  return (
    <section className="card" style={{ padding, ...style }}>
      {(title || action) && (
        <header style={{ display:'flex', alignItems:'center', marginBottom:18, gap:12 }}>
          {title && <h3 style={{ margin:0, font:'700 16px/1 var(--m-font-sans)', color:'var(--app-text)', letterSpacing:'-.01em' }}>{title}</h3>}
          <div style={{ flex:1 }} />
          {action}
        </header>
      )}
      {children}
    </section>
  );
}

function KpiCard({ label, value, delta, deltaPositive = true, sublabel, icon, accent = 'var(--app-primary)' }) {
  return (
    <section className="card lift" style={{ padding:22, position:'relative', overflow:'hidden' }}>
      <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between' }}>
        <div className="eyebrow">{label}</div>
        {icon && (
          <div style={{ width:34, height:34, borderRadius:9, background: `${accent}1A`, color: accent, display:'grid', placeItems:'center' }}>
            <i data-lucide={icon} style={{ width:16, height:16, strokeWidth:1.8 }}></i>
          </div>
        )}
      </div>
      <div style={{ marginTop:12, display:'flex', alignItems:'baseline', gap:10, flexWrap:'wrap' }}>
        <span style={{ font:'700 28px/1 var(--m-font-sans)', letterSpacing:'-.02em', color:'var(--app-text)' }}>{value}</span>
        {delta != null && (
          <span style={{
            display:'inline-flex', alignItems:'center', gap:3,
            height:22, padding:'0 8px', borderRadius:6,
            background: deltaPositive ? 'rgba(25,199,129,.10)' : 'rgba(248,40,90,.10)',
            color: deltaPositive ? '#19C781' : '#F8285A',
            font:'700 11px/1 var(--m-font-sans)',
          }}>
            <i data-lucide={deltaPositive?'trending-up':'trending-down'} style={{ width:11, height:11, strokeWidth:2.4 }}></i>
            {delta}
          </span>
        )}
      </div>
      {sublabel && <div style={{ font:'500 12px/1.4 var(--m-font-sans)', color:'var(--app-text-3)', marginTop:8 }}>{sublabel}</div>}
    </section>
  );
}

function StatusBadge({ status }) {
  const map = {
    // CRM
    'Actif':       ['rgba(25,199,129,.12)', '#19C781'],
    'Prospect':    ['rgba(19,121,240,.12)', '#1379F0'],
    'Inactif':     ['rgba(120,130,157,.16)','#78829D'],
    // Stock
    'En stock':    ['rgba(25,199,129,.12)', '#19C781'],
    'Stock bas':   ['rgba(255,168,0,.14)',  '#B57200'],
    'Rupture':     ['rgba(248,40,90,.12)',  '#F8285A'],
    'Illimité':    ['rgba(15,118,110,.14)', '#0F766E'],
    // Movement
    'Entrée':      ['rgba(25,199,129,.12)', '#19C781'],
    'Sortie':      ['rgba(248,40,90,.10)',  '#F8285A'],
    'Transfert':   ['rgba(19,121,240,.10)', '#1379F0'],
    // Service
    'Actif·service':['rgba(25,199,129,.12)','#19C781'],
  };
  const [bg, fg] = map[status] || ['var(--app-surface-2)', 'var(--app-text-2)'];
  return (
    <span className="pill" style={{ background:bg, color:fg }}>
      <span className="pill-dot" style={{ background:fg }}></span>{status}
    </span>
  );
}

function Avatar({ ini, color, size = 36 }) {
  return (
    <div className="avatar" style={{ width:size, height:size, background:color, fontSize: size>=40?13:11 }}>{ini}</div>
  );
}

/* Smooth area chart for monthly sales. */
function AreaChart({ data, height = 220, color = '#C2410C', fmt = v=>v }) {
  const W = 800, H = height, P = 24;
  const max = Math.max(...data.map(d => d.v));
  const stepX = (W - P*2) / (data.length - 1);
  const pts = data.map((d, i) => [P + i*stepX, H - P - (d.v / max) * (H - P*2)]);
  const path = pts.map((p,i)=>`${i?'L':'M'}${p[0].toFixed(1)},${p[1].toFixed(1)}`).join(' ');
  const area = `${path} L${pts[pts.length-1][0]},${H-P} L${pts[0][0]},${H-P} Z`;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={height} preserveAspectRatio="none" style={{ display:'block' }}>
      <defs>
        <linearGradient id="ac-g" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%"   stopColor={color} stopOpacity=".25" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      {[0.25, 0.5, 0.75].map((t,i)=>(
        <line key={i} x1={P} x2={W-P} y1={P + t*(H-P*2)} y2={P + t*(H-P*2)} stroke="var(--app-border)" strokeDasharray="3 4" />
      ))}
      <path d={area} fill="url(#ac-g)" />
      <path d={path} fill="none" stroke={color} strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" />
      {pts.map((p,i)=>(
        <circle key={i} cx={p[0]} cy={p[1]} r="3" fill="var(--app-surface)" stroke={color} strokeWidth="2" />
      ))}
      {data.map((d,i)=>(
        <text key={i} x={pts[i][0]} y={H-6} fontSize="10" textAnchor="middle" fill="var(--app-text-3)" style={{ font:'500 10px var(--m-font-sans)' }}>{d.m}</text>
      ))}
    </svg>
  );
}

function Donut({ segments, size = 140, thickness = 18, label, sub }) {
  const r = (size - thickness) / 2;
  const cx = size/2, cy = size/2;
  const C = 2 * Math.PI * r;
  const total = segments.reduce((s,x)=>s+x.value,0);
  let acc = 0;
  return (
    <div style={{ display:'flex', alignItems:'center', gap:16 }}>
      <svg width={size} height={size} style={{ transform:'rotate(-90deg)' }}>
        <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--app-border)" strokeWidth={thickness} />
        {segments.map((s, i) => {
          const len = (s.value/total) * C;
          const off = C - len;
          const dash = `${len} ${C - len}`;
          const dashoffset = -((acc/total) * C);
          acc += s.value;
          return <circle key={i} cx={cx} cy={cy} r={r} fill="none"
            stroke={s.color} strokeWidth={thickness}
            strokeDasharray={dash} strokeDashoffset={dashoffset} strokeLinecap="butt" />;
        })}
        <foreignObject x="0" y="0" width={size} height={size} style={{ transform:'rotate(90deg)', transformOrigin:'center' }}>
          <div style={{ display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', height: size, gap:2 }}>
            <span style={{ font:'700 22px/1 var(--m-font-sans)', color:'var(--app-text)', letterSpacing:'-.02em' }}>{label}</span>
            {sub && <span style={{ font:'500 10px/1 var(--m-font-sans)', color:'var(--app-text-3)' }}>{sub}</span>}
          </div>
        </foreignObject>
      </svg>
      <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
        {segments.map((s,i)=>(
          <div key={i} style={{ display:'flex', alignItems:'center', gap:8 }}>
            <span style={{ width:10, height:10, borderRadius:3, background:s.color }}></span>
            <span style={{ font:'500 12px/1 var(--m-font-sans)', color:'var(--app-text-2)' }}>{s.label}</span>
            <span style={{ font:'700 12px/1 var(--m-font-sans)', color:'var(--app-text)' }}>{Math.round(100*s.value/total)}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function NotificationsPanel({ open, onClose }) {
  if (!open) return null;
  const toneMap = {
    danger:  ['#F8285A', 'rgba(248,40,90,.10)'],
    warning: ['#B57200', 'rgba(255,168,0,.14)'],
    primary: ['#1379F0', 'rgba(19,121,240,.10)'],
    success: ['#19C781', 'rgba(25,199,129,.10)'],
    warm:    ['#C2410C', 'rgba(194,65,12,.10)'],
  };
  return (
    <div onClick={onClose} style={{
      position:'fixed', inset:0, zIndex:30, background:'rgba(0,0,0,.18)'
    }}>
      <div onClick={e=>e.stopPropagation()} className="card" style={{
        position:'absolute', top:72, right:24, width:360, padding:0, overflow:'hidden',
        boxShadow:'0 8px 24px rgba(7,20,55,.18)'
      }}>
        <div style={{ padding:'14px 18px', display:'flex', alignItems:'center', borderBottom:'1px solid var(--app-border)' }}>
          <div style={{ font:'700 14px/1 var(--m-font-sans)', color:'var(--app-text)' }}>Notifications</div>
          <span style={{ marginLeft:8, font:'700 10px/1 var(--m-font-sans)', color:'#fff', background:'#C2410C', borderRadius:99, padding:'3px 7px' }}>5</span>
          <div style={{ flex:1 }} />
          <button className="btn btn-ghost" style={{ height:28, padding:'0 10px', font:'500 11px/1 var(--m-font-sans)' }}>Tout marquer lu</button>
        </div>
        <div style={{ maxHeight:420, overflowY:'auto' }}>
          {NOTIFICATIONS.map((n,i)=>{
            const [fg, bg] = toneMap[n.tone];
            return (
              <div key={i} style={{ display:'flex', gap:12, padding:'12px 18px', borderBottom:'1px solid var(--app-border)', alignItems:'flex-start' }}>
                <div style={{ width:34, height:34, borderRadius:9, background:bg, color:fg, display:'grid', placeItems:'center', flexShrink:0 }}>
                  <i data-lucide={n.icon} style={{ width:16, height:16, strokeWidth:1.8 }}></i>
                </div>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ font:'700 13px/1.2 var(--m-font-sans)', color:'var(--app-text)' }}>{n.title}</div>
                  <div style={{ font:'500 12px/1.4 var(--m-font-sans)', color:'var(--app-text-3)', marginTop:3 }}>{n.body}</div>
                  <div style={{ font:'500 10px/1 var(--m-font-sans)', color:'var(--app-text-4)', marginTop:6 }}>{n.when}</div>
                </div>
              </div>
            );
          })}
        </div>
        <div style={{ padding:'12px 18px', textAlign:'center', borderTop:'1px solid var(--app-border)' }}>
          <a href="#" style={{ font:'700 12px/1 var(--m-font-sans)', color:'var(--app-primary)' }}>Voir toutes les notifications</a>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Widget, KpiCard, StatusBadge, Avatar, AreaChart, Donut, NotificationsPanel });
