// Shared UI primitives for buildwithmodels.com
// Terminal Hybrid direction + brutalist stat strip + tag pills

const BWM = {
  // — theme access — all sites read from CSS vars so Tweaks can swap live
  useTheme: () => {
    const [, force] = React.useReducer(x => x + 1, 0);
    React.useEffect(() => {
      const obs = new MutationObserver(force);
      obs.observe(document.documentElement, { attributes: true, attributeFilter: ['style', 'data-theme', 'data-density'] });
      return () => obs.disconnect();
    }, []);
  },
};

// ASCII-ish divider
const Divider = ({ width = 120 }) => (
  <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--rule)', whiteSpace: 'pre', overflow: 'hidden', lineHeight: 1 }}>
    {'─'.repeat(width)}
  </div>
);

// Top bar: tmux-style status + traffic lights
const TopBar = ({ path = '~', current }) => {
  const [now, setNow] = React.useState(() => new Date());
  React.useEffect(() => {
    const t = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(t);
  }, []);
  const hh = String(now.getHours()).padStart(2, '0');
  const mm = String(now.getMinutes()).padStart(2, '0');
  return (
  <div style={{
    display: 'flex', alignItems: 'center', gap: 10, padding: '10px 20px',
    background: 'var(--ink-2)', borderBottom: '1px solid var(--rule)',
    fontFamily: 'var(--mono)', fontSize: 11,
  }}>
    <div style={{ width: 10, height: 10, borderRadius: 5, background: '#b85c3a' }} />
    <div style={{ width: 10, height: 10, borderRadius: 5, background: 'var(--brass)' }} />
    <div style={{ width: 10, height: 10, borderRadius: 5, background: '#7a8f5a' }} />
    <span style={{ color: 'var(--fg-dimmer)', marginLeft: 16 }}>
      mike@buildwithmodels <span style={{ color: 'var(--brass)' }}>{path}</span> $ {current}
    </span>
    <span style={{ flex: 1 }} />
    <span style={{ color: 'var(--fg-dimmer)' }}>tmux 0:shell* ·  {hh}:{mm} · 87% ·  UTF-8</span>
  </div>
  );
};

// Main nav — prompt-style with keyboard hints
const SiteNav = ({ current, onNav }) => {
  const items = [
    ['h', 'home', 'home'],
    ['w', 'writing', 'writing'],
    ['p', 'projects', 'projects'],
    ['a', 'about', 'about'],
    ['r', 'rss', 'rss'],
  ];
  return (
    <nav style={{
      display: 'flex', alignItems: 'center', gap: 0, padding: '14px 20px',
      borderBottom: '1px solid var(--rule)', fontFamily: 'var(--mono)', fontSize: 12,
      flexWrap: 'wrap',
    }}>
      <a onClick={() => onNav && onNav('home')} style={{
        color: 'var(--fg)', fontWeight: 700, letterSpacing: '-0.02em', marginRight: 24,
        display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', textDecoration: 'none',
      }}>
        <span style={{ color: 'var(--brass)' }}>▮</span>
        <span className="bwm-shimmer">buildwithmodels</span><span style={{ color: 'var(--fg-dimmer)' }}>.com</span>
      </a>
      <span style={{ flex: 1 }} />
      <div style={{ display: 'flex', gap: 4 }}>
        {items.map(([k, label, id]) => (
          <a key={id} onClick={() => onNav && onNav(id)}
            style={{
              padding: '4px 10px', cursor: 'pointer', textDecoration: 'none',
              color: current === id ? 'var(--brass)' : 'var(--fg-dim)',
              border: current === id ? '1px solid var(--brass)' : '1px solid transparent',
            }}>
            <span style={{ color: 'var(--fg-dimmer)', marginRight: 6 }}>[{k}]</span>{label}
          </a>
        ))}
      </div>
    </nav>
  );
};

