// Core UI atoms for the HiKit hi-fi app.
// Card / Button / Badge / Pill / Avatar / Tabs / Input / Select / Toggle /
// Progress / Tooltip / KPI / Section. All read CSS vars from tokens.jsx.

if (typeof document !== 'undefined' && !document.getElementById('hk-ui')) {
  const s = document.createElement('style');
  s.id = 'hk-ui';
  s.textContent = `
    /* ── Card ────────────────────────────────────────────── */
    .hk-card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--r-4); box-shadow: var(--shadow-1); }
    .hk-card-pad { padding: 20px; }
    .hk-card-head { padding: 16px 20px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 10px; }
    .hk-card-body { padding: 16px 20px; }
    .hk-card-row { padding: 12px 20px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 10px; }
    .hk-card-row:last-child { border-bottom: 0; }
    /* ── Button ──────────────────────────────────────────── */
    .hk-btn {
      display: inline-flex; align-items: center; justify-content: center;
      gap: 6px; height: 34px; padding: 0 14px;
      font-weight: 500; font-size: 13px; line-height: 1;
      border-radius: var(--r-pill); border: 1px solid var(--border-input);
      background: var(--surface); color: var(--ink);
      transition: background .14s, border-color .14s, box-shadow .14s, color .14s, transform .04s;
      white-space: nowrap; user-select: none;
    }
    .hk-btn:hover { background: var(--surface-3); }
    .hk-btn:active { transform: translateY(0.5px); }
    .hk-btn-primary { background: var(--ink); color: var(--paper); border-color: var(--ink); }
    .hk-btn-primary:hover { background: var(--ink-2); border-color: var(--ink-2); }
    .hk-btn-accent { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); }
    .hk-btn-accent:hover { background: var(--accent-hover); border-color: var(--accent-hover); }
    .hk-btn-ghost { border-color: transparent; background: transparent; }
    .hk-btn-ghost:hover { background: var(--surface-3); }
    .hk-btn-danger { color: var(--bad); border-color: var(--bad-soft); background: var(--surface); }
    .hk-btn-danger:hover { background: var(--bad-soft); }
    .hk-btn-sm { height: 28px; padding: 0 10px; font-size: 12px; }
    .hk-btn-lg { height: 42px; padding: 0 20px; font-size: 14px; }
    .hk-btn-icon { width: 34px; padding: 0; border-radius: 999px; }
    .hk-btn-icon.hk-btn-sm { width: 28px; }
    .hk-btn[disabled] { opacity: 0.4; cursor: not-allowed; }

    /* ── Badge & Pill ───────────────────────────────────── */
    .hk-badge {
      display: inline-flex; align-items: center; gap: 4px;
      height: 20px; padding: 0 8px; font-size: 11px; font-weight: 500;
      border-radius: var(--r-pill); white-space: nowrap;
      background: var(--surface3); color: var(--ink-2); border: 1px solid var(--border);
    }
    .hk-badge-ok   { background: var(--ok-soft);   color: var(--ok);   border-color: transparent; }
    .hk-badge-warn { background: var(--warn-soft); color: var(--warn); border-color: transparent; }
    .hk-badge-bad  { background: var(--bad-soft);  color: var(--bad);  border-color: transparent; }
    .hk-badge-info { background: var(--info-soft); color: var(--info); border-color: transparent; }
    .hk-badge-accent { background: var(--accent-soft); color: var(--accent-deep); border-color: transparent; }
    .hk-badge-num  { font-family: var(--font-mono); }
    .hk-badge-dot::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: currentColor; display: inline-block; }

    /* ── Input ──────────────────────────────────────────── */
    .hk-input {
      display: flex; align-items: center; gap: 8px;
      height: 34px; padding: 0 10px;
      background: var(--surface); border: 1px solid var(--border-input);
      border-radius: var(--r-2); color: var(--ink);
      transition: border-color .14s, box-shadow .14s;
    }
    .hk-input:focus-within { border-color: var(--ink); box-shadow: 0 0 0 3px rgba(26,24,21,0.08); outline: none; }
    .hk-input input, .hk-input textarea {
      flex: 1; min-width: 0; border: 0; outline: 0; background: transparent; font: inherit; color: inherit;
      padding: 0;
    }
    .hk-input input::placeholder, .hk-input textarea::placeholder { color: var(--ink-3); }
    .hk-input-lg { height: 42px; font-size: 15px; padding: 0 14px; }
    .hk-textarea { min-height: 90px; padding: 8px 10px; align-items: flex-start; }

    /* ── Tabs ───────────────────────────────────────────── */
    .hk-tabs { display: flex; gap: 2px; border-bottom: 1px solid var(--border); }
    .hk-tab {
      padding: 9px 12px; font-size: 13px; font-weight: 500; color: var(--ink-3);
      border-bottom: 2px solid transparent; margin-bottom: -1px; cursor: pointer;
      transition: color .14s, border-color .14s;
      white-space: nowrap;
    }
    .hk-tab:hover { color: var(--ink); }
    .hk-tab[aria-selected="true"] { color: var(--ink); border-bottom-color: var(--accent); }

    /* segmented control */
    .hk-seg { display: inline-flex; background: var(--surface3); border: 1px solid var(--border); border-radius: var(--r-2); padding: 2px; gap: 2px; }
    .hk-seg button { padding: 4px 10px; border-radius: 4px; font-size: 12px; font-weight: 500; color: var(--ink-3); white-space: nowrap; }
    .hk-seg button[aria-selected="true"] { background: var(--surface); color: var(--ink); box-shadow: var(--shadow-1); }

    /* ── Toggle ─────────────────────────────────────────── */
    .hk-toggle { width: 32px; height: 18px; background: var(--ink-4); border-radius: 999px; position: relative; transition: background .15s; cursor: pointer; flex-shrink: 0; }
    .hk-toggle::after { content: ''; position: absolute; top: 2px; left: 2px; width: 14px; height: 14px; background: var(--surface); border-radius: 50%; box-shadow: 0 1px 2px rgba(0,0,0,.2); transition: transform .15s; }
    .hk-toggle[aria-checked="true"] { background: var(--accent); }
    .hk-toggle[aria-checked="true"]::after { transform: translateX(14px); }

    /* ── Progress ───────────────────────────────────────── */
    .hk-progress { height: 6px; background: var(--surface3); border-radius: 999px; overflow: hidden; }
    .hk-progress > div { height: 100%; background: var(--ink); border-radius: 999px; transition: width .35s ease; }
    .hk-progress-accent > div { background: var(--accent); }
    .hk-progress-ok > div { background: var(--ok); }
    .hk-progress-warn > div { background: var(--warn); }

    /* ── Avatar ─────────────────────────────────────────── */
    .hk-avatar {
      width: 28px; height: 28px; border-radius: 50%;
      background: var(--accent-soft); color: var(--accent-deep);
      display: inline-flex; align-items: center; justify-content: center;
      font-weight: 600; font-size: 11px; letter-spacing: 0.02em;
      flex-shrink: 0; overflow: hidden;
    }

    /* ── Kbd ────────────────────────────────────────────── */
    .hk-kbd {
      font-family: var(--font-mono); font-size: 11px;
      padding: 1px 6px; border-radius: 4px;
      background: var(--surface3); border: 1px solid var(--border);
      color: var(--ink-2);
    }

    /* ── Link ───────────────────────────────────────────── */
    .hk-link { color: var(--ink); border-bottom: 1px solid var(--border-strong); padding-bottom: 1px; cursor: pointer; }
    .hk-link:hover { border-color: var(--ink); }
    .hk-link-accent { color: var(--accent); border-color: var(--accent-soft); }
    .hk-link-accent:hover { border-color: var(--accent); }

    /* ── Tooltip-ish title hover (lightweight) ──────────── */
    .hk-hover-row { transition: background .12s; border-radius: var(--r-2); }
    .hk-hover-row:hover { background: var(--surface3); }

    /* ── Section header ─────────────────────────────────── */
    .hk-section-head { display: flex; align-items: baseline; gap: 12px; margin-bottom: 14px; }
    .hk-section-head .hk-h2 { margin: 0; }

    /* Status dot */
    .hk-statdot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; flex-shrink: 0; }
    .hk-statdot.ok   { background: var(--ok); }
    .hk-statdot.warn { background: var(--warn); }
    .hk-statdot.bad  { background: var(--bad); }
    .hk-statdot.info { background: var(--info); }
    .hk-statdot.gray { background: var(--ink-4); }
  `;
  document.head.appendChild(s);
}

