/* Prism UI-kit primitives — renderable mirror of the design-system components
   (components/**). Kept inline so kit screens render without the compiled
   bundle. Consumers of the design system should import the real components
   from window.<Namespace> via _ds_bundle.js instead. */

const { useState } = React;

function Mesh({ intensity = 0.9, blur = 40 }) {
  return <div aria-hidden="true" className="prism-mesh" style={{ position: 'absolute', inset: '-20%', zIndex: 0, pointerEvents: 'none', opacity: intensity, filter: `blur(${blur}px) saturate(118%)` }} />;
}

function Logo({ size = 28, showWord = true, tone = 'ink', style = {} }) {
  const stroke = tone === 'light' ? '#FFFFFF' : '#0A0B0D';
  const word = tone === 'light' ? '#FFFFFF' : 'var(--ink-900)';
  const spec = tone === 'light' ? ['#A7A4F7', '#67D2A4', '#F8975B'] : ['#5B5BF0', '#138A5A', '#F8975B'];
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: size * 0.34, ...style }}>
      <svg width={size} height={size} viewBox="0 0 40 40" fill="none" role="img" aria-label="Prism">
        <path d="M20 7 L33 30 H7 Z" stroke={stroke} strokeWidth="2" strokeLinejoin="round" fill="none" />
        <path d="M2 20 H16" stroke={stroke} strokeWidth="2" strokeLinecap="round" />
        <path d="M24 21 L38 16.5" stroke={spec[0]} strokeWidth="2" strokeLinecap="round" />
        <path d="M24 23.5 L38 22" stroke={spec[1]} strokeWidth="2" strokeLinecap="round" />
        <path d="M24 26 L38 27.5" stroke={spec[2]} strokeWidth="2" strokeLinecap="round" />
      </svg>
      {showWord && <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: size * 0.74, letterSpacing: '-0.03em', color: word }}>Prism</span>}
    </span>
  );
}

function Button({ children, variant = 'primary', size = 'md', onClick, iconRight, style = {} }) {
  const [h, setH] = useState(false), [p, setP] = useState(false);
  const sizes = { sm: { padding: '8px 14px', fontSize: 13 }, md: { padding: '12px 20px', fontSize: 15 }, lg: { padding: '15px 26px', fontSize: 16 } };
  const v = {
    primary: { background: h ? 'var(--ink-700)' : 'var(--ink-900)', color: '#fff', border: '1px solid var(--ink-900)', boxShadow: h ? 'var(--shadow-md)' : 'var(--shadow-sm)' },
    glass: { background: h ? '#fff' : 'var(--glass-fill-strong)', color: 'var(--ink-800)', border: '1px solid var(--glass-border)', backdropFilter: 'blur(12px) saturate(140%)', WebkitBackdropFilter: 'blur(12px) saturate(140%)', boxShadow: 'var(--shadow-sm)' },
    ghost: { background: h ? 'var(--surface-sunken)' : 'transparent', color: 'var(--ink-700)', border: '1px solid var(--line-strong)' },
    spectrum: { background: h ? 'var(--accent-press)' : 'var(--accent)', color: '#fff', border: '1px solid var(--accent)', boxShadow: '0 4px 16px rgba(91,91,240,0.28)' },
    quiet: { background: h ? 'var(--surface-sunken)' : 'transparent', color: 'var(--ink-600)', border: '1px solid transparent' },
  }[variant];
  return (
    <button onClick={onClick} onMouseEnter={() => setH(true)} onMouseLeave={() => { setH(false); setP(false); }} onMouseDown={() => setP(true)} onMouseUp={() => setP(false)}
      style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8, fontFamily: 'var(--font-sans)', fontWeight: 600, letterSpacing: '-0.01em', lineHeight: 1, borderRadius: 'var(--r-pill)', cursor: 'pointer', whiteSpace: 'nowrap', transition: 'all var(--dur-base) var(--ease-out)', transform: p ? 'scale(0.975)' : 'scale(1)', ...sizes[size], ...v, ...style }}>
      {children}{iconRight}
    </button>
  );
}

