// ui-primitives.jsx — OnboardIQ component library, on canvas

// ─────────────────────────────────────────────────────────────
// Reusable primitives (used both in the gallery AND the dashboard)
// ─────────────────────────────────────────────────────────────

const Btn = ({ kind = "primary", size = "md", icon, children, full, disabled, style, ...rest }) => {
  const sz = size === "sm" ? { padY: 5, padX: 10, fs: 12 } :
             size === "lg" ? { padY: 10, padX: 16, fs: 14 } :
                             { padY: 7, padX: 12, fs: 13 };
  const base = {
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
    fontFamily: 'var(--sans)', fontWeight: 500, fontSize: sz.fs,
    padding: `${sz.padY}px ${sz.padX}px`,
    borderRadius: 'var(--r-2)',
    border: '1px solid transparent',
    cursor: disabled ? 'not-allowed' : 'pointer',
    transition: 'background 120ms, border-color 120ms, color 120ms',
    letterSpacing: '-0.005em',
    width: full ? '100%' : 'auto',
    opacity: disabled ? 0.5 : 1,
    whiteSpace: 'nowrap',
    lineHeight: 1.1,
  };
  const kinds = {
    primary: { background: 'var(--ink-900)', color: 'var(--paper-50)' },
    secondary: { background: 'var(--paper-50)', color: 'var(--ink-900)', borderColor: 'var(--ink-300)' },
    ghost: { background: 'transparent', color: 'var(--ink-700)' },
    amber: { background: 'var(--amber-500)', color: 'var(--ink-900)' },
    danger: { background: 'var(--paper-50)', color: 'var(--red-500)', borderColor: 'var(--red-100)' },
    link: { background: 'transparent', color: 'var(--ink-900)', textDecoration: 'underline', textUnderlineOffset: 3, padding: 0, border: 'none' },
  };
  return (
    <button {...rest} disabled={disabled} style={{ ...base, ...kinds[kind], ...style }}>
      {icon && <Icon name={icon} size={14} stroke={1.7} />}
      {children}
    </button>
  );
};

const Input = ({ value, placeholder, prefix, suffix, mono, style, ...rest }) => (
  <div style={{
    display: 'inline-flex', alignItems: 'center', gap: 6,
    padding: '7px 10px',
    border: '1px solid var(--paper-300)',
    background: 'var(--paper-50)',
    borderRadius: 'var(--r-2)',
    fontSize: 13,
    ...style,
  }}>
    {prefix && <span style={{ color: 'var(--ink-500)', display: 'flex' }}>{prefix}</span>}
    <input
      defaultValue={value}
      placeholder={placeholder}
      {...rest}
      style={{
        border: 'none', outline: 'none', background: 'transparent',
        flex: 1, fontFamily: mono ? 'var(--mono)' : 'var(--sans)',
        fontSize: mono ? 12 : 13, color: 'var(--ink-900)', width: '100%',
        padding: 0, lineHeight: 1.2,
      }}
    />
    {suffix && <span style={{ color: 'var(--ink-500)', fontSize: 11, fontFamily: 'var(--mono)' }}>{suffix}</span>}
  </div>
);

const Pill = ({ kind = "neutral", children, dot, mono = true }) => {
  const styles = {
    neutral: { bg: 'var(--paper-200)', fg: 'var(--ink-700)', dotColor: 'var(--ink-500)' },
    success: { bg: 'var(--green-100)', fg: 'var(--green-700)', dotColor: 'var(--green-500)' },
    warn:    { bg: 'var(--amber-100)', fg: 'var(--amber-700)', dotColor: 'var(--amber-600)' },
    danger:  { bg: 'var(--red-100)',   fg: 'var(--red-700)',   dotColor: 'var(--red-500)' },
    info:    { bg: 'var(--blue-100)',  fg: 'var(--blue-700)',  dotColor: 'var(--blue-500)' },
    slate:   { bg: 'var(--slate-100)', fg: 'var(--slate-700)', dotColor: 'var(--slate-500)' },
    ink:     { bg: 'var(--ink-900)',   fg: 'var(--paper-50)',  dotColor: 'var(--amber-500)' },
  }[kind];
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '2px 8px',
      background: styles.bg, color: styles.fg,
      borderRadius: 'var(--r-pill)',
      fontFamily: mono ? 'var(--mono)' : 'var(--sans)',
      fontSize: 10.5, fontWeight: 500,
      letterSpacing: '0.02em',
      lineHeight: 1.5,
      whiteSpace: 'nowrap',
    }}>
      {dot && <span className="oiq-dot" style={{ background: styles.dotColor }} />}
      {children}
    </span>
  );
};