// ── Components ────────────────────────────────────────────────

function Card({ children, className = '', style, pad = false, onClick, hoverable }) {
  const cls = ['hk-card'];
  if (pad) cls.push('hk-card-pad');
  if (hoverable) cls.push('hk-hover-row');
  if (className) cls.push(className);
  return <div className={cls.join(' ')} style={style} onClick={onClick}>{children}</div>;
}

function CardHead({ title, subtitle, action, children }) {
  return (
    <div className="hk-card-head">
      <div className="hk-grow">
        {title && <div className="hk-h3">{title}</div>}
        {subtitle && <div className="hk-tiny" style={{ marginTop: 2 }}>{subtitle}</div>}
      </div>
      {action || children}
    </div>
  );
}

function Btn({ children, variant, size, icon, iconOnly, className = '', style, ...rest }) {
  const cls = ['hk-btn'];
  if (variant === 'primary') cls.push('hk-btn-primary');
  if (variant === 'accent')  cls.push('hk-btn-accent');
  if (variant === 'ghost')   cls.push('hk-btn-ghost');
  if (variant === 'danger')  cls.push('hk-btn-danger');
  if (size === 'sm') cls.push('hk-btn-sm');
  if (size === 'lg') cls.push('hk-btn-lg');
  if (iconOnly) cls.push('hk-btn-icon');
  if (className) cls.push(className);
  return (
    <button className={cls.join(' ')} style={style} {...rest}>
      {icon && <Icon name={icon} size={size === 'sm' ? 14 : 15} />}
      {children}
    </button>
  );
}

