import { css } from '@emotion/react';

interface TutorialTooltipProps {
  message: string;
  onNext: () => void;
  onSkip?: () => void;
  nextLabel?: string;
  // 툴팁 위치: 타겟 요소의 위 or 아래
  position?: 'above' | 'below';
  targetRect?: DOMRect | null;
}

const TOOLTIP_WIDTH = 280;

const overlayStyle = css`
  position: fixed;
  inset: 0;
  z-index: 1001;
  pointer-events: none;
`;

const tooltipStyle = (position: 'above' | 'below', left: number, top: number) => css`
  position: fixed;
  left: ${left}px;
  top: ${top}px;
  width: ${TOOLTIP_WIDTH}px;
  background: #ffffff;
  border-radius: 14px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.25);
  padding: 16px;
  pointer-events: all;
  z-index: 1002;

  /* CSS triangle arrow */
  &::after {
    content: '';
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    border: 8px solid transparent;
    ${position === 'below'
      ? `
      top: -16px;
      border-bottom-color: #ffffff;
    `
      : `
      bottom: -16px;
      border-top-color: #ffffff;
    `}
  }
`;

const messageStyle = css`
  font-size: 14px;
  line-height: 1.5;
  color: #191919;
  margin-bottom: 14px;
`;

const buttonRowStyle = css`
  display: flex;
  justify-content: space-between;
  align-items: center;
`;

const nextButtonStyle = css`
  background: #3182f6;
  color: #ffffff;
  border: none;
  border-radius: 8px;
  padding: 8px 20px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  pointer-events: all;
`;

const skipButtonStyle = css`
  background: none;
  border: none;
  color: rgba(25, 25, 25, 0.4);
  font-size: 12px;
  cursor: pointer;
  padding: 4px;
  pointer-events: all;
`;

export function TutorialTooltip({
  message,
  onNext,
  onSkip,
  nextLabel = '다음',
  position = 'below',
  targetRect,
}: TutorialTooltipProps) {
  const viewportWidth = typeof window !== 'undefined' ? window.innerWidth : 375;
  const viewportHeight = typeof window !== 'undefined' ? window.innerHeight : 812;

  let left = (viewportWidth - TOOLTIP_WIDTH) / 2;
  let top = viewportHeight / 2;

  if (targetRect) {
    left = Math.max(8, Math.min(viewportWidth - TOOLTIP_WIDTH - 8, targetRect.left + targetRect.width / 2 - TOOLTIP_WIDTH / 2));
    if (position === 'below') {
      top = targetRect.bottom + 20;
    } else {
      top = targetRect.top - 20 - 120; // approximate tooltip height
    }
  }

  // Clamp to viewport
  top = Math.max(8, Math.min(viewportHeight - 160, top));

  return (
    <div css={overlayStyle}>
      <div css={tooltipStyle(position, left, top)}>
        <p css={messageStyle}>{message}</p>
        <div css={buttonRowStyle}>
          {onSkip ? (
            <button css={skipButtonStyle} onClick={onSkip}>건너뛰기</button>
          ) : (
            <span />
          )}
          <button css={nextButtonStyle} onClick={onNext}>{nextLabel}</button>
        </div>
      </div>
    </div>
  );
}
