/* Atomic components for the Monolit UI kit. Exports to window for sharing. */
const { useState, useEffect, useRef } = React;

// ---------- Button ----------------------------------------------------------
function Button({ variant = 'primary', size = 'md', icon, iconRight, children, onClick, type = 'button', disabled, fullWidth, title }) {
  const cls = ['mn-btn', `mn-btn--${variant}`, `mn-btn--${size}`];
  if (disabled) cls.push('mn-btn--disabled');
  if (fullWidth) cls.push('mn-btn--full');
  return (
    <button type={type} className={cls.join(' ')} onClick={disabled ? undefined : onClick} disabled={disabled} title={title}>
      {icon ? <Icon name={icon} size={size === 'lg' ? 'md' : 'sm'} /> : null}
      {children ? <span>{children}</span> : null}
      {iconRight ? <Icon name={iconRight} size={size === 'lg' ? 'md' : 'sm'} /> : null}
    </button>
  );
}

function IconButton({ icon, onClick, title, active, size = 'md', danger }) {
  const cls = ['mn-icobtn', `mn-icobtn--${size}`];
  if (active) cls.push('mn-icobtn--active');
  if (danger) cls.push('mn-icobtn--danger');
  return (
    <button type="button" className={cls.join(' ')} onClick={onClick} title={title} aria-label={title}>
      <Icon name={icon} size={size === 'lg' ? 'md' : 'sm'} />
    </button>
  );
}

// ---------- Icon (Lucide wrapper) ------------------------------------------
// lucide.createIcons() REPLACES the <i> node with an <svg>, which breaks React
// reconciliation if React owns that node (removeChild crash on unmount). So the
// component owns a stable wrapper span and manages the <i>/<svg> imperatively.
function Icon({ name, size = 'sm', color, stroke }) {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current) return;
    const cls = ['icon', `icon-${size}`];
    if (color) cls.push(`icon-${color}`);
    if (stroke) cls.push(`icon-stroke-${stroke}`);
    ref.current.innerHTML = '<i data-lucide="' + name + '" class="' + cls.join(' ') + '"></i>';
    if (window.refreshIcons) window.refreshIcons(ref.current);
  }, [name, size, color, stroke]);
  return <span ref={ref} className="mn-iconwrap" />;
}

// ---------- Input -----------------------------------------------------------
function Input({ value, defaultValue, onChange, placeholder, icon, type = 'text', kbd, size = 'md', error, fullWidth, name, autoFocus }) {
  const cls = ['mn-input', `mn-input--${size}`];
  if (error) cls.push('mn-input--error');
  if (fullWidth) cls.push('mn-input--full');
  return (
    <label className={cls.join(' ')}>
      {icon ? <Icon name={icon} size="sm" color="text-3" /> : null}
      <input
        type={type}
        name={name}
        value={value}
        defaultValue={defaultValue}
        onChange={onChange ? (e) => onChange(e.target.value) : undefined}
        placeholder={placeholder}
        autoFocus={autoFocus}
      />
      {kbd ? <kbd className="mn-kbd">{kbd}</kbd> : null}
    </label>
  );
}

function Field({ label, required, hint, children, error }) {
  return (
    <div className="mn-field">
      <span className="mn-field-lbl">{label}{required ? <span className="mn-req"> *</span> : null}</span>
      {children}
      {error ? <span className="mn-field-err">{error}</span> : hint ? <span className="mn-field-hint">{hint}</span> : null}
    </div>
  );
}

// ---------- Avatar ----------------------------------------------------------
const AVATAR_BGS = {
  teal:   ['var(--teal-200)',   'var(--teal-900)'],
  blue:   ['var(--blue-200)',   'var(--blue-900)'],
  orange: ['var(--orange-200)', 'var(--orange-900)'],
  slate:  ['var(--slate-200)',  'var(--slate-800)'],
  green:  ['var(--green-200)',  'var(--green-900)'],
};
function Avatar({ user, size = 24 }) {
  if (!user) {
    return <span className="mn-avatar mn-avatar--empty" style={{ width: size, height: size }}><Icon name="user-x" size="sm" color="warning"/></span>;
  }
  const [bg, fg] = AVATAR_BGS[user.color] || AVATAR_BGS.slate;
  return (
    <span className="mn-avatar" style={{ width: size, height: size, background: bg, color: fg, fontSize: Math.max(10, Math.round(size * 0.42)) }}>
      {user.initials}
    </span>
  );
}

// ---------- Score ring ------------------------------------------------------
function ScoreRing({ value, size = 36 }) {
  if (value == null) {
    return (
      <span className="mn-score" style={{ width: size, height: size }}>
        <svg viewBox="0 0 36 36" width={size} height={size}><circle cx="18" cy="18" r="15" fill="none" stroke="var(--bg-3)" strokeWidth="3"/></svg>
        <span className="mn-score-num" style={{ color: 'var(--text-3)', fontSize: Math.max(11, Math.round(size * 0.36)) }}>–</span>
      </span>
    );
  }
  const band = value >= 70 ? 'success' : value >= 40 ? 'warning' : 'error';
  return (
    <span className="mn-score" style={{ width: size, height: size }}>
      <svg viewBox="0 0 36 36" width={size} height={size}>
        <circle cx="18" cy="18" r="15" fill="none" stroke={`var(--${band}-low)`} strokeWidth="3"/>
        <circle cx="18" cy="18" r="15" fill="none" stroke={`var(--${band}-main)`} strokeWidth="3"
                strokeDasharray={`${value} 100`} strokeLinecap="round" transform="rotate(-90 18 18)"/>
      </svg>
      <span className="mn-score-num" style={{ color: `var(--${band}-low-on)`, fontSize: Math.max(11, Math.round(size * 0.36)) }}>{value}</span>
    </span>
  );
}

