// atoms.jsx — small reusable components for the Immovertrieb app

const btnBase = {
  display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
  fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 600,
  padding: '11px 20px', borderRadius: 10, cursor: 'pointer',
  border: '1px solid transparent', transition: 'all 160ms cubic-bezier(.2,.8,.2,1)',
  lineHeight: 1, userSelect: 'none', whiteSpace: 'nowrap',
};

function Button({ variant = 'primary', size = 'md', children, leadingIcon, trailingIcon, block, style, ...rest }) {
  const variants = {
    primary:   { background: 'var(--accent)', color: 'var(--fg-on-amber)' },
    secondary: { background: '#fff', color: 'var(--fg-1)', border: '1px solid var(--border-strong)' },
    ghost:     { background: 'transparent', color: 'var(--fg-2)' },
    danger:    { background: 'var(--danger-500)', color: '#fff' },
    success:   { background: 'var(--success-500)', color: '#fff' },
  }[variant];
  const sizes = {
    sm: { padding: '7px 12px', fontSize: 13 },
    md: { padding: '11px 18px', fontSize: 14 },
    lg: { padding: '13px 24px', fontSize: 15 },
  }[size];
  return (
    <button {...rest} style={{ ...btnBase, ...variants, ...sizes, width: block ? '100%' : undefined, ...(style || {}) }}
      onMouseOver={e => {
        if (variant === 'primary') e.currentTarget.style.background = 'var(--accent-hover)';
        else if (variant === 'secondary') e.currentTarget.style.background = 'var(--surface-sunken)';
        else if (variant === 'ghost') e.currentTarget.style.background = 'var(--surface-sunken)';
      }}
      onMouseOut={e => {
        if (variant === 'primary') e.currentTarget.style.background = 'var(--accent)';
        else if (variant === 'secondary') e.currentTarget.style.background = '#fff';
        else if (variant === 'ghost') e.currentTarget.style.background = 'transparent';
      }}>
      {leadingIcon}{children}{trailingIcon}
    </button>
  );
}

function Field({ label, required, children, hint, htmlFor }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      {label && (
        <label htmlFor={htmlFor} style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg-2)' }}>
          {label}{required && <span style={{ color: 'var(--danger-500)', marginLeft: 2 }}>*</span>}
        </label>
      )}
      {children}
      {hint && <div style={{ fontSize: 12, color: 'var(--fg-4)' }}>{hint}</div>}
    </div>
  );
}

function Input(props) {
  const [focus, setFocus] = React.useState(false);
  return (
    <input {...props}
      onFocus={(e) => { setFocus(true); props.onFocus && props.onFocus(e); }}
      onBlur={(e) => { setFocus(false); props.onBlur && props.onBlur(e); }}
      style={{
        padding: '10px 12px', borderRadius: 10, fontFamily: 'var(--font-sans)',
        fontSize: 14, color: 'var(--fg-1)', background: '#fff', outline: 'none',
        border: `1px solid ${focus ? 'var(--accent)' : 'var(--border-input)'}`,
        boxShadow: focus ? 'var(--shadow-focus)' : 'none',
        transition: 'all 120ms ease', width: '100%', boxSizing: 'border-box',
        ...(props.style || {}),
      }}/>
  );
}

function Select(props) {
  const [focus, setFocus] = React.useState(false);
  return (
    <select {...props}
      onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
      style={{
        padding: '10px 12px', borderRadius: 10, fontFamily: 'var(--font-sans)',
        fontSize: 14, color: 'var(--fg-1)', background: '#fff', outline: 'none',
        border: `1px solid ${focus ? 'var(--accent)' : 'var(--border-input)'}`,
        boxShadow: focus ? 'var(--shadow-focus)' : 'none',
        transition: 'all 120ms ease', width: '100%', boxSizing: 'border-box',
        appearance: 'none',
        backgroundImage: 'url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' width=\'12\' height=\'12\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'%236B7280\' stroke-width=\'2\' stroke-linecap=\'round\' stroke-linejoin=\'round\'><path d=\'M6 9l6 6 6-6\'/></svg>")',
        backgroundRepeat: 'no-repeat', backgroundPosition: 'right 12px center', paddingRight: 36,
        ...(props.style || {}),
      }}>{props.children}</select>
  );
}