function Badge({ children, variant = 'neutral', dot = false, style = {} }) {
  const v = {
    neutral: { background: 'var(--surface-sunken)', color: 'var(--ink-600)', border: '1px solid var(--line)' },
    glass: { background: 'var(--glass-fill-strong)', color: 'var(--ink-700)', border: '1px solid var(--glass-border)', backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)' },
    ink: { background: 'var(--ink-900)', color: '#fff', border: '1px solid var(--ink-900)' },
    positive: { background: 'var(--positive-tint)', color: 'var(--positive)', border: '1px solid transparent' },
    accent: { background: 'var(--accent-tint)', color: 'var(--accent)', border: '1px solid transparent' },
    live: { background: 'var(--positive-tint)', color: 'var(--positive)', border: '1px solid transparent' },
  }[variant];
  const dc = { live: 'var(--live)', positive: 'var(--positive)', accent: 'var(--accent)' }[variant] || 'var(--ink-400)';
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontFamily: 'var(--font-mono)', fontSize: 11.5, fontWeight: 500, letterSpacing: '0.08em', textTransform: 'uppercase', padding: '5px 10px', borderRadius: 'var(--r-pill)', ...v, ...style }}>
      {dot && <span style={{ width: 6, height: 6, borderRadius: '50%', background: dc, animation: variant === 'live' ? 'prism-pulse 1.8s var(--ease-out) infinite' : 'none' }} />}
      {children}
    </span>
  );
}

function GlassPanel({ children, strong = false, glow = false, radius = 'var(--r-xl)', padding = 'var(--sp-7)', style = {} }) {
  return (
    <div style={{ position: 'relative', background: strong ? 'var(--glass-fill-strong)' : 'var(--glass-fill)', backdropFilter: 'blur(var(--glass-blur)) saturate(var(--glass-saturate))', WebkitBackdropFilter: 'blur(var(--glass-blur)) saturate(var(--glass-saturate))', border: '1px solid var(--glass-border)', borderRadius: radius, padding, boxShadow: (glow ? 'var(--shadow-form)' : 'var(--shadow-lg)') + ', var(--shadow-inset)', ...style }}>
      {children}
    </div>
  );
}

