// Shared UI primitives — with mobile-aware behaviour.

function useMedia(query) {
  const [match, setMatch] = React.useState(() =>
    typeof window !== 'undefined' ? window.matchMedia(query).matches : false
  );
  React.useEffect(() => {
    const mm = window.matchMedia(query);
    const handler = (e) => setMatch(e.matches);
    mm.addEventListener?.('change', handler);
    return () => mm.removeEventListener?.('change', handler);
  }, [query]);
  return match;
}

const LOGO_CANDIDATES = ['/assets/logo.jpg', '/assets/logo.png', '/assets/logo.avif', '/assets/logo.svg'];

const Logo = ({ size = 14, color, name, onClick }) => {
  const height = (size + 2) * 4.5;
  const [idx, setIdx] = React.useState(0);
  return (
    <button
      type="button"
      onClick={onClick}
      title={onClick ? 'Back to homepage' : undefined}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 10,
        fontFamily: 'var(--font-sans)', fontWeight: 600, letterSpacing: '-0.02em',
        fontSize: size + 2, color: color || 'var(--ink)',
        background: 'transparent', border: 0, padding: 0,
        cursor: onClick ? 'pointer' : 'default',
      }}
    >
      <img
        src={LOGO_CANDIDATES[idx]}
        alt={name || 'Lupipak'}
        onError={() => setIdx(i => Math.min(i + 1, LOGO_CANDIDATES.length - 1))}
        style={{
          height, width: 'auto', display: 'block',
          mixBlendMode: 'multiply',
        }}
      />
    </button>
  );
};

const TopBar = ({ step, total = 4, stepLabels = [], onLogo, right }) => {
  const isMobile = useMedia('(max-width: 900px)');
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 20,
      display: 'grid',
      gridTemplateColumns: isMobile ? '1fr auto' : '1fr auto 1fr',
      alignItems: 'center', gap: 12,
      padding: isMobile ? '12px 16px' : '14px 32px',
      background: 'rgba(245,243,238,.82)',
      backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
      borderBottom: '.5px solid var(--line)'
    }}>
      <Logo onClick={onLogo} size={17.2} />

      {!isMobile && (
        stepLabels.length > 0 ? (
          <nav style={{ display: 'flex', gap: 6, alignItems: 'center', fontSize: 11.5 }}>
            {stepLabels.map((lbl, i) => {
              const active = i === step;
              const done = i < step;
              return (
                <React.Fragment key={lbl}>
                  {i > 0 && <span style={{ width: 14, height: 1, background: done ? 'var(--ink)' : 'var(--line-2)' }} />}
                  <span className="mono" style={{
                    display: 'inline-flex', alignItems: 'center', gap: 6,
                    padding: '6px 10px', borderRadius: 999,
                    background: active ? 'var(--ink)' : 'transparent',
                    color: active ? 'var(--paper)' : (done ? 'var(--ink)' : 'var(--muted)'),
                    border: active ? 'none' : '.5px solid var(--line-2)',
                    fontSize: 10.5, letterSpacing: '0.04em', textTransform: 'uppercase',
                  }}>
                    <span style={{
                      display: 'inline-block', width: 5, height: 5, borderRadius: '50%',
                      background: active ? 'var(--accent)' : (done ? 'var(--ink)' : 'var(--muted)'),
                    }} />
                    {lbl}
                  </span>
                </React.Fragment>
              );
            })}
          </nav>
        ) : <div />
      )}

      <div style={{
        display: 'flex', justifyContent: 'flex-end',
        gap: isMobile ? 8 : 14, alignItems: 'center',
        fontSize: 12.5, color: 'var(--muted)',
      }}>
        {isMobile && stepLabels.length > 0 && (
          <span className="mono" style={{
            fontSize: 10, letterSpacing: '0.06em', textTransform: 'uppercase',
            padding: '4px 8px', borderRadius: 999, background: 'var(--ink)', color: 'var(--paper)',
          }}>
            {step + 1}/{stepLabels.length}
          </span>
        )}
        {right}
      </div>
    </header>
  );
};

const Button = ({ children, variant = 'primary', size = 'md', onClick, style, disabled, icon, iconRight, full, type }) => {
  const base = {
    appearance: 'none', border: 0, cursor: disabled ? 'default' : 'pointer',
    fontFamily: 'var(--font-sans)', fontWeight: 500,
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
    borderRadius: size === 'lg' ? 12 : 10,
    padding: size === 'lg' ? '16px 24px' : size === 'sm' ? '8px 14px' : '12px 18px',
    fontSize: size === 'lg' ? 15 : size === 'sm' ? 12.5 : 13.5,
    letterSpacing: '-0.005em',
    transition: 'all .2s cubic-bezier(.2,.8,.2,1)',
    opacity: disabled ? 0.45 : 1,
    width: full ? '100%' : 'auto',
  };
  const styles = {
    primary: { background: 'var(--ink)', color: 'var(--paper)' },
    accent:  { background: 'var(--accent)', color: '#fff' },
    ghost:   { background: 'transparent', color: 'var(--ink)', border: '.5px solid var(--line-2)' },
    quiet:   { background: 'rgba(21,19,14,.04)', color: 'var(--ink)' },
  };
  return (
    <button
      type={type || 'button'}
      onClick={disabled ? undefined : onClick}
      style={{ ...base, ...styles[variant], ...style }}
    >
      {icon}
      <span>{children}</span>
      {iconRight}
    </button>
  );
};

const ArrowRight = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 16 16" fill="none">
    <path d="M3 8 L13 8 M9 4 L13 8 L9 12" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);

const Plus = ({ size = 12 }) => (
  <svg width={size} height={size} viewBox="0 0 16 16" fill="none">
    <path d="M8 3 V13 M3 8 H13" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
  </svg>
);

const Minus = ({ size = 12 }) => (
  <svg width={size} height={size} viewBox="0 0 16 16" fill="none">
    <path d="M3 8 H13" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
  </svg>
);

const Check = ({ size = 12 }) => (
  <svg width={size} height={size} viewBox="0 0 16 16" fill="none">
    <path d="M3 8.5 L6.5 12 L13 4.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);

const Metric = ({ label, value, align = 'left' }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 4, textAlign: align }}>
    <span className="mono" style={{ fontSize: 10, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--muted)' }}>{label}</span>
    <span style={{ fontSize: 15, fontWeight: 500, letterSpacing: '-0.01em' }}>{value}</span>
  </div>
);

const Rule = ({ label, style }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 12, ...style }}>
    {label && (
      <span className="mono" style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)' }}>
        {label}
      </span>
    )}
    <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
  </div>
);

const Spinner = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 16 16" style={{ animation: 'spin 0.9s linear infinite' }}>
    <circle cx="8" cy="8" r="6" fill="none" stroke="currentColor" strokeWidth="1.5" opacity="0.2"/>
    <path d="M8 2 A6 6 0 0 1 14 8" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
  </svg>
);

const PageLoading = () => (
  <div style={{
    minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
    color: 'var(--muted)', fontSize: 13, gap: 10,
  }}>
    <Spinner size={18} />
    <span className="mono" style={{ letterSpacing: '0.06em', textTransform: 'uppercase' }}>Loading…</span>
  </div>
);

Object.assign(window, { Logo, TopBar, Button, ArrowRight, Plus, Minus, Check, Metric, Rule, Spinner, PageLoading, useMedia });