function Textarea(props) {
  const [focus, setFocus] = React.useState(false);
  return (
    <textarea {...props}
      onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
      style={{
        padding: '10px 12px', borderRadius: 10, fontFamily: 'var(--font-sans)',
        fontSize: 14, color: 'var(--fg-1)', background: '#fff', outline: 'none', resize: 'vertical',
        border: `1px solid ${focus ? 'var(--accent)' : 'var(--border-input)'}`,
        boxShadow: focus ? 'var(--shadow-focus)' : 'none',
        transition: 'all 120ms ease', width: '100%', boxSizing: 'border-box', minHeight: 60,
        ...(props.style || {}),
      }}/>
  );
}

function Accordion({ title, children, defaultOpen = true, right }) {
  const [open, setOpen] = React.useState(defaultOpen);
  return (
    <div style={{ background: '#fff', border: '1px solid var(--border-default)',
                  borderRadius: 12, overflow: 'hidden' }}>
      <button onClick={() => setOpen(!open)} style={{
        width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '14px 18px', background: 'transparent', border: 0, cursor: 'pointer',
        fontFamily: 'var(--font-sans)', fontSize: 15, fontWeight: 600, color: 'var(--fg-1)',
      }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>{title}</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
          {right}
          <span style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 160ms', color: 'var(--fg-3)' }}>
            <Icon.chevronDown size={18} />
          </span>
        </span>
      </button>
      {open && <div style={{ padding: '8px 18px 18px', borderTop: '1px solid var(--border-default)', display: 'flex', flexDirection: 'column', gap: 14 }}>{children}</div>}
    </div>
  );
}

function Pill({ children, tone = 'amber', size = 'md' }) {
  const tones = {
    amber:   { bg: 'var(--accent-soft)',  fg: 'var(--wholix-amber-800)' },
    red:     { bg: 'var(--danger-soft)',  fg: '#991B1B' },
    green:   { bg: 'var(--success-soft)', fg: '#166534' },
    blue:    { bg: 'var(--info-soft)',    fg: '#1E40AF' },
    grey:    { bg: 'var(--surface-sunken)', fg: 'var(--fg-2)' },
    yellow:  { bg: 'var(--warning-soft)', fg: '#92400E' },
  };
  const t = tones[tone] || tones.amber;
  const sz = size === 'sm'
    ? { padding: '2px 7px', fontSize: 10 }
    : { padding: '3px 9px', fontSize: 10 };
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4, background: t.bg, color: t.fg, borderRadius: 999,
      ...sz, fontWeight: 700, letterSpacing: '0.08em',
      textTransform: 'uppercase', lineHeight: 1.4, whiteSpace: 'nowrap',
    }}>{children}</span>
  );
}

function Tag({ children, tone = 'grey' }) {
  const tones = {
    grey:  { bg: 'var(--surface-sunken)', fg: 'var(--fg-2)', bd: 'var(--border-default)' },
    amber: { bg: 'var(--accent-soft)', fg: 'var(--wholix-amber-800)', bd: 'var(--accent-soft-border)' },
    green: { bg: 'var(--success-soft)', fg: '#166534', bd: '#BBF7D0' },
    blue:  { bg: 'var(--info-soft)', fg: '#1E40AF', bd: '#BFDBFE' },
  };
  const t = tones[tone] || tones.grey;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6, background: t.bg, color: t.fg,
      border: `1px solid ${t.bd}`, borderRadius: 999, padding: '3px 10px', fontSize: 12,
      fontWeight: 500, lineHeight: 1.4, whiteSpace: 'nowrap',
    }}>{children}</span>
  );
}

function InfoBanner({ children, tone = 'amber' }) {
  const tones = {
    amber: { bg: 'var(--accent-soft)', bd: 'var(--accent-soft-border)', fg: 'var(--wholix-amber-700)' },
    blue:  { bg: 'var(--info-soft)', bd: '#BFDBFE', fg: '#1E40AF' },
  }[tone];
  return (
    <div style={{
      display: 'flex', gap: 12, alignItems: 'flex-start',
      background: tones.bg, border: `1px solid ${tones.bd}`,
      borderRadius: 10, padding: '12px 16px', fontSize: 14, color: 'var(--fg-2)',
    }}>
      <span style={{ color: tones.fg, flexShrink: 0, marginTop: 1 }}><Icon.info size={18} /></span>
      <div style={{ flex: 1 }}>{children}</div>
    </div>
  );
}