function Badge({ children, tone, dot, num, className = '', style }) {
  const cls = ['hk-badge'];
  if (tone === 'ok')   cls.push('hk-badge-ok');
  if (tone === 'warn') cls.push('hk-badge-warn');
  if (tone === 'bad')  cls.push('hk-badge-bad');
  if (tone === 'info') cls.push('hk-badge-info');
  if (tone === 'accent') cls.push('hk-badge-accent');
  if (num) cls.push('hk-badge-num');
  if (dot) cls.push('hk-badge-dot');
  if (className) cls.push(className);
  return <span className={cls.join(' ')} style={style}>{children}</span>;
}

function StatDot({ tone = 'ok', style }) {
  return <span className={`hk-statdot ${tone}`} style={style} />;
}

function Avatar({ name = '?', tone, size = 28, src }) {
  const init = name.split(/\s+/).map(s => s[0]).filter(Boolean).slice(0, 2).join('').toUpperCase();
  // Theme-aware avatar palette via CSS vars
  const isDark = (typeof document !== 'undefined') && document.documentElement.getAttribute('data-theme') === 'dark';
  const bgs = isDark
    ? ['rgba(242,200,73,.18)', 'rgba(111,203,133,.18)', 'rgba(111,168,240,.18)', 'rgba(229,185,90,.18)', 'rgba(190,148,224,.18)', 'rgba(218,178,140,.18)']
    : ['#FBEDB6', '#DCEEDF', '#DAE6F5', '#F4E7C2', '#EBE3F5', '#E9DDD5'];
  const fgs = isDark
    ? ['#F2C849', '#6FCB85', '#6FA8F0', '#E5B95A', '#BE94E0', '#DAB28C']
    : ['#6E5710', '#1F5C2A', '#1C3F76', '#7A5C0F', '#5B3D80', '#5E3A1F'];
  const i = (name.charCodeAt(0) || 0) % bgs.length;
  return (
    <span className="hk-avatar" style={{ width: size, height: size, fontSize: Math.max(10, size * 0.38), background: tone === 'mono' ? 'var(--surface3)' : bgs[i], color: tone === 'mono' ? 'var(--ink-2)' : fgs[i] }}>
      {src ? <img src={src} alt="" style={{ width: '100%', height: '100%', borderRadius: '50%', objectFit: 'cover' }}/> : init}
    </span>
  );
}