const StepIcon = ({ type, size = 16 }) => {
  // Small symbolic markers per step type — used in step lists.
  const props = { width: size, height: size, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: 1.4, strokeLinecap: "square" };
  const variants = {
    doc:    <svg {...props}><rect x="3" y="2" width="9" height="12"/><path d="M5 6h5M5 9h5M5 12h3"/></svg>,
    sig:    <svg {...props}><path d="M2 12c1-1 2-4 3.5-4S6.5 11 8 11s2-6 3.5-6 1 3 2.5 3"/><path d="M2 14h12"/></svg>,
    form:   <svg {...props}><rect x="2" y="2" width="12" height="12"/><path d="M5 6h6M5 9h6M5 12h3"/></svg>,
    train:  <svg {...props}><path d="M2 5l6-2 6 2-6 2z"/><path d="M5 6v3c0 1 1.3 1.5 3 1.5s3-.5 3-1.5V6"/></svg>,
    eq:     <svg {...props}><rect x="2" y="3" width="12" height="8"/><path d="M1 13h14"/></svg>,
    access: <svg {...props}><rect x="3" y="7" width="10" height="7"/><path d="M5 7V5a3 3 0 016 0v2"/></svg>,
    bg:     <svg {...props}><circle cx="7" cy="7" r="4"/><path d="M10 10l4 4"/></svg>,
    ev:     <svg {...props}><rect x="2" y="3" width="12" height="10"/><path d="M5 8l2 2 4-4"/></svg>,
    cl:     <svg {...props}><path d="M8 2l5 2v4c0 3-2 5-5 5.5C5 13 3 11 3 8V4z"/><path d="M6 8l1.5 1.5L11 6"/></svg>,
    check:  <svg {...props}><path d="M3 8l3 3 7-7"/></svg>,
    buddy:  <svg {...props}><circle cx="6" cy="6" r="2"/><path d="M2 13c0-2 2-3.5 4-3.5s4 1.5 4 3.5"/><circle cx="11" cy="5" r="1.5"/></svg>,
    task:   <svg {...props}><rect x="2" y="2" width="12" height="12"/><path d="M5 8l2 2 4-4"/></svg>,
  };
  return variants[type] || null;
};

const Avatar = ({ name, size = 28, color }) => {
  // Initials avatar — never AI-generated headshots.
  const initials = name.split(" ").map(p => p[0]).slice(0, 2).join("");
  const colors = ['#3F7A5A', '#B07B1F', '#3D5878', '#98353F', '#647686', '#8B6017'];
  const c = color || colors[name.charCodeAt(0) % colors.length];
  return (
    <div style={{
      width: size, height: size, borderRadius: 'var(--r-1)',
      background: c, color: '#FBF9F4',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'var(--mono)', fontSize: size * 0.36, fontWeight: 500,
      letterSpacing: '0.04em', flexShrink: 0,
    }}>{initials.toUpperCase()}</div>
  );
};

const Progress = ({ value, total, size = "md", showLabel }) => {
  const pct = Math.min(100, Math.max(0, (value / total) * 100));
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
      <div style={{
        flex: 1, height: size === "sm" ? 4 : 6,
        background: 'var(--paper-200)',
        borderRadius: 999,
        overflow: 'hidden',
        position: 'relative',
      }}>
        <div style={{
          width: `${pct}%`, height: '100%',
          background: 'var(--ink-800)',
        }} />
      </div>
      {showLabel && (
        <span className="oiq-mono" style={{ fontSize: 10.5, color: 'var(--ink-600)', minWidth: 36, textAlign: 'right' }}>
          {value}/{total}
        </span>
      )}
    </div>
  );
};

// Segmented control
const Seg = ({ value, options, onChange }) => (
  <div style={{
    display: 'inline-flex', padding: 2,
    border: '1px solid var(--paper-300)', borderRadius: 'var(--r-2)',
    background: 'var(--paper-50)',
  }}>
    {options.map(o => (
      <button key={o.value || o} onClick={() => onChange?.(o.value || o)} style={{
        padding: '4px 10px',
        fontFamily: 'var(--sans)', fontSize: 12, fontWeight: 500,
        background: value === (o.value || o) ? 'var(--ink-900)' : 'transparent',
        color: value === (o.value || o) ? 'var(--paper-50)' : 'var(--ink-700)',
        border: 'none', borderRadius: 'var(--r-1)', cursor: 'pointer',
        letterSpacing: '-0.005em',
      }}>{o.label || o}</button>
    ))}
  </div>
);

// Surface card
const Surface = ({ children, style, ...rest }) => (
  <div {...rest} style={{
    background: 'var(--paper-50)',
    border: '1px solid var(--paper-300)',
    borderRadius: 'var(--r-3)',
    ...style,
  }}>{children}</div>
);

// ─────────────────────────────────────────────────────────────
// PRIMITIVES GALLERY CARDS
// ─────────────────────────────────────────────────────────────

