/* crm-shared.jsx — Sidebar, TopBar, Badge, Timeline, Icons, helpers */

// ── Icons (line-art, 16px viewbox) ───────────────────────────────────────
function Icon({k, size=16, color='currentColor'}) {
  const p = {width:size, height:size, viewBox:'0 0 16 16', fill:'none', stroke:color, strokeWidth:1.2, strokeLinecap:'round', strokeLinejoin:'round'};
  switch(k){
    case 'dashboard': return <svg {...p}><rect x="2" y="2" width="5" height="5"/><rect x="9" y="2" width="5" height="5"/><rect x="2" y="9" width="5" height="5"/><rect x="9" y="9" width="5" height="5"/></svg>;
    case 'contracts': return <svg {...p}><path d="M3 1.5 h7 l3 3 v10 h-10 z"/><path d="M10 1.5 v3 h3"/><line x1="5" y1="7" x2="11" y2="7"/><line x1="5" y1="9.5" x2="11" y2="9.5"/><line x1="5" y1="12" x2="9" y2="12"/></svg>;
    case 'customers': return <svg {...p}><circle cx="5.5" cy="5" r="2.5"/><circle cx="11" cy="6" r="2"/><path d="M1.5 13 c0 -2.5 2 -4 4 -4 s4 1.5 4 4"/><path d="M9.5 13 c0 -2 1.5 -3.2 3 -3.2 s3 1.2 3 3.2"/></svg>;
    case 'products':  return <svg {...p}><path d="M6 1.5 h4 v2 h-4 z"/><path d="M4 3.5 h8 v10 a1 1 0 0 1 -1 1 h-6 a1 1 0 0 1 -1 -1 z"/><line x1="5" y1="9" x2="11" y2="9"/></svg>;
    case 'cycle':     return <svg {...p}><circle cx="8" cy="8" r="6"/><path d="M8 4 v4 l3 2"/></svg>;
    case 'billing':   return <svg {...p}><rect x="2" y="3" width="12" height="9" rx="0.5"/><line x1="2" y1="6" x2="14" y2="6"/><rect x="10" y="8.5" width="3" height="2" rx="0.3"/></svg>;
    case 'calendar':  return <svg {...p}><rect x="2" y="3" width="12" height="11" rx="0.5"/><line x1="2" y1="6" x2="14" y2="6"/><line x1="5" y1="1.5" x2="5" y2="4"/><line x1="11" y1="1.5" x2="11" y2="4"/></svg>;
    case 'search':    return <svg {...p}><circle cx="7" cy="7" r="4.5"/><line x1="10.5" y1="10.5" x2="14" y2="14"/></svg>;
    case 'plus':      return <svg {...p}><line x1="8" y1="3" x2="8" y2="13"/><line x1="3" y1="8" x2="13" y2="8"/></svg>;
    case 'chevron-r': return <svg {...p}><path d="M6 3 l5 5 l-5 5"/></svg>;
    case 'chevron-d': return <svg {...p}><path d="M3 6 l5 5 l5 -5"/></svg>;
    case 'arrow-r':   return <svg {...p}><line x1="2" y1="8" x2="14" y2="8"/><path d="M10 4 l4 4 l-4 4"/></svg>;
    case 'arrow-up':  return <svg {...p}><path d="M3 9 l5 -5 l5 5"/></svg>;
    case 'arrow-dn':  return <svg {...p}><path d="M3 7 l5 5 l5 -5"/></svg>;
    case 'filter':    return <svg {...p}><path d="M1.5 3 h13 l-5 6 v5 l-3 -1.5 v-3.5 z"/></svg>;
    case 'download':  return <svg {...p}><path d="M8 2 v9 M4 7 l4 4 l4 -4"/><line x1="2" y1="14" x2="14" y2="14"/></svg>;
    case 'check':     return <svg {...p}><path d="M3 8 l3 3 l7 -7"/></svg>;
    case 'x':         return <svg {...p}><line x1="4" y1="4" x2="12" y2="12"/><line x1="12" y1="4" x2="4" y2="12"/></svg>;
    case 'more':      return <svg {...p}><circle cx="3" cy="8" r="1" fill={color}/><circle cx="8" cy="8" r="1" fill={color}/><circle cx="13" cy="8" r="1" fill={color}/></svg>;
    case 'edit':      return <svg {...p}><path d="M2 14 h3 l8 -8 l-3 -3 l-8 8 z"/><line x1="10" y1="3" x2="13" y2="6"/></svg>;
    case 'bell':      return <svg {...p}><path d="M3.5 11 c0 -1 0.5 -1.5 0.5 -3.5 c0 -2 1.5 -4 4 -4 s4 2 4 4 c0 2 0.5 2.5 0.5 3.5 z"/><path d="M6.5 12 c0 1 0.5 1.5 1.5 1.5 s1.5 -0.5 1.5 -1.5"/></svg>;
    case 'pen':       return <svg {...p}><path d="M2 13 l1 -3 l7 -7 l2 2 l-7 7 z"/></svg>;
    case 'sepa':      return <svg {...p}><rect x="2" y="4" width="12" height="8" rx="0.5"/><line x1="2" y1="7" x2="14" y2="7"/><circle cx="11.5" cy="9.5" r="1" fill={color}/></svg>;
    case 'truck':     return <svg {...p}><rect x="1.5" y="5" width="7" height="6"/><path d="M8.5 7 h3 l2.5 2.5 v1.5 h-5.5"/><circle cx="4.5" cy="12" r="1.2"/><circle cx="11" cy="12" r="1.2"/></svg>;
    case 'invoice':   return <svg {...p}><path d="M3 1.5 h7 l3 3 v10 h-10 z"/><line x1="5" y1="7" x2="11" y2="7"/><line x1="5" y1="9.5" x2="11" y2="9.5"/><line x1="5" y1="12" x2="11" y2="12"/></svg>;
    case 'sun':       return <svg {...p}><circle cx="8" cy="8" r="3"/><line x1="8" y1="1" x2="8" y2="3"/><line x1="8" y1="13" x2="8" y2="15"/><line x1="1" y1="8" x2="3" y2="8"/><line x1="13" y1="8" x2="15" y2="8"/><line x1="3" y1="3" x2="4.5" y2="4.5"/><line x1="11.5" y1="11.5" x2="13" y2="13"/><line x1="3" y1="13" x2="4.5" y2="11.5"/><line x1="11.5" y1="4.5" x2="13" y2="3"/></svg>;
    case 'moon':      return <svg {...p}><path d="M12 9 a5 5 0 0 1 -7 -7 a6 6 0 1 0 7 7 z"/></svg>;
    default: return <svg {...p}><rect x="3" y="3" width="10" height="10"/></svg>;
  }
}