function Input({ icon, iconRight, placeholder, value, onChange, size, type = 'text', style, ...rest }) {
  const cls = ['hk-input']; if (size === 'lg') cls.push('hk-input-lg');
  return (
    <label className={cls.join(' ')} style={style}>
      {icon && <Icon name={icon} size={size === 'lg' ? 18 : 16} style={{ color: 'var(--ink-3)' }}/>}
      <input type={type} value={value} placeholder={placeholder} onChange={onChange} {...rest}/>
      {iconRight && <Icon name={iconRight} size={size === 'lg' ? 18 : 16} style={{ color: 'var(--ink-3)' }}/>}
    </label>
  );
}

function Textarea({ placeholder, value, onChange, style, rows = 3, ...rest }) {
  return (
    <label className="hk-input hk-textarea" style={style}>
      <textarea rows={rows} value={value} placeholder={placeholder} onChange={onChange} {...rest} style={{ resize: 'vertical' }}/>
    </label>
  );
}

function Tabs({ tabs, value, onChange, style }) {
  return (
    <div className="hk-tabs" style={style} role="tablist">
      {tabs.map(t => {
        const sel = (t.id ?? t) === value;
        return (
          <button key={t.id ?? t} className="hk-tab" aria-selected={sel}
            onClick={() => onChange(t.id ?? t)} role="tab">
            {t.icon && <Icon name={t.icon} size={14} style={{ marginRight: 6, verticalAlign: '-2px' }}/>}
            {t.label ?? t}
            {t.count != null && <span className="hk-mono hk-dim" style={{ marginLeft: 6, fontSize: 11 }}>{t.count}</span>}
          </button>
        );
      })}
    </div>
  );
}

function Seg({ options, value, onChange, style }) {
  return (
    <div className="hk-seg" style={style}>
      {options.map(o => {
        const id = o.id ?? o;
        return (
          <button key={id} aria-selected={id === value} onClick={() => onChange(id)}>
            {o.icon && <Icon name={o.icon} size={12} style={{ marginRight: 4, verticalAlign: '-2px' }}/>}
            {o.label ?? id}
          </button>
        );
      })}
    </div>
  );
}

function Toggle({ checked, onChange, style }) {
  return (
    <button className="hk-toggle" aria-checked={checked ? 'true' : 'false'}
      onClick={() => onChange(!checked)} style={style}/>
  );
}

function Progress({ value = 0, max = 100, tone = 'ink', style }) {
  const pct = Math.max(0, Math.min(100, (value / max) * 100));
  const cls = ['hk-progress'];
  if (tone === 'accent') cls.push('hk-progress-accent');
  if (tone === 'ok')     cls.push('hk-progress-ok');
  if (tone === 'warn')   cls.push('hk-progress-warn');
  return <div className={cls.join(' ')} style={style}><div style={{ width: pct + '%' }}/></div>;
}

function Kbd({ children }) { return <span className="hk-kbd">{children}</span>; }

function Eyebrow({ children, style }) { return <div className="hk-eyebrow" style={style}>{children}</div>; }

// Trend pill — shows delta with arrow + color
function Trend({ value, suffix = '', tone, dim }) {
  const isUp = typeof value === 'number' ? value >= 0 : String(value).startsWith('+') || String(value).startsWith('↑');
  const t = tone || (isUp ? 'ok' : 'bad');
  return (
    <Badge tone={t} num>
      <Icon name={isUp ? 'arrowUp' : 'arrowDn'} size={11} strokeWidth={2.2}/>
      {typeof value === 'number' ? `${isUp ? '+' : ''}${value}${suffix}` : value}
    </Badge>
  );
}

