// ============================================================
// IUVENIS · Shared components + icons
// ============================================================
const { useState, useEffect, useMemo, useRef, useCallback } = React;

// ---------- ICONS (Lucide-style, 16px default) ----------
const I = {
  home:   (p) => <svg {...iconProps(p)}><path d="M3 10.5 12 3l9 7.5"/><path d="M5 9.5V20a1 1 0 0 0 1 1h4v-6h4v6h4a1 1 0 0 0 1-1V9.5"/></svg>,
  social: (p) => <svg {...iconProps(p)}><circle cx="6" cy="6" r="2.5"/><circle cx="18" cy="6" r="2.5"/><circle cx="12" cy="18" r="2.5"/><path d="M7.8 7.4 10.2 16.6M16.2 7.4 13.8 16.6"/></svg>,
  money:  (p) => <svg {...iconProps(p)}><path d="M12 3v18M16 7H10a3 3 0 0 0 0 6h4a3 3 0 0 1 0 6H7"/></svg>,
  users:  (p) => <svg {...iconProps(p)}><circle cx="9" cy="8" r="3.5"/><path d="M3 20a6 6 0 0 1 12 0"/><circle cx="17.5" cy="9" r="2.5"/><path d="M16 20a4.5 4.5 0 0 1 5-4.4"/></svg>,
  mail:   (p) => <svg {...iconProps(p)}><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m4 7 8 6 8-6"/></svg>,
  pipe:   (p) => <svg {...iconProps(p)}><path d="M3 6h18M6 12h12M9 18h6"/></svg>,
  book:   (p) => <svg {...iconProps(p)}><path d="M4 4h11a3 3 0 0 1 3 3v13H7a3 3 0 0 1-3-3V4Z"/><path d="M4 17a3 3 0 0 1 3-3h11"/></svg>,
  check:  (p) => <svg {...iconProps(p)}><path d="M3 12l4 4 14-14"/></svg>,
  checks: (p) => <svg {...iconProps(p)}><path d="m3 12 4 4L17 6M13 16l3 3 5-5"/></svg>,
  search: (p) => <svg {...iconProps(p)}><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>,
  bell:   (p) => <svg {...iconProps(p)}><path d="M6 8a6 6 0 1 1 12 0c0 5 2 7 2 7H4s2-2 2-7Z"/><path d="M10 19a2 2 0 0 0 4 0"/></svg>,
  sun:    (p) => <svg {...iconProps(p)}><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg>,
  moon:   (p) => <svg {...iconProps(p)}><path d="M20 14.5A8 8 0 1 1 9.5 4a6 6 0 0 0 10.5 10.5Z"/></svg>,
  plus:   (p) => <svg {...iconProps(p)}><path d="M12 4v16M4 12h16"/></svg>,
  x:      (p) => <svg {...iconProps(p)}><path d="M5 5l14 14M19 5 5 19"/></svg>,
  arrow:  (p) => <svg {...iconProps(p)}><path d="M5 12h14M13 6l6 6-6 6"/></svg>,
  up:     (p) => <svg {...iconProps(p)}><path d="m6 14 6-6 6 6"/></svg>,
  down:   (p) => <svg {...iconProps(p)}><path d="m6 10 6 6 6-6"/></svg>,
  chev:   (p) => <svg {...iconProps(p)}><path d="m9 6 6 6-6 6"/></svg>,
  filter: (p) => <svg {...iconProps(p)}><path d="M4 5h16l-6 8v6l-4-2v-4Z"/></svg>,
  ext:    (p) => <svg {...iconProps(p)}><path d="M9 5H5v14h14v-4M14 4h6v6M10 14 20 4"/></svg>,
  more:   (p) => <svg {...iconProps(p)}><circle cx="5" cy="12" r="1.4"/><circle cx="12" cy="12" r="1.4"/><circle cx="19" cy="12" r="1.4"/></svg>,
  send:   (p) => <svg {...iconProps(p)}><path d="M4 20 21 4 14 21l-2-7-8-2Z"/></svg>,
  sparkle:(p) => <svg {...iconProps(p)}><path d="M12 3v6M12 15v6M3 12h6M15 12h6M6 6l3 3M18 18l-3-3M6 18l3-3M18 6l-3 3"/></svg>,
  cal:    (p) => <svg {...iconProps(p)}><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 9h18M8 3v4M16 3v4"/></svg>,
  play:   (p) => <svg {...iconProps(p)}><path d="M7 4v16l13-8Z"/></svg>,
  doc:    (p) => <svg {...iconProps(p)}><path d="M6 3h9l4 4v14H6Z"/><path d="M14 3v5h5"/></svg>,
  inst:   (p) => <svg {...iconProps(p)}><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17" cy="7" r="1" fill="currentColor"/></svg>,
  yt:     (p) => <svg {...iconProps(p)}><rect x="2" y="5" width="20" height="14" rx="3"/><path d="m10 9 6 3-6 3Z" fill="currentColor"/></svg>,
  tt:     (p) => <svg {...iconProps(p)}><path d="M14 4v9.5a4.5 4.5 0 1 1-4.5-4.5"/><path d="M14 4c.5 2.5 2.5 4.5 5 4.5"/></svg>,
  li:     (p) => <svg {...iconProps(p)}><rect x="3" y="3" width="18" height="18" rx="3"/><path d="M7 10v7M7 7v.01M11 17v-7M11 13c0-2 4-3 4 0v4" stroke="currentColor"/></svg>,
};
function iconProps(p={}) {
  return {
    width: p.size||16, height: p.size||16,
    viewBox:"0 0 24 24", fill:"none",
    stroke:"currentColor", strokeWidth:1.7, strokeLinecap:"round", strokeLinejoin:"round",
    className: "ico " + (p.className||""),
    style: p.style,
  };
}

