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

// ─────────────────────────────────────────────────────────────────
// Button
// ─────────────────────────────────────────────────────────────────
function Button({
  variant = 'primary',
  size = 'md',
  fullWidth = false,
  loading = false,
  icon,
  iconRight,
  children,
  onClick,
  disabled,
  type = 'button',
  className = '',
  ...rest
}) {
  const base = {
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    gap: '8px',
    borderRadius: '12px',
    fontWeight: 600,
    border: 'none',
    transition: 'transform 0.15s ease, background 0.2s ease, opacity 0.2s ease',
    width: fullWidth ? '100%' : 'auto',
    opacity: disabled ? 0.5 : 1,
    cursor: disabled ? 'not-allowed' : 'pointer',
    letterSpacing: '-0.01em',
    whiteSpace: 'nowrap',
  };
  const sizes = {
    md: { height: '48px', padding: '0 24px', fontSize: '15px' },
    lg: { height: '56px', padding: '0 32px', fontSize: '17px' },
  };
  const variants = {
    primary:   { background: 'var(--color-signal)', color: 'var(--color-charcoal)' },
    secondary: { background: 'transparent', color: 'var(--color-trust)', border: '2px solid var(--color-trust)' },
    ghost:     { background: 'transparent', color: 'var(--color-charcoal)' },
  };
  const [hover, setHover] = useState(false);
  const hoverStyle = !disabled && hover ? {
    primary:   { background: '#E8581F', transform: 'scale(1.02)' },
    secondary: { background: 'rgba(30,58,95,0.06)' },
    ghost:     { background: 'rgba(26,26,26,0.05)' },
  }[variant] : {};

  return (
    <button
      type={type}
      onClick={onClick}
      disabled={disabled || loading}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{ ...base, ...sizes[size], ...variants[variant], ...hoverStyle }}
      className={className}
      {...rest}
    >
      {loading ? (
        <span style={{
          width: 16, height: 16, border: '2px solid currentColor',
          borderTopColor: 'transparent', borderRadius: '50%',
          animation: 'spin 0.8s linear infinite', display: 'inline-block'
        }} />
      ) : (
        <>
          {icon && <span style={{ display: 'inline-flex' }}>{icon}</span>}
          <span>{children}</span>
          {iconRight && <span style={{ display: 'inline-flex' }}>{iconRight}</span>}
        </>
      )}
    </button>
  );
}

// ─────────────────────────────────────────────────────────────────
// Card
// ─────────────────────────────────────────────────────────────────
function Card({ variant = 'default', children, style = {}, className = '', ...rest }) {
  const variants = {
    default:     { background: 'var(--color-hanji)', color: 'var(--color-charcoal)' },
    highlighted: { background: 'var(--color-trust)', color: 'var(--color-ivory)' },
    plain:       { background: 'var(--color-ivory)', color: 'var(--color-charcoal)' },
  };
  return (
    <div
      className={className}
      style={{
        borderRadius: '20px',
        padding: '28px',
        border: '1px solid rgba(26,26,26,0.06)',
        ...variants[variant],
        ...style,
      }}
      {...rest}
    >
      {children}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// Badge
// ─────────────────────────────────────────────────────────────────
function Badge({ variant = 'neutral', children, style = {} }) {
  const variants = {
    orange:  { background: 'rgba(255,106,44,0.10)', color: 'var(--color-signal)' },
    sage:    { background: 'rgba(184,197,166,0.30)', color: 'var(--color-charcoal)' },
    trust:   { background: 'rgba(30,58,95,0.10)',   color: 'var(--color-trust)' },
    neutral: { background: 'rgba(26,26,26,0.05)',   color: 'rgba(26,26,26,0.7)' },
    onTrust: { background: 'rgba(255,255,255,0.12)', color: 'var(--color-ivory)' },
  };
  return (
    <span
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        padding: '4px 12px',
        borderRadius: '999px',
        fontSize: '12px',
        fontWeight: 500,
        letterSpacing: '-0.01em',
        ...variants[variant],
        ...style,
      }}
    >
      {children}
    </span>
  );
}