// Brutalist stat strip — "bento" card with tabular rows + sparkline feel
const StatStrip = ({ stats }) => (
  <div style={{
    fontFamily: 'var(--mono)',
    borderTop: '1px solid var(--rule)', borderBottom: '1px solid var(--rule)',
    background: 'linear-gradient(180deg, var(--ink-2), var(--ink))',
  }}>
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '10px 20px', borderBottom: '1px dashed var(--rule)',
      fontSize: 10, color: 'var(--fg-dimmer)', letterSpacing: '0.12em', textTransform: 'uppercase',
    }}>
      <span style={{ color: 'var(--brass)' }}>▸</span>
      <span>$ stat --summary</span>
      <span style={{ flex: 1, height: 1, background: 'var(--rule)' }} />
      <span style={{ color: 'var(--brass)' }}>live</span>
      <span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: 3, background: '#7a8f5a', animation: 'bwmBlink 1.4s step-end infinite' }} />
    </div>
    <div style={{ display: 'grid', gridTemplateColumns: `repeat(${stats.length}, 1fr)` }}>
      {stats.map((s, i) => (
        <div key={s[0]} style={{
          padding: '18px 20px',
          borderRight: i < stats.length - 1 ? '1px dashed var(--rule)' : 'none',
          display: 'flex', flexDirection: 'column', gap: 6,
        }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
            <span style={{ color: 'var(--fg-dimmer)', fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
              {String(i + 1).padStart(2, '0')} · {s[0]}
            </span>
            <span style={{ color: 'var(--brass)', fontSize: 9 }}>{s[2] || '↑'}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
            <span style={{ color: 'var(--brass)', fontSize: 28, fontWeight: 700, letterSpacing: '-0.03em', lineHeight: 1 }}>{s[1]}</span>
            {s[3] && <span style={{ color: 'var(--fg-dimmer)', fontSize: 10 }}>{s[3]}</span>}
          </div>
          <div style={{ display: 'flex', gap: 2, marginTop: 4 }}>
            {Array.from({ length: 16 }).map((_, j) => {
              const seed = (i * 7 + j * 3) % 11;
              const h = 4 + seed;
              return <div key={j} style={{ width: 3, height: h, background: j > 11 ? 'var(--brass)' : 'var(--rule-strong)' }} />;
            })}
          </div>
        </div>
      ))}
    </div>
  </div>
);

// Tag pill
const Tag = ({ children, brass = false }) => (
  <span style={{
    fontFamily: 'var(--mono)', fontSize: 10,
    color: brass ? 'var(--brass)' : 'var(--fg-dim)',
    border: brass ? '1px solid var(--brass)' : '1px solid var(--rule)',
    padding: '2px 8px', display: 'inline-block',
  }}>{children}</span>
);

const LabBadge = () => <Tag brass>◉ lab</Tag>;

// Section header with filepath + count
const SectionHead = ({ cmd, count, file }) => (
  <div style={{
    display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20,
    fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--fg-dimmer)',
    letterSpacing: '0.08em', textTransform: 'uppercase',
  }}>
    <span style={{ color: 'var(--brass)' }}>▸</span>
    <span>{cmd}</span>
    <span style={{ flex: 1, height: 1, background: 'var(--rule)' }} />
    {count != null && <span style={{ color: 'var(--brass)' }}>[{String(count).padStart(2, '0')}]</span>}
    {file && <span style={{ color: 'var(--fg-dimmer)', textTransform: 'none', letterSpacing: '0.04em' }}>{file}</span>}
  </div>
);

// Site footer
const SiteFoot = () => (
  <footer style={{
    padding: '20px 24px', borderTop: '1px solid var(--rule)',
    fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--fg-dimmer)',
    display: 'flex', justifyContent: 'space-between',
  }}>
    <span>exit status: 0 · © 2026 mike jenkins · built with astro · hosted on github pages</span>
    <span style={{ color: 'var(--brass)' }}>▮</span>
  </footer>
);