// ── Sidebar nav ──────────────────────────────────────────────────────────
const NAV_ITEMS = [
  {k:'dashboard',    label:'Dashboard',     icon:'dashboard'},
  {k:'new-proposal', label:'Nova proposta', icon:'pen',        accent:true},
  {k:'contracts',    label:'Contratos',     icon:'contracts',  count:14},
  {k:'cycle',        label:'Ciclo Q3',      icon:'cycle',      count:12, kbd:'⌘ Q'},
  {k:'customers',    label:'Clientes',      icon:'customers',  count:18},
  {k:'products',     label:'Produtos',      icon:'products',   count:8},
  {k:'billing',      label:'Faturação',     icon:'billing'},
  {k:'calendar',     label:'Calendário',    icon:'calendar'},
];

function Sidebar({route, onNav, onOpenSearch}) {
  return (
    <div className="sidebar">
      <div className="sb-brand">
        <div>
          <div className="logo">RVDE</div>
          <div className="role" style={{marginTop:2}}>admin · CRM</div>
        </div>
        <button className="btn ghost sm" style={{padding:'0 6px'}} title="Notificações">
          <Icon k="bell" size={14}/>
        </button>
      </div>

      <div className="sb-search" onClick={onOpenSearch}>
        <Icon k="search" size={14} color="currentColor"/>
        <span>Pesquisar…</span>
        <span className="kbd">⌘ K</span>
      </div>

      <div className="sb-section">
        <div className="label">Operação</div>
      </div>
      {NAV_ITEMS.map(it => (
        <div key={it.k}
             className={'sb-item' + (route === it.k ? ' active' : '') + (it.accent ? ' accent' : '')}
             onClick={() => onNav(it.k)}>
          <Icon k={it.icon} size={15} />
          <span className="grow truncate">{it.label}</span>
          {it.count != null && <span className="count">{it.count}</span>}
        </div>
      ))}

      <div className="sb-profile">
        <div className="avatar">J</div>
        <div className="grow truncate">
          <div style={{fontSize:13, lineHeight:1.2, fontWeight:600}}>Jorge Libório</div>
          <div className="ink-3" style={{fontSize:11}}>RVDE · gerente</div>
        </div>
      </div>
    </div>
  );
}

