import { __decorate, __metadata } from "tslib";
import { LitElement, css, html, nothing } from 'lit';
import { customElement, property, query, state } from 'lit/decorators.js';
import { isMobileDevice } from '@operato/utils';
let SmallTooltipElement = class SmallTooltipElement extends LitElement {
    constructor() {
        super(...arguments);
        this.content = '';
        this.open = false;
        this.alignLeft = false;
        this.stickLeft = false;
        this.flipUp = false;
        this.isMobile = false;
        this.mobileOffsetX = 0;
        this.dropBelow = false;
        this.idRef = Math.random().toString(36).slice(2);
        this.onDocumentPointerDown = (e) => {
            // 바깥 클릭 시 닫기
            if (!this.open)
                return;
            const path = e.composedPath();
            if (!path.includes(this))
                this.open = false;
        };
        this.onWindowResize = () => {
            this.isMobile = isMobileDevice();
            if (!this.open)
                return;
            this.measureSoon();
        };
        this.onOtherTooltipOpen = (e) => {
            if (e.detail?.id !== this.idRef)
                this.open = false;
        };
        this.onToggle = (e) => {
            e.stopPropagation();
            const willOpen = !this.open;
            if (willOpen) {
                window.dispatchEvent(new CustomEvent('small-tooltip:open', { detail: { id: this.idRef } }));
            }
            this.open = willOpen;
        };
    }
    static { this.styles = css `
    :host {
      position: relative;
      display: inline-block;
    }

    .iconBtn {
      width: 18px;
      height: 18px;
      border-radius: 9999px;
      border: 1px solid #d1d5db;
      color: #374151;
      background: #fff;
      cursor: pointer;
      font-size: 12px;
      line-height: 1;
      padding: 0;
      display: inline-flex;
      align-items: center;
      justify-content: center;
    }

    .popover {
      position: absolute;
      z-index: 30;
      top: 0;
      left: calc(100% + 8px);
      transform: translateY(0);
      background: #ffffff;
      color: #111827;
      border: 1px solid #e5e7eb;
      border-radius: 8px;
      font-size: 13px;
      min-width: 200px;
      max-width: 420px;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25);
    }

    .flipUp {
      top: auto;
      bottom: 0;
    }

    .alignLeft {
      left: auto;
      right: calc(100% + 8px);
    }

    .stickLeftViewport {
      left: 8px !important;
      right: auto !important;
    }

    .popoverContent {
      display: flex;
      width: max-content;
      padding: 10px 12px;
      line-height: 1.4;
      /*white-space: pre-wrap; */
      word-break: break-word;
      max-height: 260px;
      overflow: auto;
      font-weight: 500;
      text-align: left;
    }

    .popoverContent ul {
      list-style: disc;
      margin: 6px 0 0 0;
      padding-left: 16px;
    }
    .popoverContent li {
      margin: 2px 0;
    }
    .popoverContent strong {
      font-weight: 600;
    }

    .iconSvg {
      color: #2563eb;
      width: 14px;
      height: 14px;
    }

    .popover.below-layout {
      left: 0;
      right: auto;
      top: calc(100% + 8px);
      bottom: auto;
      max-width: 420px;
      width: fit-content;
      transform: none;
    }

    .popover.below-layout.flipUp {
      top: auto;
      bottom: calc(100% + 8px);
    }

    :host a {
      color: #2563eb;
      text-decoration: none;
      cursor: pointer;
    }

    /* Mobile layout: place below the icon and keep within viewport */
    @media (max-width: 768px) {
      .popover.mobile,
      .popover.below-layout {
        position: absolute;
        left: 0;
        right: auto;
        top: calc(100% + 8px);
        bottom: auto;
        max-width: min(92vw, 420px);
        min-width: 220px; /* prevent 1ch shrink-to-fit */
        width: fit-content; /* expand to content within max-width */
        transform: none; /* we control X offset via inline style */
      }

      .popover.mobile.flipUp,
      .popover.below-layout.flipUp {
        top: auto;
        bottom: calc(100% + 8px);
      }

      .popover.mobile .popoverContent {
        display: block;
        width: auto;
        max-height: min(50vh, 360px);
        white-space: normal;
        word-break: keep-all;
        overflow-wrap: anywhere;
      }
    }
  `; }
    connectedCallback() {
        super.connectedCallback();
        this.isMobile = isMobileDevice();
        window.addEventListener('small-tooltip:open', this.onOtherTooltipOpen);
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        window.removeEventListener('small-tooltip:open', this.onOtherTooltipOpen);
        this.detachGlobalListeners();
    }
    updated(changed) {
        if (changed.has('open')) {
            if (this.open) {
                this.attachGlobalListeners();
                this.measureSoon();
            }
            else {
                this.detachGlobalListeners();
            }
        }
    }
    attachGlobalListeners() {
        document.addEventListener('mousedown', this.onDocumentPointerDown, { capture: true });
        document.addEventListener('touchstart', this.onDocumentPointerDown, { capture: true });
        window.addEventListener('resize', this.onWindowResize);
    }
    detachGlobalListeners() {
        document.removeEventListener('mousedown', this.onDocumentPointerDown, true);
        document.removeEventListener('touchstart', this.onDocumentPointerDown, true);
        window.removeEventListener('resize', this.onWindowResize);
    }
    measureSoon() {
        this.alignLeft = false;
        this.stickLeft = false;
        this.flipUp = false;
        this.dropBelow = false;
        this.updateComplete.then(() => {
            requestAnimationFrame(() => this.measureAndAlign());
        });
    }
    measureAndAlign() {
        const el = this.popRef;
        if (!el)
            return;
        const rect = el.getBoundingClientRect();
        const hostRect = this.getBoundingClientRect();
        const minMargin = 8;
        const gap = 8;
        const offsetParent = this.offsetParent;
        let boundaryEl = null;
        if (offsetParent instanceof HTMLElement && offsetParent !== document.body) {
            boundaryEl = offsetParent;
        }
        else if (this.parentElement instanceof HTMLElement) {
            boundaryEl = this.parentElement;
        }
        const boundaryRect = boundaryEl?.getBoundingClientRect();
        const boundaryTop = boundaryRect ? boundaryRect.top + minMargin : minMargin;
        const boundaryBottom = boundaryRect ? boundaryRect.bottom - minMargin : window.innerHeight - minMargin;
        const boundaryLeft = boundaryRect ? boundaryRect.left + minMargin : minMargin;
        const boundaryRight = boundaryRect ? boundaryRect.right - minMargin : window.innerWidth - minMargin;
        const availableRight = Math.max(0, boundaryRight - (hostRect.right + gap));
        const availableLeft = Math.max(0, hostRect.left - gap - boundaryLeft);
        const availableAboveDrop = Math.max(0, hostRect.top - gap - boundaryTop);
        const availableBelowDrop = Math.max(0, boundaryBottom - (hostRect.bottom + gap));
        const availableAboveSide = Math.max(0, hostRect.bottom - boundaryTop);
        const availableBelowSide = Math.max(0, boundaryBottom - hostRect.top);
        this.dropBelow = false;
        this.alignLeft = false;
        this.stickLeft = false;
        if (availableRight >= rect.width) {
            // keep default to the right
        }
        else if (availableLeft >= rect.width) {
            this.alignLeft = true;
            const targetLeft = hostRect.left - gap - rect.width;
            if (targetLeft < boundaryLeft)
                this.stickLeft = true;
        }
        else {
            this.dropBelow = true;
        }
        if (this.dropBelow || this.isMobile) {
            const initialLeftAbs = hostRect.left;
            const minLeftAbs = boundaryLeft;
            const maxLeftAbs = Math.max(minLeftAbs, boundaryRight - rect.width);
            const targetLeftAbs = Math.min(Math.max(initialLeftAbs, minLeftAbs), maxLeftAbs);
            this.mobileOffsetX = targetLeftAbs - hostRect.left;
        }
        const chooseFlip = (canBelow, canAbove, spaceBelow, spaceAbove) => {
            if (!canBelow && canAbove)
                return true;
            if (!canAbove && canBelow)
                return false;
            if (!canBelow && !canAbove)
                return spaceAbove >= spaceBelow;
            return false;
        };
        if (this.dropBelow) {
            const canBelow = availableBelowDrop >= rect.height;
            const canAbove = availableAboveDrop >= rect.height;
            this.flipUp = chooseFlip(canBelow, canAbove, availableBelowDrop, availableAboveDrop);
        }
        else {
            const canBelow = availableBelowSide >= rect.height;
            const canAbove = availableAboveSide >= rect.height;
            this.flipUp = chooseFlip(canBelow, canAbove, availableBelowSide, availableAboveSide);
        }
    }
    render() {
        const classes = ['popover'];
        if (this.isMobile || this.dropBelow)
            classes.push('mobile');
        if (this.dropBelow)
            classes.push('below-layout');
        if (this.flipUp)
            classes.push('flipUp');
        if (this.alignLeft)
            classes.push('alignLeft');
        if (this.stickLeft)
            classes.push('stickLeftViewport');
        return html `
      <div @mousedown=${(e) => e.stopPropagation()} @touchstart=${(e) => e.stopPropagation()}>
        <button type="button" class="iconBtn" @click=${this.onToggle} aria-label="도움말">
          <svg
            class="iconSvg"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <circle cx="12" cy="12" r="10"></circle>
            <path d="M9.09 9a3 3 0 1 1 5.83 1c0 2-3 3-3 3"></path>
            <line x1="12" y1="17" x2="12.01" y2="17"></line>
          </svg>
        </button>
        ${this.open
            ? html `
              <div
                class=${classes.join(' ')}
                role="tooltip"
                style=${this.isMobile || this.dropBelow ? `left: ${this.mobileOffsetX}px;` : ''}
              >
                <div class="popoverContent" draggable="true">
                  <slot>${this.content}</slot>
                </div>
              </div>
            `
            : nothing}
      </div>
    `;
    }
};
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], SmallTooltipElement.prototype, "content", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], SmallTooltipElement.prototype, "open", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], SmallTooltipElement.prototype, "alignLeft", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], SmallTooltipElement.prototype, "stickLeft", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], SmallTooltipElement.prototype, "flipUp", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], SmallTooltipElement.prototype, "isMobile", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], SmallTooltipElement.prototype, "mobileOffsetX", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], SmallTooltipElement.prototype, "dropBelow", void 0);
__decorate([
    query('.popover'),
    __metadata("design:type", HTMLDivElement)
], SmallTooltipElement.prototype, "popRef", void 0);
SmallTooltipElement = __decorate([
    customElement('small-tooltip')
], SmallTooltipElement);
export { SmallTooltipElement };
//# sourceMappingURL=small-tooltip.js.map