// Code block with terminal-style chrome + copy button
const CodeBlock = ({ filename, language, code, style }) => {
  const [copied, setCopied] = React.useState(false);
  const codeStyle = style || 'traditional';
  const highlight = (txt) => {
    // naive python/shell highlight — good enough for demo
    return txt
      .replace(/(#[^\n]*)/g, '<span style="color:var(--fg-dimmer)">$1</span>')
      .replace(/("[^"]*"|'[^']*')/g, '<span style="color:#7a8f5a">$1</span>')
      .replace(/\b(from|import|def|return|class|if|else|for|in|await|async|with|as)\b/g, '<span style="color:var(--brass)">$1</span>')
      .replace(/\b(True|False|None)\b/g, '<span style="color:#b85c3a">$1</span>');
  };
  const copy = () => { navigator.clipboard?.writeText(code); setCopied(true); setTimeout(() => setCopied(false), 1400); };

  if (codeStyle === 'terminal') {
    return (
      <div style={{ fontFamily: 'var(--mono)', fontSize: 12, background: 'var(--ink-3)', border: '1px solid var(--rule)', marginBottom: 20 }}>
        <div style={{ display: 'flex', alignItems: 'center', padding: '10px 14px', borderBottom: '1px solid var(--rule)', background: 'var(--ink-2)', gap: 8 }}>
          <div style={{ width: 8, height: 8, borderRadius: 4, background: '#b85c3a' }} />
          <div style={{ width: 8, height: 8, borderRadius: 4, background: 'var(--brass)' }} />
          <div style={{ width: 8, height: 8, borderRadius: 4, background: '#7a8f5a' }} />
          <span style={{ marginLeft: 14, color: 'var(--fg-dim)', fontSize: 11 }}>{filename}</span>
          <span style={{ flex: 1 }} />
          <button onClick={copy} style={{ background: 'transparent', border: '1px solid var(--rule)', color: 'var(--fg-dim)', fontFamily: 'var(--mono)', fontSize: 10, padding: '2px 8px', cursor: 'pointer' }}>
            {copied ? '✓ copied' : 'copy'}
          </button>
        </div>
        <pre style={{ margin: 0, padding: 16, overflow: 'auto', color: 'var(--fg)', lineHeight: 1.7 }}
          dangerouslySetInnerHTML={{ __html: highlight(code) }} />
      </div>
    );
  }

  if (codeStyle === 'minimal') {
    return (
      <div style={{ fontFamily: 'var(--mono)', fontSize: 12, background: 'var(--ink-3)', marginBottom: 20, padding: 16, position: 'relative' }}>
        <button onClick={copy} style={{ position: 'absolute', top: 8, right: 8, background: 'transparent', border: 'none', color: 'var(--fg-dimmer)', fontFamily: 'var(--mono)', fontSize: 10, cursor: 'pointer', padding: 4 }}>
          {copied ? '✓' : '⎘'}
        </button>
        <pre style={{ margin: 0, color: 'var(--fg)', lineHeight: 1.7 }} dangerouslySetInnerHTML={{ __html: highlight(code) }} />
      </div>
    );
  }

  // traditional
  return (
    <div style={{ fontFamily: 'var(--mono)', fontSize: 12, background: 'var(--ink-3)', border: '1px solid var(--rule)', marginBottom: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', padding: '8px 14px', borderBottom: '1px solid var(--rule)', gap: 12 }}>
        <span style={{ color: 'var(--brass)', fontSize: 10, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{language}</span>
        <span style={{ color: 'var(--fg-dim)', fontSize: 11 }}>{filename}</span>
        <span style={{ flex: 1 }} />
        <button onClick={copy} style={{ background: 'transparent', border: 'none', color: 'var(--fg-dim)', fontFamily: 'var(--mono)', fontSize: 10, cursor: 'pointer' }}>
          {copied ? '✓ copied' : 'copy'}
        </button>
      </div>
      <pre style={{ margin: 0, padding: 16, overflow: 'auto', color: 'var(--fg)', lineHeight: 1.7, counterReset: 'line' }}
        dangerouslySetInnerHTML={{ __html: highlight(code) }} />
    </div>
  );
};

// Standard page shell — every page routes content through this.
// Top bar + nav are full-bleed; everything else is constrained to SITE_MAX.
const SITE_MAX = 1760;
const SITE_PAD_X = 48;
const PageShell = ({ topPath, topCurrent, nav, onNav, children, fullBleedChildren }) => (
  <div style={{ background: 'var(--ink)', minHeight: '100vh' }}>
    <TopBar path={topPath} current={topCurrent} />
    <SiteNav current={nav} onNav={onNav} />
    {fullBleedChildren}
    <div style={{ maxWidth: SITE_MAX, margin: '0 auto', padding: `0 ${SITE_PAD_X}px` }}>
      {children}
    </div>
    <SiteFoot />
  </div>
);

Object.assign(window, { BWM, Divider, TopBar, SiteNav, StatStrip, Tag, LabBadge, SectionHead, SiteFoot, CodeBlock, PageShell, SITE_MAX, SITE_PAD_X });