function EmailCaptureForm({ layout = 'inline', placeholder = 'you@work.com', cta = 'Subscribe', note = "Free · weekly · unsubscribe anytime", accent = 'ink', onDark = false, className = '', onDone, style = {} }) {
  const [email, setEmail] = useState(''), [state, setState] = useState('idle'), [bh, setBh] = useState(false);
  const valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  const submit = (e) => { e.preventDefault(); if (!valid) { setState('error'); return; } setState('loading'); setTimeout(() => { setState('done'); onDone && onDone(email); }, 620); };
  const btnBg = accent === 'spectrum' ? (bh ? 'var(--accent-press)' : 'var(--accent)') : (bh ? 'var(--ink-700)' : 'var(--ink-900)');
  const err = state === 'error';
  if (state === 'done') {
    return (
      <div style={style}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, background: 'var(--positive-tint)', borderRadius: 'var(--r-pill)', padding: '14px 22px', fontFamily: 'var(--font-body)', color: 'var(--positive)', fontWeight: 600, fontSize: 15 }}>
          <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--positive)', color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, flex: 'none' }}>✓</span>
          You're in. Issue 048 lands Tuesday.
        </div>
      </div>
    );
  }
  const Note = () => (note || err) ? <p style={{ margin: '10px 4px 0', fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.04em', color: err ? 'var(--negative)' : 'var(--ink-500)' }}>{err ? 'Please enter a valid email address.' : note}</p> : null;
  if (layout === 'stacked') {
    return (
      <div style={style}>
        <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <input type="email" value={email} onChange={(e) => { setEmail(e.target.value); if (err) setState('idle'); }} placeholder={placeholder}
            style={{ width: '100%', boxSizing: 'border-box', fontFamily: 'var(--font-body)', fontSize: 16, color: 'var(--ink-800)', padding: '15px 18px', background: 'var(--surface)', border: `1px solid ${err ? 'var(--negative)' : 'var(--line-strong)'}`, borderRadius: 'var(--r-md)', outline: 'none' }} />
          <button type="submit" onMouseEnter={() => setBh(true)} onMouseLeave={() => setBh(false)} style={{ width: '100%', border: 'none', borderRadius: 'var(--r-md)', cursor: 'pointer', background: btnBg, color: '#fff', fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 16, padding: '15px 18px', transition: 'background var(--dur-base) var(--ease-out)' }}>{state === 'loading' ? 'Joining…' : cta}</button>
        </form>
        <Note />
      </div>
    );
  }
  const dBtnBg = onDark ? (bh ? 'rgba(255,255,255,0.9)' : '#fff') : btnBg;
  return (
    <div className={className} style={style}>
      <form onSubmit={submit} style={{ display: 'flex', alignItems: 'center', gap: 8, background: onDark ? 'rgba(255,255,255,0.07)' : 'var(--surface)', backdropFilter: onDark ? 'blur(12px) saturate(140%)' : 'none', WebkitBackdropFilter: onDark ? 'blur(12px) saturate(140%)' : 'none', borderRadius: 'var(--r-pill)', padding: '7px 7px 7px 20px', border: `1px solid ${err ? 'var(--negative)' : (onDark ? 'rgba(255,255,255,0.18)' : 'var(--line)')}`, boxShadow: onDark ? 'var(--shadow-inset)' : 'var(--shadow-md)' }}>
        <input type="email" value={email} onChange={(e) => { setEmail(e.target.value); if (err) setState('idle'); }} placeholder={placeholder}
          style={{ flex: 1, minWidth: 0, border: 'none', outline: 'none', background: 'transparent', fontFamily: 'var(--font-body)', fontSize: 16, color: onDark ? '#fff' : 'var(--ink-800)' }} />
        <button type="submit" onMouseEnter={() => setBh(true)} onMouseLeave={() => setBh(false)} style={{ flex: 'none', border: 'none', borderRadius: 'var(--r-pill)', cursor: 'pointer', background: dBtnBg, color: onDark ? 'var(--ink-900)' : '#fff', fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 15, padding: '12px 22px', transition: 'background var(--dur-base) var(--ease-out)', whiteSpace: 'nowrap' }}>{state === 'loading' ? 'Joining…' : cta}</button>
      </form>
      <Note />
    </div>
  );
}

function AvatarStack({ count = 5, size = 36, label = '', tone = 'light', style = {} }) {
  const palette = ['#C7C2F2', '#B6D2F4', '#BCEBD6', '#F8CDB0', '#F4C3DA'];
  const ring = tone === 'light' ? 'var(--surface)' : 'var(--ink-900)';
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 12, ...style }}>
      <div style={{ display: 'flex' }}>
        {Array.from({ length: count }).map((_, i) => (
          <div key={i} style={{ width: size, height: size, borderRadius: '50%', marginLeft: i === 0 ? 0 : -size * 0.32, border: `2px solid ${ring}`, background: palette[i % palette.length], display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: size * 0.36, color: 'rgba(10,11,13,0.55)', zIndex: count - i, boxShadow: 'var(--shadow-xs)' }}>{String.fromCharCode(65 + i)}</div>
        ))}
      </div>
      {label && <span style={{ fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 500, color: tone === 'light' ? 'var(--ink-600)' : 'var(--on-ink-mid)' }}>{label}</span>}
    </div>
  );
}

function StatPill({ value, label, delta = null }) {
  const up = delta && !String(delta).startsWith('-');
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 28, letterSpacing: '-0.02em', color: 'var(--ink-900)' }}>{value}</span>
        {delta && <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600, color: up ? 'var(--positive)' : 'var(--negative)' }}>{up ? '▲' : '▼'} {String(delta).replace('-', '')}</span>}
      </div>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-500)' }}>{label}</span>
    </div>
  );
}

function IssueCard({ issue, date, title, excerpt, readTime, onClick }) {
  const [h, setH] = useState(false);
  return (
    <div onClick={onClick} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', padding: 'var(--sp-6)', boxShadow: h ? 'var(--shadow-lg)' : 'var(--shadow-sm)', transform: h ? 'translateY(-2px)' : 'none', transition: 'all var(--dur-base) var(--ease-out)', cursor: onClick ? 'pointer' : 'default' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-500)' }}>{issue}</span>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-400)' }}>{date}</span>
      </div>
      <h3 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, lineHeight: 1.2, letterSpacing: '-0.02em', color: 'var(--ink-900)' }}>{title}</h3>
      {excerpt && <p style={{ margin: '10px 0 0', fontFamily: 'var(--font-body)', fontSize: 15, lineHeight: 1.55, color: 'var(--ink-600)' }}>{excerpt}</p>}
      {readTime && <p style={{ margin: '16px 0 0', fontFamily: 'var(--font-mono)', fontSize: 11.5, color: 'var(--ink-400)', letterSpacing: '0.06em' }}>{readTime}</p>}
    </div>
  );
}

Object.assign(window, { Mesh, Logo, Button, Badge, GlassPanel, EmailCaptureForm, AvatarStack, StatPill, IssueCard });
