/* global React */
const { useState, useRef } = React;

// Splits code into lines and flags which ones are comments (line // or block /* */)
// so we can tint them without a full tokenizer.
function classifyLines(code) {
  const lines = code.replace(/\s+$/, '').split('\n');
  let inBlock = false;
  return lines.map((text) => {
    const trimmed = text.trim();
    let comment = false;
    if (inBlock) {
      comment = true;
      if (trimmed.includes('*/')) inBlock = false;
    } else if (trimmed.startsWith('/*')) {
      comment = true;
      if (!trimmed.includes('*/')) inBlock = true;
    } else if (trimmed.startsWith('//')) {
      comment = true;
    } else if (trimmed.startsWith('*')) {
      comment = true;
    }
    return { text, comment };
  });
}

function CodeBlock({ code, filename = 'sketch.ino', lang = 'Arduino / C++', caption }) {
  const [expanded, setExpanded] = useState(false);
  const [copied, setCopied] = useState(false);
  const lines = classifyLines(code || '');

  const copy = () => {
    try {
      navigator.clipboard.writeText(code);
      setCopied(true);
      setTimeout(() => setCopied(false), 1600);
    } catch (e) { /* clipboard blocked — ignore */ }
  };

  const chip = {
    fontFamily: 'var(--font-mono)', fontSize: '10px', textTransform: 'uppercase',
    letterSpacing: '0.14em', color: 'var(--fg-4)',
  };
  const btn = {
    display: 'inline-flex', alignItems: 'center', gap: '7px', cursor: 'pointer',
    fontFamily: 'var(--font-mono)', fontSize: '11px', letterSpacing: '0.08em', textTransform: 'uppercase',
    color: 'var(--fg-2)', background: 'transparent', border: '1px solid var(--line-strong)',
    borderRadius: 'var(--radius-pill, 999px)', padding: '7px 14px',
    transition: 'color var(--dur-fast) var(--ease-out), border-color var(--dur-fast) var(--ease-out), background var(--dur-fast) var(--ease-out)',
  };

  return (
    <figure style={{ margin: 0, maxWidth: '1000px', marginLeft: 'auto', marginRight: 'auto', width: '100%' }}>
      <div className="am-code" style={{
        border: '1px solid var(--line)', borderRadius: 'var(--radius-lg)', overflow: 'hidden',
        background: 'var(--bg-card)', boxShadow: 'var(--shadow-md)',
      }}>
        {/* Title bar */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '16px',
          padding: '13px 16px', borderBottom: '1px solid var(--line)', background: 'var(--bg-input)',
          flexWrap: 'wrap',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px', minWidth: 0 }}>
            <span aria-hidden="true" style={{ display: 'inline-flex', gap: '6px' }}>
              <span style={{ width: 10, height: 10, borderRadius: '50%', background: 'rgba(255,255,255,0.16)' }}></span>
              <span style={{ width: 10, height: 10, borderRadius: '50%', background: 'rgba(255,255,255,0.16)' }}></span>
              <span style={{ width: 10, height: 10, borderRadius: '50%', background: 'rgba(255,255,255,0.16)' }}></span>
            </span>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: '12.5px', color: 'var(--fg-1)', whiteSpace: 'nowrap' }}>{filename}</span>
            <span style={chip}>{lang}</span>
            <span style={chip}>· {lines.length} lines</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <button className="am-code-btn" style={btn} onClick={() => setExpanded((v) => !v)}>
              {expanded ? 'Collapse ↑' : 'Expand ↓'}
            </button>
          </div>
        </div>

        {/* Code body */}
        <div style={{ position: 'relative' }}>
          <div style={{
            maxHeight: expanded ? '72vh' : '300px',
            overflowY: expanded ? 'auto' : 'hidden',
            overflowX: 'auto',
            transition: 'max-height var(--dur-slow, 480ms) var(--ease-emph)',
          }}>
            <pre style={{ margin: 0, padding: '18px 0', fontFamily: 'var(--font-mono)', fontSize: '12.5px', lineHeight: 1.65 }}>
              <code style={{ display: 'block', minWidth: 'max-content' }}>
                {lines.map((ln, i) => (
                  <div key={i} style={{ display: 'flex', gap: '18px', padding: '0 20px' }}>
                    <span aria-hidden="true" style={{
                      width: '30px', flex: '0 0 auto', textAlign: 'right', userSelect: 'none',
                      color: 'var(--fg-5, #4a4e57)', opacity: 0.7,
                    }}>{i + 1}</span>
                    <span style={{
                      whiteSpace: 'pre', color: ln.comment ? 'var(--fg-4)' : 'var(--fg-1)',
                      fontStyle: ln.comment ? 'italic' : 'normal',
                    }}>{ln.text || ' '}</span>
                  </div>
                ))}
              </code>
            </pre>
          </div>

          {/* Fade + expand affordance when collapsed */}
          {!expanded && (
            <button onClick={() => setExpanded(true)} style={{
              position: 'absolute', left: 0, right: 0, bottom: 0, height: '128px',
              display: 'flex', alignItems: 'flex-end', justifyContent: 'center', paddingBottom: '16px',
              border: 'none', cursor: 'pointer',
              background: 'linear-gradient(180deg, rgba(20,21,25,0) 0%, var(--bg-card) 82%)',
            }}>
              <span style={{ ...btn, background: 'var(--bg-input)' }}>Expand code ↓</span>
            </button>
          )}
        </div>
      </div>
      {caption && (
        <figcaption style={{
          fontFamily: 'var(--font-mono)', fontSize: 'var(--type-micro)', letterSpacing: '0.04em',
          color: 'var(--fg-4)', textTransform: 'uppercase', textAlign: 'center', marginTop: '14px',
        }}>{caption}</figcaption>
      )}
    </figure>
  );
}

window.CodeBlock = CodeBlock;
