// Shared UI primitives for DashM Advogados
// Read theme via window.useTheme()
// Exports: Card, Pill, Tab, Tabs, Stat, ProgressBar, Bars, Donut, Avatar, NavBar, BottomNav, FAB, ListRow, SectionHead, ChipRow, Toggle, Btn, SearchPill, MiniSpark, Currency

function useTheme() { return React.useContext(window.ThemeCtx); }

function Card({ children, style = {}, pad = 16, t, onClick }) {
  const tok = t || useTheme();
  return <div onClick={onClick} style={{
    background: tok.surface, border: `1px solid ${tok.border}`, borderRadius: 16,
    padding: pad, boxShadow: tok.shadow, cursor: onClick ? 'pointer' : undefined, ...style,
  }}>{children}</div>;
}

function Pill({ children, tone, style }) {
  const t = useTheme();
  const palette = {
    accent:   { bg: t.chipBg,                       fg: t.chipText },
    neutral:  { bg: t.elevated,                     fg: t.subtext },
    positive: { bg: 'rgba(127,169,127,0.13)',       fg: t.positive },
    danger:   { bg: 'rgba(196,123,108,0.13)',       fg: t.danger },
    warn:     { bg: 'rgba(212,165,116,0.13)',       fg: t.warn },
  }[tone || 'neutral'];
  return <span style={{
    display: 'inline-flex', alignItems: 'center', gap: 6,
    background: palette.bg, color: palette.fg,
    padding: '3px 9px', borderRadius: 999, fontSize: 11, fontWeight: 600,
    letterSpacing: 0.1, ...style,
  }}>{children}</span>;
}

function Tabs({ items, value, onChange, compact, t: tin }) {
  const t = tin || useTheme();
  return <div style={{
    display: 'flex', gap: 4, background: t.elevated,
    border: `1px solid ${t.borderSoft}`, padding: 3, borderRadius: 999,
  }}>
    {items.map(it => {
      const active = it === value || it.id === value;
      const label = it.label || it;
      const id = it.id || it;
      return <button key={id} onClick={() => onChange?.(id)} style={{
        flex: 1, border: 'none', cursor: 'pointer',
        background: active ? t.surface : 'transparent',
        color: active ? t.text : t.subtext,
        padding: compact ? '5px 10px' : '7px 12px', borderRadius: 999,
        fontSize: compact ? 11 : 12, fontWeight: 600, fontFamily: 'inherit',
        boxShadow: active ? `0 1px 2px rgba(0,0,0,${active ? 0.15 : 0})` : 'none',
        whiteSpace: 'nowrap',
      }}>{label}</button>;
    })}
  </div>;
}

function Stat({ label, value, hint, tone = 'accent', t: tin, big }) {
  const t = tin || useTheme();
  return <div>
    <div style={{ fontSize: 10, letterSpacing: 0.6, textTransform: 'uppercase', color: t.muted, fontWeight: 600 }}>{label}</div>
    <div style={{
      fontFamily: '"Playfair Display", serif', fontWeight: 600,
      fontSize: big ? 30 : 22, color: t.text, marginTop: 4, lineHeight: 1.1, letterSpacing: -0.3,
    }}>{value}</div>
    {hint && <div style={{ fontSize: 11, color: tone === 'positive' ? t.positive : tone === 'danger' ? t.danger : t.subtext, marginTop: 3, fontWeight: 500 }}>{hint}</div>}
  </div>;
}

function ProgressBar({ value = 0.5, color, height = 5, t: tin }) {
  const t = tin || useTheme();
  return <div style={{ width: '100%', height, background: t.elevated, borderRadius: 999, overflow: 'hidden' }}>
    <div style={{ width: `${value*100}%`, height: '100%', background: color || t.accent, borderRadius: 999 }} />
  </div>;
}

function Bars({ data = [], height = 60, color, accent = '#c8956d', t: tin }) {
  const t = tin || useTheme();
  const max = Math.max(...data, 1);
  return <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, height }}>
    {data.map((v, i) => <div key={i} style={{
      flex: 1, height: `${(v/max)*100}%`, minHeight: 3,
      background: i === data.length - 1 ? (accent || t.accent) : (color || t.elevated),
      borderRadius: 3,
    }} />)}
  </div>;
}