function ControlsCard() {
  const [seg, setSeg] = React.useState("active");
  return (
    <div className="oiq" style={{ padding: 32, height: '100%', background: 'var(--paper-50)', display: 'flex', flexDirection: 'column', gap: 16 }}>
      <window.OiqHeader eyebrow="07 · Controls" title="Buttons, inputs, segmented" subtitle="One ink primary. Amber reserved for amber-meaning moments." />

      <Section title="Buttons">
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
          <Btn kind="primary">Start onboarding</Btn>
          <Btn kind="primary" icon="plus">New from template</Btn>
          <Btn kind="secondary">Cancel</Btn>
          <Btn kind="secondary" icon="upload">Import CSV</Btn>
          <Btn kind="amber" icon="shield">Issue clearance prep</Btn>
          <Btn kind="danger" icon="x">Void envelope</Btn>
          <Btn kind="ghost">View audit log</Btn>
          <Btn kind="primary" size="sm">sm</Btn>
          <Btn kind="primary" size="lg">lg</Btn>
          <Btn kind="primary" disabled>Disabled</Btn>
        </div>
      </Section>

      <Section title="Inputs">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          <Input placeholder="Search documents, onboardings, people" prefix={<Icon name="search" size={14} />} suffix="⌘K" />
          <Input value="case_e-verify_82h11k" mono prefix={<Icon name="lock" size={14} />} />
          <Input placeholder="daniel.okafor@meridian.fed" />
          <Input value="$8.00 / onboarding" suffix="USD" />
        </div>
      </Section>

      <Section title="Segmented">
        <Seg value={seg} onChange={setSeg} options={[
          { value: "active", label: "Active · 12" },
          { value: "pending", label: "Pending · 4" },
          { value: "complete", label: "Complete · 87" },
          { value: "archived", label: "Archived" },
        ]} />
      </Section>

      <Section title="Select · combo">
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <FauxSelect label="Hire type" value="W-2 employee" />
          <FauxSelect label="Department" value="Engineering" />
          <FauxSelect label="Location" value="Arlington, VA" />
          <FauxSelect label="Clearance" value="TS pending" />
        </div>
      </Section>
    </div>
  );
}

function FauxSelect({ label, value }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: '6px 10px',
      border: '1px solid var(--paper-300)', background: 'var(--paper-50)',
      borderRadius: 'var(--r-2)',
    }}>
      <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--ink-500)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{label}</span>
      <span style={{ fontSize: 12.5, color: 'var(--ink-900)' }}>{value}</span>
      <Icon name="chevron-d" size={12} />
    </div>
  );
}

function Section({ title, children }) {
  return (
    <div>
      <div className="oiq-eyebrow" style={{ marginBottom: 8 }}>{title}</div>
      {children}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────

function StatusCard() {
  return (
    <div className="oiq" style={{ padding: 32, height: '100%', background: 'var(--paper-50)', display: 'flex', flexDirection: 'column', gap: 16 }}>
      <window.OiqHeader eyebrow="08 · Status" title="Pills, dots, progress" subtitle="Status colors carry meaning. Amber is action; warn is its own."/>

      <Section title="Status pills">
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          <Pill kind="success" dot>countersigned</Pill>
          <Pill kind="warn" dot>section-2 due</Pill>
          <Pill kind="danger" dot>e-verify · tnc</Pill>
          <Pill kind="info" dot>polygraph scheduled</Pill>
          <Pill kind="slate" dot>sub · BlueRidge LLC</Pill>
          <Pill kind="neutral" dot>1099 contractor</Pill>
          <Pill kind="ink" dot>TS · interim</Pill>
        </div>
      </Section>

      <Section title="Step type markers">
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          {[
            ["doc","Documents"], ["sig","E-signature"], ["form","Form fill"],
            ["train","Training"], ["eq","Equipment"], ["access","System access"],
            ["bg","Background check"], ["ev","E-Verify"], ["cl","Clearance"],
            ["buddy","Buddy intro"], ["task","Custom task"], ["check","Check-in"],
          ].map(([k, l]) => (
            <span key={k} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 8px', border: '1px solid var(--paper-300)', borderRadius: 'var(--r-1)', background: 'var(--paper-100)' }}>
              <StepIcon type={k} /> <span style={{ fontSize: 11.5, color: 'var(--ink-700)' }}>{l}</span>
            </span>
          ))}
        </div>
      </Section>

      <Section title="Progress">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ fontSize: 12, color: 'var(--ink-700)' }}>Daniel Okafor · Cloud Engineer</span>
              <span className="oiq-mono" style={{ fontSize: 11, color: 'var(--ink-500)' }}>day 3 / 14</span>
            </div>
            <Progress value={7} total={18} showLabel />
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ fontSize: 12, color: 'var(--ink-700)' }}>Priya Subramanian · Sr Contracts</span>
              <span className="oiq-mono" style={{ fontSize: 11, color: 'var(--ink-500)' }}>day 7 / 14</span>
            </div>
            <Progress value={14} total={18} showLabel />
          </div>
        </div>
      </Section>

      <Section title="Avatars · people">
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          {["Daniel Okafor","Priya Subramanian","Marcus Reed","Jenna Whitfield","Theo Bramwell","Aisha Karam"].map(n => (
            <Avatar key={n} name={n} size={32} />
          ))}
          <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 32, height: 32, border: '1px dashed var(--paper-300)', borderRadius: 'var(--r-1)', color: 'var(--ink-500)', fontFamily: 'var(--mono)', fontSize: 11 }}>+6</span>
        </div>
      </Section>
    </div>
  );
}

// Export
Object.assign(window, {
  Btn, Input, Pill, StepIcon, Avatar, Progress, Seg, Surface, FauxSelect,
  ControlsCard, StatusCard,
});