// ---------- Helpers ----------
const fmtBRL = (v) => "R$ " + Math.round(v).toLocaleString("pt-BR");
const fmtCompact = (v) => {
  if (v >= 1_000_000) return (v/1_000_000).toFixed(1).replace(/\.0$/,"")+"M";
  if (v >= 1_000)     return (v/1_000).toFixed(1).replace(/\.0$/,"")+"k";
  return ""+v;
};
const fmtPct = (v) => (v>=0?"+":"") + v.toFixed(1) + "%";

function Delta({ value, suffix="%" }) {
  const c = value > 0 ? "up" : value < 0 ? "down" : "flat";
  const Arrow = value > 0 ? I.up : value < 0 ? I.down : null;
  return (
    <span className={"delta " + c}>
      {Arrow && <Arrow size={10}/>}
      {(value>=0?"+":"") + value.toFixed(1) + suffix}
    </span>
  );
}

function Avatar({ name, color }) {
  const init = name.split(" ").map(w=>w[0]).slice(0,2).join("").toUpperCase();
  // Deterministic color from name
  const palette = ["#1B4DD8","#6A47C7","#137DA0","#0F9D58","#D63384","#B7791F","#C8332B","#3F6ED9","#0E7AA1","#7C4FCF"];
  const idx = (name.charCodeAt(0) + name.charCodeAt(name.length-1)) % palette.length;
  return <div className="av" style={{ background: color || palette[idx] }}>{init}</div>;
}

// ---------- Charts (pure SVG) ----------
function LineChart({ data, height=220, gradientId="lg", color="var(--brand)", showXLabels=true, showGrid=true, secondary=null, secondaryColor="var(--text-3)" }) {
  const w = 800, h = height, pad = { l: 36, r: 12, t: 12, b: showXLabels?28:12 };
  const innerW = w - pad.l - pad.r, innerH = h - pad.t - pad.b;
  const max = Math.max(...data.map(d=>d.v), ...(secondary?secondary.map(d=>d.v):[0])) * 1.1;
  const min = 0;
  const x = i => pad.l + (i/(data.length-1)) * innerW;
  const y = v => pad.t + innerH - ((v-min)/(max-min||1)) * innerH;
  const pathD = data.map((d,i)=> (i===0?"M":"L")+x(i)+","+y(d.v)).join(" ");
  const areaD = pathD + ` L${x(data.length-1)},${y(min)} L${x(0)},${y(min)} Z`;
  const sec = secondary ? secondary.map((d,i)=> (i===0?"M":"L")+x(i)+","+y(d.v)).join(" ") : null;
  const ticks = 4;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" preserveAspectRatio="none" style={{display:"block"}}>
      <defs>
        <linearGradient id={gradientId} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%"  stopColor={color} stopOpacity="0.24"/>
          <stop offset="100%" stopColor={color} stopOpacity="0"/>
        </linearGradient>
      </defs>
      {showGrid && [...Array(ticks+1)].map((_,i)=>{
        const yy = pad.t + (i/ticks)*innerH;
        const val = max - (i/ticks)*(max-min);
        return <g key={i}>
          <line x1={pad.l} x2={w-pad.r} y1={yy} y2={yy} stroke="var(--border)" strokeDasharray={i===ticks?"":"3 3"}/>
          <text x={pad.l-6} y={yy+3} textAnchor="end" fontSize="10" fill="var(--text-3)" fontFamily="var(--font-mono)">{fmtCompact(val)}</text>
        </g>;
      })}
      <path d={areaD} fill={`url(#${gradientId})`}/>
      <path d={pathD} fill="none" stroke={color} strokeWidth="2"/>
      {sec && <path d={sec} fill="none" stroke={secondaryColor} strokeWidth="1.5" strokeDasharray="4 3"/>}
      {data.map((d,i)=> (
        <circle key={i} cx={x(i)} cy={y(d.v)} r={2.5} fill={color}/>
      ))}
      {showXLabels && data.map((d,i)=> i%Math.ceil(data.length/8)===0 && (
        <text key={"x"+i} x={x(i)} y={h-8} textAnchor="middle" fontSize="10" fill="var(--text-3)" fontFamily="var(--font-mono)">{d.label||""}</text>
      ))}
    </svg>
  );
}