function IconButton({ icon, onClick, badge, title, size = 34, active }) {
  return (
    <button onClick={onClick} title={title} style={{
      position: 'relative', width: size, height: size, borderRadius: 999,
      background: active ? 'var(--surface-sunken)' : 'transparent', border: 0, display: 'inline-flex',
      alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
      color: 'var(--fg-2)', flexShrink: 0,
    }}
      onMouseOver={e => e.currentTarget.style.background = 'var(--surface-sunken)'}
      onMouseOut={e => e.currentTarget.style.background = active ? 'var(--surface-sunken)' : 'transparent'}>
      {icon}
      {badge != null && (
        <span style={{
          position: 'absolute', top: 0, right: 0, minWidth: 16, height: 16, padding: '0 4px',
          borderRadius: 999, background: 'var(--danger-500)', color: '#fff', fontSize: 10,
          fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center',
          border: '2px solid #fff',
        }}>{badge}</span>
      )}
    </button>
  );
}

function Card({ children, padding = 20, style, onClick }) {
  return (
    <div onClick={onClick} style={{
      background: '#fff', border: '1px solid var(--border-default)',
      borderRadius: 14, padding, boxShadow: 'var(--shadow-xs)',
      cursor: onClick ? 'pointer' : 'default',
      ...(style || {}),
    }}>{children}</div>
  );
}

function Avatar({ name, size = 32, src, color }) {
  const initials = (name || '?').split(' ').map(s => s[0]).slice(0, 2).join('').toUpperCase();
  // Stable hue from name
  let hue = 0;
  for (let i = 0; i < (name || '').length; i++) hue = (hue * 31 + name.charCodeAt(i)) % 360;
  const bg = color || `oklch(0.86 0.06 ${hue})`;
  const fg = color ? '#fff' : `oklch(0.32 0.08 ${hue})`;
  return (
    <div style={{
      width: size, height: size, borderRadius: 999, background: src ? '#eee' : bg,
      color: fg, fontSize: Math.max(10, size * 0.38), fontWeight: 700,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      backgroundImage: src ? `url(${src})` : undefined, backgroundSize: 'cover', backgroundPosition: 'center',
    }}>{src ? '' : initials}</div>
  );
}

// Currency formatter (DE)
const fmtEUR = (n, opts = {}) => new Intl.NumberFormat('de-DE', {
  style: 'currency', currency: 'EUR', maximumFractionDigits: 0, ...opts,
}).format(n);
const fmtNum = (n, dec = 0) => new Intl.NumberFormat('de-DE', {
  minimumFractionDigits: dec, maximumFractionDigits: dec,
}).format(n);
const fmtPct = (n, dec = 2) => new Intl.NumberFormat('de-DE', {
  style: 'percent', minimumFractionDigits: dec, maximumFractionDigits: dec,
}).format(n);

// Empty state
function EmptyState({ icon, title, hint, action }) {
  return (
    <div style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
      padding: '40px 20px', textAlign: 'center', color: 'var(--fg-3)',
    }}>
      <div style={{
        width: 48, height: 48, borderRadius: 999, background: 'var(--surface-sunken)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--fg-3)',
      }}>{icon}</div>
      <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--fg-1)' }}>{title}</div>
      {hint && <div style={{ fontSize: 13, color: 'var(--fg-3)', maxWidth: 320 }}>{hint}</div>}
      {action}
    </div>
  );
}

// Stat block (KPI)
function Stat({ label, value, delta, deltaTone = 'green', icon, sub }) {
  return (
    <Card padding={18}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
        {icon && <div style={{
          width: 36, height: 36, borderRadius: 10, background: 'var(--accent-soft)',
          color: 'var(--wholix-amber-700)', display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>{icon}</div>}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12, color: 'var(--fg-3)', fontWeight: 500 }}>{label}</div>
          <div style={{ fontSize: 24, fontWeight: 700, color: 'var(--fg-1)', letterSpacing: '-0.01em', marginTop: 4 }}>{value}</div>
          {(delta || sub) && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6 }}>
              {delta && <Pill tone={deltaTone} size="sm">{delta}</Pill>}
              {sub && <span style={{ fontSize: 12, color: 'var(--fg-4)' }}>{sub}</span>}
            </div>
          )}
        </div>
      </div>
    </Card>
  );
}

Object.assign(window, {
  Button, Field, Input, Select, Textarea, Accordion, Pill, Tag, InfoBanner,
  IconButton, Card, Avatar, EmptyState, Stat, fmtEUR, fmtNum, fmtPct,
});