function CardBody({ children, style }) {
  return <div className="hk-card-body" style={style}>{children}</div>;
}

// ── Hint tooltip (? badge with hover popup) ──────────────────
function Hint({ text, width = 200 }) {
  const [show, setShow] = React.useState(false);
  const [above, setAbove] = React.useState(true);
  const ref = React.useRef(null);

  const toggle = (visible) => {
    if (visible && ref.current) {
      const rect = ref.current.getBoundingClientRect();
      setAbove(rect.top > 160);
    }
    setShow(visible);
  };

  return (
    <span ref={ref} style={{ position:'relative', display:'inline-flex', alignItems:'center', flexShrink:0 }}
      onMouseEnter={() => toggle(true)} onMouseLeave={() => toggle(false)}>
      <span style={{
        width:14, height:14, borderRadius:'50%',
        background:'var(--surface-3)', border:'1px solid var(--border)',
        display:'inline-flex', alignItems:'center', justifyContent:'center',
        fontSize:9, fontWeight:700, color:'var(--ink-3)',
        cursor:'help', lineHeight:1,
      }}>?</span>
      {show && (
        <span style={{
          position:'absolute',
          [above ? 'bottom' : 'top']: 'calc(100% + 7px)',
          left:'50%', transform:'translateX(-50%)',
          background:'var(--paper)', border:'1px solid var(--border)',
          borderRadius:'var(--r-2)', padding:'8px 11px',
          width, fontSize:12, color:'var(--ink-2)',
          lineHeight:1.55, zIndex:300, boxShadow:'var(--shadow-pop)',
          pointerEvents:'none', whiteSpace:'normal',
          display:'block',
        }}>{text}</span>
      )}
    </span>
  );
}

// ── LockedSection (blur + upgrade CTA overlay) ───────────────
function LockedSection({ label = 'Unlock Full Recommendations', sub, ctaUrl, ctaLabel = 'Book a Free Call', children }) {
  const c = window.CP_CLIENT || {};
  const url = ctaUrl || c.bookingUrl || 'https://calendly.com/office-hikit/30min';
  return (
    <div style={{ position:'relative', borderRadius:'var(--r-3)', overflow:'hidden' }}>
      <div style={{ filter:'blur(4px)', pointerEvents:'none', userSelect:'none', opacity:0.55 }}>
        {children}
      </div>
      <div style={{
        position:'absolute', inset:0,
        background:'linear-gradient(to bottom, transparent 0%, var(--surface) 52%)',
        display:'flex', flexDirection:'column',
        alignItems:'center', justifyContent:'flex-end',
        padding:'28px 20px 20px',
      }}>
        <div style={{ fontSize:20, marginBottom:6 }}>🔒</div>
        <div style={{ fontSize:14, fontWeight:700, color:'var(--ink)', marginBottom:4, textAlign:'center' }}>{label}</div>
        <p style={{ fontSize:12.5, color:'var(--ink-3)', marginBottom:14, textAlign:'center', lineHeight:1.5, maxWidth:300 }}>
          {sub || 'Book a free strategy call to get step-by-step fix guides for every issue found.'}
        </p>
        <a href={url} target="_blank" rel="noopener" style={{
          display:'inline-flex', alignItems:'center', gap:6,
          padding:'9px 20px', background:'var(--accent)', color:'#fff',
          borderRadius:'var(--r-pill)', fontSize:13.5, fontWeight:700,
          textDecoration:'none',
        }}>
          <Icon name="calendar" size={14}/> {ctaLabel}
        </a>
      </div>
    </div>
  );
}

window.Card = Card;
window.CardHead = CardHead;
window.CardBody = CardBody;
window.Btn = Btn;
window.Badge = Badge;
window.StatDot = StatDot;
window.Avatar = Avatar;
window.Input = Input;
window.Textarea = Textarea;
window.Tabs = Tabs;
window.Seg = Seg;
window.Toggle = Toggle;
window.Progress = Progress;
window.Kbd = Kbd;
window.Eyebrow = Eyebrow;
window.Trend = Trend;
window.Hint = Hint;
window.LockedSection = LockedSection;