function BarChart({ data, height=220, color="var(--brand)" }) {
  const w = 800, h = height, pad = { l: 36, r: 12, t: 12, b: 28 };
  const innerW = w-pad.l-pad.r, innerH = h-pad.t-pad.b;
  const max = Math.max(...data.map(d=>d.v)) * 1.1;
  const bw = innerW / data.length * 0.6;
  const step = innerW / data.length;
  const ticks = 4;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" preserveAspectRatio="none" style={{display:"block"}}>
      {[...Array(ticks+1)].map((_,i)=>{
        const yy = pad.t + (i/ticks)*innerH;
        const val = max - (i/ticks)*max;
        return <g key={i}>
          <line x1={pad.l} x2={w-pad.r} y1={yy} y2={yy} stroke="var(--border)" strokeDasharray={i===ticks?"":"3 3"}/>
          <text x={pad.l-6} y={yy+3} textAnchor="end" fontSize="10" fill="var(--text-3)" fontFamily="var(--font-mono)">{fmtCompact(val)}</text>
        </g>;
      })}
      {data.map((d,i)=>{
        const bh = (d.v/max)*innerH;
        const cx = pad.l + i*step + step/2;
        return <g key={i}>
          <rect x={cx-bw/2} y={pad.t+innerH-bh} width={bw} height={bh} fill={color} rx="3"/>
          <text x={cx} y={h-8} textAnchor="middle" fontSize="10" fill="var(--text-3)" fontFamily="var(--font-mono)">{d.label}</text>
        </g>;
      })}
    </svg>
  );
}

function ComboChart({ data, height=260 }) {
  // data: [{mes, receita, despesa}]
  const w = 800, h = height, pad = { l: 44, r: 12, t: 16, b: 30 };
  const innerW = w-pad.l-pad.r, innerH = h-pad.t-pad.b;
  const max = Math.max(...data.map(d=>Math.max(d.receita,d.despesa))) * 1.15;
  const step = innerW / data.length;
  const bw = step*0.32;
  const x = i => pad.l + i*step + step/2;
  const y = v => pad.t + innerH - (v/max)*innerH;
  const lucroLine = data.map((d,i)=> (i===0?"M":"L")+x(i)+","+y(d.receita-d.despesa)).join(" ");
  const ticks = 4;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" preserveAspectRatio="none" style={{display:"block"}}>
      <defs>
        <linearGradient id="recG" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="var(--brand-accent)"/>
          <stop offset="100%" stopColor="var(--brand)"/>
        </linearGradient>
      </defs>
      {[...Array(ticks+1)].map((_,i)=>{
        const yy = pad.t + (i/ticks)*innerH;
        const val = max - (i/ticks)*max;
        return <g key={i}>
          <line x1={pad.l} x2={w-pad.r} y1={yy} y2={yy} stroke="var(--border)" strokeDasharray={i===ticks?"":"3 3"}/>
          <text x={pad.l-6} y={yy+3} textAnchor="end" fontSize="10" fill="var(--text-3)" fontFamily="var(--font-mono)">{fmtCompact(val)}</text>
        </g>;
      })}
      {data.map((d,i)=>{
        const recH = (d.receita/max)*innerH;
        const desH = (d.despesa/max)*innerH;
        return <g key={i}>
          <rect x={x(i)-bw} y={pad.t+innerH-recH} width={bw} height={recH} fill="url(#recG)" rx="3"/>
          <rect x={x(i)+2}  y={pad.t+innerH-desH} width={bw} height={desH} fill="var(--surface-3)" rx="3"/>
          <text x={x(i)} y={h-10} textAnchor="middle" fontSize="10" fill="var(--text-3)" fontFamily="var(--font-mono)">{d.mes}</text>
        </g>;
      })}
      <path d={lucroLine} fill="none" stroke="var(--success)" strokeWidth="2"/>
      {data.map((d,i)=> <circle key={"l"+i} cx={x(i)} cy={y(d.receita-d.despesa)} r={3} fill="var(--success)"/> )}
    </svg>
  );
}