function Donut({ segments = [], size = 92, thickness = 14, t: tin, center }) {
  const t = tin || useTheme();
  const r = (size - thickness) / 2;
  const c = 2 * Math.PI * r;
  const total = segments.reduce((s, x) => s + x.value, 0) || 1;
  let acc = 0;
  return <div style={{ position: 'relative', width: size, height: size }}>
    <svg width={size} height={size} style={{ transform: 'rotate(-90deg)' }}>
      <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={t.elevated} strokeWidth={thickness} />
      {segments.map((s, i) => {
        const len = (s.value/total) * c;
        const off = -acc;
        acc += len;
        return <circle key={i} cx={size/2} cy={size/2} r={r} fill="none" stroke={s.color} strokeWidth={thickness} strokeDasharray={`${len} ${c}`} strokeDashoffset={off} strokeLinecap="butt"/>;
      })}
    </svg>
    {center && <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', color: t.text }}>{center}</div>}
  </div>;
}

function Avatar({ name = '', size = 32, t: tin, tone }) {
  const t = tin || useTheme();
  const initials = name.split(' ').map(s => s[0]).slice(0,2).join('').toUpperCase();
  return <div style={{
    width: size, height: size, borderRadius: '50%',
    background: tone || t.chipBg, color: tone ? '#fff' : t.chipText,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    fontSize: size * 0.36, fontWeight: 700, flexShrink: 0,
    fontFamily: 'Inter, system-ui',
  }}>{initials}</div>;
}

function BottomNav({ items, value, onChange, t: tin }) {
  const t = tin || useTheme();
  const nav = React.useContext(window.NavCtx);
  const handle = (id) => { onChange ? onChange(id) : nav?.go(id); };
  return <div style={{
    position: 'absolute', left: 0, right: 0, bottom: 0,
    background: t.surface, borderTop: `1px solid ${t.border}`,
    paddingBottom: 26, paddingTop: 9, display: 'flex', justifyContent: 'space-around',
    zIndex: 10,
  }}>
    {items.map(it => {
      const active = it.id === value;
      return <button key={it.id} onClick={() => handle(it.id)} style={{
        background: 'transparent', border: 'none', cursor: 'pointer',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
        color: active ? t.accent : t.muted, fontFamily: 'inherit',
        padding: '2px 8px',
      }}>
        <Icon name={it.icon} size={22} stroke={active ? 2 : 1.6}/>
        <span style={{ fontSize: 9.5, fontWeight: 600, letterSpacing: 0.2 }}>{it.label}</span>
      </button>;
    })}
  </div>;
}

function ScreenHeader({ title, sub, right, onBack, t: tin }) {
  const t = tin || useTheme();
  return <div style={{ padding: '14px 18px 10px', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 8 }}>
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, flex: 1, minWidth: 0 }}>
      {onBack && <button onClick={onBack} style={{ background: t.elevated, border: `1px solid ${t.border}`, borderRadius: 10, width: 32, height: 32, display: 'flex', alignItems: 'center', justifyContent: 'center', color: t.text, cursor: 'pointer', flexShrink: 0, marginTop: 2 }}><Icon name="chevronL" size={16}/></button>}
      <div style={{ minWidth: 0 }}>
        {sub && <div style={{ fontSize: 10, color: t.muted, fontWeight: 600, letterSpacing: 0.8, textTransform: 'uppercase' }}>{sub}</div>}
        <h1 style={{ fontFamily: '"Playfair Display", serif', margin: '2px 0 0', fontSize: 24, fontWeight: 600, letterSpacing: -0.4, color: t.text }}>{title}</h1>
      </div>
    </div>
    {right}
  </div>;
}

function IconBtn({ name, onClick, t: tin, active }) {
  const t = tin || useTheme();
  return <button onClick={onClick} style={{
    width: 36, height: 36, borderRadius: 12,
    background: active ? t.chipBg : t.elevated, border: `1px solid ${t.border}`,
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    color: active ? t.accent : t.text, cursor: 'pointer',
  }}><Icon name={name} size={17}/></button>;
}

function Btn({ children, variant = 'primary', icon, size = 'md', t: tin, onClick, style }) {
  const t = tin || useTheme();
  const sizes = {
    sm: { px: 11, py: 6, fs: 12 },
    md: { px: 14, py: 9, fs: 13 },
    lg: { px: 18, py: 12, fs: 14 },
  }[size];
  const v = {
    primary: { bg: t.accent, fg: '#fff', border: t.accent },
    ghost: { bg: 'transparent', fg: t.text, border: t.border },
    soft: { bg: t.chipBg, fg: t.chipText, border: 'transparent' },
  }[variant];
  return <button onClick={onClick} style={{
    background: v.bg, color: v.fg, border: `1px solid ${v.border}`,
    padding: `${sizes.py}px ${sizes.px}px`, borderRadius: 10,
    fontSize: sizes.fs, fontWeight: 600, cursor: 'pointer',
    display: 'inline-flex', alignItems: 'center', gap: 7, fontFamily: 'inherit',
    ...style,
  }}>{icon && <Icon name={icon} size={14}/>}{children}</button>;
}

function ChipRow({ items, value, onChange, t: tin, scroll }) {
  const t = tin || useTheme();
  return <div style={{ display: 'flex', gap: 7, overflowX: scroll ? 'auto' : 'visible', padding: scroll ? '0 18px' : 0 }}>
    {items.map(it => {
      const id = it.id || it;
      const label = it.label || it;
      const active = id === value;
      return <button key={id} onClick={() => onChange?.(id)} style={{
        background: active ? t.text : 'transparent',
        color: active ? t.bg : t.subtext,
        border: `1px solid ${active ? t.text : t.border}`,
        padding: '6px 11px', borderRadius: 999,
        fontSize: 11.5, fontWeight: 600, whiteSpace: 'nowrap',
        cursor: 'pointer', fontFamily: 'inherit',
      }}>{label}</button>;
    })}
  </div>;
}

function MiniSpark({ data = [], color, height = 28, width = 60 }) {
  const t = useTheme();
  if (!data.length) return null;
  const max = Math.max(...data), min = Math.min(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => `${(i/(data.length-1))*width},${height - ((v-min)/range)*height}`).join(' ');
  return <svg width={width} height={height}>
    <polyline points={pts} fill="none" stroke={color || t.accent} strokeWidth={1.6}/>
  </svg>;
}

function BRL(n) {
  return n.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL', maximumFractionDigits: 0 });
}

Object.assign(window, {
  useTheme, Card, Pill, Tabs, Stat, ProgressBar, Bars, Donut, Avatar,
  BottomNav, ScreenHeader, IconBtn, Btn, ChipRow, MiniSpark, BRL,
});