// ── TopBar ───────────────────────────────────────────────────────────────
function TopBar({crumbs, actions, onOpenSearch}) {
  return (
    <div className="topbar">
      <div className="crumb">
        {crumbs.map((c, i) => (
          <React.Fragment key={i}>
            {i > 0 && <span className="sep">/</span>}
            <span style={{color: i === crumbs.length - 1 ? 'var(--ink)' : 'var(--ink-3)', fontWeight: i === crumbs.length - 1 ? 500 : 400}}>{c}</span>
          </React.Fragment>
        ))}
      </div>
      <div style={{flex:1}}/>
      <button className="btn ghost sm" onClick={onOpenSearch} title="Pesquisar (⌘K)">
        <Icon k="search" size={13}/> Pesquisar
        <span style={{marginLeft:6, fontFamily:'var(--mono)', fontSize:10.5, color:'var(--ink-3)', border:'0.5px solid var(--rule)', borderRadius:3, padding:'1px 5px'}}>⌘ K</span>
      </button>
      {actions}
    </div>
  );
}

// ── Badge with state ─────────────────────────────────────────────────────
const STATE_LABELS = {
  active:    {label:'Ativo',          cls:'active'},
  renew:     {label:'Em renovação',   cls:'renew'},
  pending:   {label:'Pendente',       cls:'pending'},
  draft:     {label:'Rascunho',       cls:'draft'},
  ended:     {label:'Terminado',      cls:'ended'},
  failed:    {label:'Suspenso',       cls:'failed'},
};
const CYCLE_LABELS = {
  awaiting:  {label:'Extras pend.',   cls:'pending'},
  confirmed: {label:'Confirmados',    cls:'charged'},
  charging:  {label:'A cobrar',       cls:'dispatch'},
  charged:   {label:'Cobrado',        cls:'charged'},
  failed:    {label:'Falhou',         cls:'failed'},
  invoiced:  {label:'Faturado',       cls:'charged'},
  dispatch:  {label:'Despachado',     cls:'dispatch'},
  delivered: {label:'Entregue',       cls:'delivered'},
};
function StateBadge({state}) {
  const s = STATE_LABELS[state] || {label:state, cls:'ended'};
  return <span className={'badge ' + s.cls}><span className="dot"/>{s.label}</span>;
}
function CycleBadge({state}) {
  const s = CYCLE_LABELS[state] || {label:state, cls:'ended'};
  return <span className={'badge ' + s.cls}><span className="dot"/>{s.label}</span>;
}

// ── Timeline (8 trimestres) — reusable ──────────────────────────────────
function Timeline({current=3, states, compact=false, showLabels=true, dates=QUARTERS}) {
  const ss = states || Array.from({length:8}, (_,i) => i+1 < current ? 'done' : (i+1 === current ? 'curr' : 'fut'));
  return (
    <div className="stack" style={{gap: compact?3:5}}>
      <div className="tl-row">
        {ss.map((s, i) => {
          let cls = 'tl-block ' + (compact ? 'compact ' : '');
          if (s==='done') cls += 'tl-done';
          else if (s==='fail') cls += 'tl-fail';
          else if (s==='curr') cls += 'tl-curr';
          else cls += 'tl-fut';
          return (
            <div key={i} className={cls}>
              <span>Q{i+1}</span>
              {s==='done' && <span className="tl-tick">✓</span>}
              {s==='fail' && <span className="tl-tick">!</span>}
              {s==='curr' && <span className="tl-progress" style={{width:'46%'}}/>}
            </div>
          );
        })}
      </div>
      {showLabels && !compact && (
        <div className="tl-row">
          {dates.map((d, i) => (
            <div key={i} className="mono" style={{fontSize:9.5, color: ss[i]==='curr' ? 'var(--ink)' : 'var(--ink-3)', fontWeight: ss[i]==='curr' ? 600 : 400, textAlign:'center', letterSpacing:0.06}}>
              {d.date}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ── Mini sparkline for KPI cards ────────────────────────────────────────
function Sparkline({values, color='var(--clay)', w=80, h=20}) {
  const max = Math.max(...values), min = Math.min(...values);
  const sx = (i) => (i / (values.length-1)) * w;
  const sy = (v) => h - ((v - min) / Math.max(1, max - min)) * h;
  const d = values.map((v,i) => (i===0?'M':'L') + sx(i).toFixed(1) + ' ' + sy(v).toFixed(1)).join(' ');
  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} style={{display:'block'}}>
      <path d={d} fill="none" stroke={color} strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/>
      <circle cx={sx(values.length-1)} cy={sy(values[values.length-1])} r="2" fill={color}/>
    </svg>
  );
}

Object.assign(window, {
  Icon, Sidebar, TopBar, StateBadge, CycleBadge, Timeline, Sparkline, NAV_ITEMS,
});
