/* global React */
const { useState, useMemo, useEffect, useRef } = React;

// =============== Icons (small inline SVGs) ===============
const Icon = ({name, size=16, stroke=1.7}) => {
  const p = {width:size, height:size, viewBox:"0 0 24 24", fill:"none", stroke:"currentColor",
    strokeWidth:stroke, strokeLinecap:"round", strokeLinejoin:"round"};
  const g = {
    grid:<g><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/>
      <rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></g>,
    map:<g><polygon points="3 6 9 3 15 6 21 3 21 18 15 21 9 18 3 21 3 6"/>
      <line x1="9" y1="3" x2="9" y2="18"/><line x1="15" y1="6" x2="15" y2="21"/></g>,
    users:<g><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/>
      <path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></g>,
    user:<g><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></g>,
    rocket:<g><path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"/>
      <path d="M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"/>
      <path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"/><path d="M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"/></g>,
    network:<g><circle cx="12" cy="5" r="3"/><circle cx="5" cy="19" r="3"/><circle cx="19" cy="19" r="3"/>
      <line x1="12" y1="8" x2="5" y2="16"/><line x1="12" y1="8" x2="19" y2="16"/></g>,
    trophy:<g><path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"/><path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"/>
      <path d="M4 22h16"/><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"/>
      <path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"/>
      <path d="M18 2H6v7a6 6 0 0 0 12 0V2Z"/></g>,
    calendar:<g><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/>
      <line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></g>,
    bell:<g><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></g>,
    search:<g><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></g>,
    settings:<g><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></g>,
    arrowRight:<g><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></g>,
    arrowUp:<g><polyline points="6 15 12 9 18 15"/></g>,
    plus:<g><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></g>,
    spark:<g><polyline points="3 17 9 11 13 15 21 7"/><polyline points="14 7 21 7 21 14"/></g>,
    chip:<g><rect x="4" y="4" width="16" height="16" rx="2"/><rect x="9" y="9" width="6" height="6"/>
      <line x1="9" y1="2" x2="9" y2="4"/><line x1="15" y1="2" x2="15" y2="4"/>
      <line x1="9" y1="20" x2="9" y2="22"/><line x1="15" y1="20" x2="15" y2="22"/>
      <line x1="20" y1="9" x2="22" y2="9"/><line x1="20" y1="14" x2="22" y2="14"/>
      <line x1="2" y1="9" x2="4" y2="9"/><line x1="2" y1="14" x2="4" y2="14"/></g>,
    layers:<g><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/>
      <polyline points="2 12 12 17 22 12"/></g>,
    building:<g><rect x="4" y="2" width="16" height="20" rx="2"/><line x1="9" y1="6" x2="9" y2="6"/>
      <line x1="15" y1="6" x2="15" y2="6"/><line x1="9" y1="10" x2="9" y2="10"/>
      <line x1="15" y1="10" x2="15" y2="10"/><line x1="9" y1="14" x2="9" y2="14"/>
      <line x1="15" y1="14" x2="15" y2="14"/><line x1="10" y1="22" x2="10" y2="18"/>
      <line x1="14" y1="22" x2="14" y2="18"/></g>,
    briefcase:<g><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"/></g>,
    book:<g><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></g>,
    target:<g><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></g>,
    flame:<g><path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"/></g>,
    star:<g><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></g>,
    check:<g><polyline points="20 6 9 17 4 12"/></g>,
    eye:<g><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></g>,
    msg:<g><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></g>,
    filter:<g><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></g>,
  };
  return <svg {...p}>{g[name] || g.grid}</svg>;
};
window.Icon = Icon;

// =============== Avatar ===============
function Avatar({name, initials, color, size='md'}) {
  const cls = size==='sm' ? 'avatar-sm' : size==='lg' ? 'avatar-lg' : size==='xl' ? 'avatar-xl' : '';
  const colors = ['#0B5FBE','#0E3F84','#7C3AED','#DB2777','#0891B2','#059669','#F59E0B','#DC2626','#0EA5E9','#6366F1'];
  const seed = (name||'?').charCodeAt(0) + (name||'?').charCodeAt(1 || 0) || 0;
  const bg = color || colors[Math.abs(seed) % colors.length];
  return <div className={`avatar ${cls}`} style={{background:`linear-gradient(135deg, ${bg}, ${shade(bg, -.18)})`}}>{initials}</div>;
}
function shade(hex, p) {
  const n = hex.replace('#','');
  const r = parseInt(n.slice(0,2),16), g = parseInt(n.slice(2,4),16), b = parseInt(n.slice(4,6),16);
  const f = (c) => Math.max(0, Math.min(255, Math.round(c + 255*p)));
  return '#'+[f(r),f(g),f(b)].map(c=>c.toString(16).padStart(2,'0')).join('');
}
window.Avatar = Avatar;
window.shade = shade;

// =============== Badge / Selo ===============
function Selo({id, small=false}) {
  const s = window.SELOS[id]; if (!s) return null;
  return <span className="selo" style={{background:s.cor+'22', color:shade(s.cor,-.2)}}>
    <span className="selo-ic" style={{background:s.cor}}>{s.icon}</span>
    {small ? null : s.nome}
  </span>;
}
window.Selo = Selo;