function Sparkline({ data, color="var(--brand)", height=32 }) {
  const w = 200, h = height;
  const max = Math.max(...data), min = Math.min(...data);
  const range = max-min || 1;
  const path = data.map((v,i)=>{
    const x = (i/(data.length-1))*w;
    const y = h - ((v-min)/range)*(h-4) - 2;
    return (i===0?"M":"L")+x+","+y;
  }).join(" ");
  return (
    <svg className="spark" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
      <path d={path+` L${w},${h} L0,${h} Z`} fill={color} opacity="0.12"/>
      <path d={path} fill="none" stroke={color} strokeWidth="1.5"/>
    </svg>
  );
}

function Donut({ segments, size=140, thickness=18, centerLabel, centerSub }) {
  const r = size/2 - thickness/2;
  const C = 2*Math.PI*r;
  const total = segments.reduce((s,x)=>s+x.value,0);
  let acc = 0;
  return (
    <div style={{ position:"relative", width:size, height:size }}>
      <svg width={size} height={size} className="ring">
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--surface-3)" strokeWidth={thickness}/>
        {segments.map((s,i)=>{
          const len = (s.value/total)*C;
          const dash = `${len} ${C-len}`;
          const dashoffset = -acc;
          acc += len;
          return <circle key={i} cx={size/2} cy={size/2} r={r} fill="none" stroke={s.color} strokeWidth={thickness} strokeDasharray={dash} strokeDashoffset={dashoffset} strokeLinecap="butt"/>;
        })}
      </svg>
      {centerLabel && <div style={{ position:"absolute", inset:0, display:"grid", placeItems:"center", textAlign:"center" }}>
        <div>
          <div className="num" style={{ fontSize:20, fontWeight:500 }}>{centerLabel}</div>
          {centerSub && <div style={{ fontSize:11, color:"var(--text-3)" }}>{centerSub}</div>}
        </div>
      </div>}
    </div>
  );
}

// ---------- PeriodFilter ----------
function PeriodFilter({ value, onChange }) {
  const opts = ["7d","30d","90d","Ano"];
  return (
    <div className="pill-group">
      {opts.map(o => (
        <button key={o} className={"pill " + (o===value?"active":"")} onClick={()=>onChange(o)}>{o}</button>
      ))}
    </div>
  );
}

// ---------- SocialIcon ----------
function SocialIcon({ rede, size=22 }) {
  const map = {
    instagram: { cls:"sn-ig", ico:<I.inst size={13}/> },
    tiktok:    { cls:"sn-tt", ico:<I.tt size={13}/> },
    youtube:   { cls:"sn-yt", ico:<I.yt size={13}/> },
    linkedin:  { cls:"sn-li", ico:<I.li size={13}/> },
  };
  const m = map[rede];
  return <span className={"sn-ico " + m.cls} style={{ width:size, height:size }}>{m.ico}</span>;
}

// ---------- Stat card ----------
function StatCard({ label, value, delta, unit, spark, accent="var(--brand)" }) {
  return (
    <div className="card">
      <div className="stat-label">{label}</div>
      <div className="row gap-3" style={{ alignItems:"baseline" }}>
        <div className="stat-value">{typeof value==="number" ? value.toLocaleString("pt-BR") : value}{unit||""}</div>
        {delta !== undefined && <Delta value={delta} suffix={typeof delta === "number"?"%":""}/>}
      </div>
      {spark && <div className="mt-3"><Sparkline data={spark} color={accent}/></div>}
    </div>
  );
}

// ---------- Modal ----------
function Modal({ title, sub, children, onClose, footer, wide }) {
  useEffect(()=>{
    const h = e => e.key === "Escape" && onClose();
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  },[onClose]);
  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal slide-up" onClick={e=>e.stopPropagation()} style={ wide ? { width:"min(880px,94vw)" } : null }>
        <div className="modal-h">
          <div>
            <div style={{ fontSize:16, fontWeight:600 }}>{title}</div>
            {sub && <div className="text-3" style={{ fontSize:12, marginTop:2 }}>{sub}</div>}
          </div>
          <button className="icon-btn" onClick={onClose}><I.x size={18}/></button>
        </div>
        <div className="modal-b">{children}</div>
        {footer && <div className="modal-f">{footer}</div>}
      </div>
    </div>
  );
}

// Expose globals
Object.assign(window, { I, fmtBRL, fmtCompact, fmtPct, Delta, Avatar, LineChart, BarChart, ComboChart, Sparkline, Donut, PeriodFilter, SocialIcon, StatCard, Modal });