// ─────────────────────────────────────────────────────────────────
// Section wrapper (with reveal-on-scroll)
// ─────────────────────────────────────────────────────────────────
function Section({ id, bg = 'ivory', children, style = {}, dense = false }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) { setSeen(true); obs.disconnect(); }
      });
    }, { rootMargin: '-80px 0px' });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  const bgClass = `bg-${bg}`;
  return (
    <section
      id={id}
      ref={ref}
      className={`${bgClass} reveal-on-view ${seen ? 'in-view' : ''}`}
      style={{ padding: dense ? '64px 0' : '96px 0', ...style }}
    >
      <div style={{
        maxWidth: '1280px',
        margin: '0 auto',
        padding: '0 24px',
      }}>
        {children}
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────────
// Section header
// ─────────────────────────────────────────────────────────────────
function SectionHeader({ eyebrow, title, subtitle, align = 'center' }) {
  return (
    <div style={{
      textAlign: align,
      maxWidth: align === 'center' ? '760px' : 'none',
      margin: align === 'center' ? '0 auto 56px' : '0 0 56px',
    }}>
      {eyebrow && (
        <div style={{ marginBottom: '16px' }}>
          <Badge variant="orange">{eyebrow}</Badge>
        </div>
      )}
      <h2 className="headline" style={{
        fontSize: 'clamp(28px, 4vw, 48px)',
        lineHeight: 1.15,
        fontWeight: 700,
        margin: 0,
        color: 'inherit',
        whiteSpace: 'pre-line',
      }}>{title}</h2>
      {subtitle && (
        <p style={{
          fontSize: '17px',
          lineHeight: 1.6,
          color: 'currentColor',
          opacity: 0.7,
          marginTop: '20px',
          marginBottom: 0,
          maxWidth: '640px',
          marginLeft: align === 'center' ? 'auto' : 0,
          marginRight: align === 'center' ? 'auto' : 0,
        }}>{subtitle}</p>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// StatPill
// ─────────────────────────────────────────────────────────────────
function StatPill({ number, label, source, emphasis = false, color = 'signal' }) {
  const numColor = color === 'signal' ? 'var(--color-signal)'
                 : color === 'trust' ? 'var(--color-trust)'
                 : 'inherit';
  return (
    <div style={{ textAlign: 'center' }}>
      <div className="tabular" style={{
        fontSize: emphasis ? 'clamp(48px, 6vw, 76px)' : 'clamp(40px, 5vw, 60px)',
        fontWeight: 700,
        lineHeight: 1,
        color: numColor,
        letterSpacing: '-0.04em',
      }}>{number}</div>
      <div style={{ marginTop: '12px', fontSize: '15px', opacity: 0.75, lineHeight: 1.5 }}>{label}</div>
      {source && <div style={{ marginTop: '6px', fontSize: '11px', opacity: 0.4, fontFamily: 'IBM Plex Mono, monospace' }}>{source}</div>}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// Input
// ─────────────────────────────────────────────────────────────────
function Input({ label, error, helperText, style = {}, ...rest }) {
  const [focus, setFocus] = useState(false);
  return (
    <label style={{ display: 'block', width: '100%' }}>
      {label && (
        <div style={{ fontSize: '13px', fontWeight: 500, opacity: 0.8, marginBottom: '8px' }}>
          {label}
        </div>
      )}
      <input
        onFocus={() => setFocus(true)}
        onBlur={() => setFocus(false)}
        style={{
          width: '100%',
          height: '48px',
          background: 'var(--color-ivory)',
          border: `1px solid ${error ? '#DC2626' : focus ? 'var(--color-signal)' : 'rgba(26,26,26,0.15)'}`,
          boxShadow: focus ? '0 0 0 3px rgba(255,106,44,0.18)' : 'none',
          borderRadius: '12px',
          padding: '0 16px',
          fontSize: '15px',
          fontFamily: 'inherit',
          color: 'var(--color-charcoal)',
          outline: 'none',
          transition: 'border-color 0.15s, box-shadow 0.15s',
          ...style,
        }}
        {...rest}
      />
      {error
        ? <div style={{ marginTop: '6px', fontSize: '13px', color: '#DC2626' }}>{error}</div>
        : helperText && <div style={{ marginTop: '6px', fontSize: '13px', opacity: 0.5 }}>{helperText}</div>
      }
    </label>
  );
}

function Textarea({ label, error, ...rest }) {
  const [focus, setFocus] = useState(false);
  return (
    <label style={{ display: 'block', width: '100%' }}>
      {label && (
        <div style={{ fontSize: '13px', fontWeight: 500, opacity: 0.8, marginBottom: '8px' }}>
          {label}
        </div>
      )}
      <textarea
        onFocus={() => setFocus(true)}
        onBlur={() => setFocus(false)}
        style={{
          width: '100%',
          minHeight: '120px',
          background: 'var(--color-ivory)',
          border: `1px solid ${error ? '#DC2626' : focus ? 'var(--color-signal)' : 'rgba(26,26,26,0.15)'}`,
          boxShadow: focus ? '0 0 0 3px rgba(255,106,44,0.18)' : 'none',
          borderRadius: '12px',
          padding: '12px 16px',
          fontSize: '15px',
          fontFamily: 'inherit',
          color: 'var(--color-charcoal)',
          outline: 'none',
          resize: 'vertical',
          lineHeight: 1.5,
        }}
        {...rest}
      />
    </label>
  );
}

// Export to window so other JSX scripts can use these
Object.assign(window, {
  Button, Card, Badge, Section, SectionHeader, StatPill, Input, Textarea,
});