function ClassifPill({id, withDot=true}) {
  const c = window.CLASSIFICACOES.find(x=>x.id===id); if (!c) return null;
  return <span className="classif-pill" style={{background:c.cor+'18', color:shade(c.cor,-.25)}}>
    {withDot && <span className="dot" style={{background:c.cor}}/>}
    {c.nome}
  </span>;
}
window.ClassifPill = ClassifPill;

// =============== Sparkline ===============
function Sparkline({data, w=80, h=22, color='#0B5FBE', fill=true}) {
  const max = Math.max(...data), min = Math.min(...data);
  const range = max - min || 1;
  const dx = w / (data.length - 1);
  let path = '';
  data.forEach((v, i) => {
    const x = i * dx, y = h - ((v - min) / range) * (h - 2) - 1;
    path += (i===0?'M':'L') + x.toFixed(1) + ' ' + y.toFixed(1) + ' ';
  });
  const fillPath = path + `L ${w} ${h} L 0 ${h} Z`;
  return <svg width={w} height={h} className="spark">
    {fill && <path d={fillPath} fill={color} opacity=".12"/>}
    <path d={path} fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round"/>
  </svg>;
}
window.Sparkline = Sparkline;

// =============== Radar Chart ===============
function Radar({dim, size=200, color='#0B5FBE'}) {
  const cx = size/2, cy = size/2, R = size/2 - 22;
  const labels = [
    {key:'engajamento', name:'Engajamento'},
    {key:'execucao',    name:'Execução'},
    {key:'colaboracao', name:'Colaboração'},
    {key:'reconhecimento', name:'Reconhecimento'},
    {key:'maturidade',  name:'Maturidade'},
  ];
  const N = labels.length;
  const point = (val, i) => {
    const a = -Math.PI/2 + i * 2*Math.PI/N;
    const r = (val/100) * R;
    return [cx + r*Math.cos(a), cy + r*Math.sin(a)];
  };
  const grid = [0.25, 0.5, 0.75, 1].map(f =>
    labels.map((_, i) => point(100*f, i)).map(p=>p.join(',')).join(' ')
  );
  const dataPoly = labels.map((l, i) => point(dim[l.key], i)).map(p=>p.join(',')).join(' ');
  return (
    <div className="radar-wrap">
      <div className="radar">
        <svg width={size} height={size}>
          {grid.map((pts, i) => (
            <polygon key={i} points={pts} fill="none" stroke="#E2E8F0" strokeWidth="1"/>
          ))}
          {labels.map((l, i) => {
            const [x, y] = point(100, i);
            return <line key={i} x1={cx} y1={cy} x2={x} y2={y} stroke="#E2E8F0" strokeWidth="1"/>;
          })}
          <polygon points={dataPoly} fill={color} fillOpacity=".18" stroke={color} strokeWidth="1.8"/>
          {labels.map((l, i) => {
            const [x, y] = point(dim[l.key], i);
            return <circle key={i} cx={x} cy={y} r="3.5" fill={color} stroke="#fff" strokeWidth="1.5"/>;
          })}
          {labels.map((l, i) => {
            const [x, y] = point(118, i);
            return <text key={i} x={x} y={y} textAnchor="middle" dominantBaseline="middle"
              fontSize="9.5" fontFamily="DM Sans" fontWeight="600" fill="#475569">{l.name}</text>;
          })}
        </svg>
      </div>
      <div className="radar-legend">
        {labels.map(l => (
          <div key={l.key} className="radar-legend-row">
            <span className="radar-legend-dot" style={{background:color, opacity:.35 + dim[l.key]/200}}/>
            <span className="radar-legend-name">{l.name}</span>
            <span className="radar-legend-val">{dim[l.key]}</span>
          </div>
        ))}
      </div>
    </div>
  );
}
window.Radar = Radar;

// =============== Trail (gamified progression) ===============
function Trail({points}) {
  const steps = window.CLASSIFICACOES;
  const currentIdx = steps.findIndex(s => points >= s.faixa[0] && points < s.faixa[1]);
  return (
    <div className="trail">
      {steps.map((s, i) => {
        const done = i < currentIdx;
        const current = i === currentIdx;
        const cls = done ? 'done' : current ? 'current' : '';
        return (
          <div key={s.id} className={`trail-step ${cls}`}>
            <div className="trail-bubble">
              {done ? '✓' : i+1}
            </div>
            <div className="trail-label">{s.nome}<br/>
              <span style={{fontSize:10, color:'var(--gray-500)', fontWeight:500}}>
                {s.faixa[0]}–{s.faixa[1]>=999?'∞':s.faixa[1]} pts
              </span>
            </div>
          </div>
        );
      })}
    </div>
  );
}
window.Trail = Trail;

// =============== Bar list ===============
function BarRow({name, value, max, color='#0B5FBE'}) {
  const pct = (value/max)*100;
  return <div className="bar-row">
    <span className="name">{name}</span>
    <div className="bar"><i style={{width:pct+'%', background:color}}/></div>
    <span className="v">{value}</span>
  </div>;
}
window.BarRow = BarRow;

Object.assign(window, {Icon, Avatar, shade, Selo, ClassifPill, Sparkline, Radar, Trail, BarRow});