// ---------- Status badge ----------------------------------------------------
const STATUS_CFG = {
  new:           { label: 'New',           cls: 'new',  icon: 'circle' },
  in_progress:   { label: 'In progress',   cls: 'ip',   icon: 'play' },
  qualified:     { label: 'Qualified',     cls: 'qual', icon: 'check' },
  disqualified:  { label: 'Disqualified',  cls: 'disq', icon: 'x' },
  converted:     { label: 'Converted',     cls: 'conv', icon: 'check-check' },
  archived:      { label: 'Archived',      cls: 'arc',  icon: 'archive' },
};
function StatusBadge({ status, size = 'md', onClick }) {
  const c = STATUS_CFG[status] || STATUS_CFG.new;
  const cls = ['mn-chip', `mn-chip--${size}`, `mn-chip--st-${c.cls}`];
  if (onClick) cls.push('mn-chip--btn');
  return (
    <span className={cls.join(' ')} onClick={onClick}>
      <Icon name={c.icon} size="xs" stroke="2"/> {c.label}
      {onClick ? <Icon name="chevron-down" size="xs" stroke="2"/> : null}
    </span>
  );
}

function Chip({ kind = 'neutral', icon, children }) {
  return <span className={`mn-chip mn-chip--md mn-chip--${kind}`}>{icon ? <Icon name={icon} size="xs" stroke="2"/> : null}{children}</span>;
}

// ---------- Next step cell --------------------------------------------------
function NextStepCell({ nextStep, now }) {
  if (!nextStep) return <span className="mn-chip mn-chip--md mn-chip--nonext">No next step</span>;
  const due = new Date(nextStep.due);
  const today = new Date(now); today.setHours(0,0,0,0);
  const dueDay = new Date(due); dueDay.setHours(0,0,0,0);
  const diff = (dueDay - today) / 86400000;
  let tone = 'neutral';
  if (diff < 0) tone = 'overdue';
  else if (diff === 0) tone = 'today';
  const fmt = due.toLocaleDateString('en-GB', { day: '2-digit', month: 'short' });
  return (
    <span className={`mn-next mn-next--${tone}`}>
      <span className="mn-next-text">{nextStep.text}</span>
      <span className="mn-next-date">{tone === 'overdue' ? `${fmt} · overdue` : fmt}</span>
    </span>
  );
}

// ---------- Tabs ------------------------------------------------------------
function Tabs({ items, value, onChange }) {
  return (
    <div className="mn-tabs">
      {items.map((it) => (
        <button key={it.id} type="button"
                className={'mn-tab' + (it.id === value ? ' mn-tab--active' : '')}
                onClick={() => onChange(it.id)}>
          <span>{it.label}</span>
          {typeof it.count === 'number' ? <span className="mn-tab-count">{it.count}</span> : null}
        </button>
      ))}
    </div>
  );
}

// ---------- Card ------------------------------------------------------------
function Card({ title, eyebrow, action, children, padding = 'md' }) {
  return (
    <section className={`mn-card mn-card--p-${padding}`}>
      {(title || eyebrow || action) ? (
        <header className="mn-card-h">
          <div>
            {eyebrow ? <div className="mn-eyebrow">{eyebrow}</div> : null}
            {title ? <h3 className="title-4 mn-card-title">{title}</h3> : null}
          </div>
          {action || null}
        </header>
      ) : null}
      {children}
    </section>
  );
}

// ---------- Logo ------------------------------------------------------------
function Logo({ wordmark = true }) {
  return (
    <span className="mn-logo">
      <svg className="mn-logo-mark" viewBox="0 0 32 32" width="24" height="24" aria-label="Monolit">
        <path d="M16 15 L25 10 L25 22.5 L16 27.5 Z" fill="#0f766e"/>
        <path d="M16 15 L7 10 L7 22.5 L16 27.5 Z" fill="#14b8a6"/>
        <path d="M16 4.5 L25 9.5 L16 14.5 L7 9.5 Z" fill="#5eead4"/>
        <path d="M7 16 L16 21 L25 16" fill="none" stroke="#042f2e" strokeOpacity="0.28" strokeWidth="1.1" strokeLinejoin="round"/>
      </svg>
      {wordmark ? <span className="mn-logo-word">monolit</span> : null}
    </span>
  );
}

Object.assign(window, { Button, IconButton, Icon, Input, Field, Avatar, ScoreRing, StatusBadge, Chip, NextStepCell, Tabs, Card, Logo });
