var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import '../buttons/tool-icon-button.js';
import '../panel/embed-card-style-panel.js';
import { assertExists } from '@blockeditor/global/utils';
import { WithDisposable } from '@blockeditor/lit';
import { css, html, LitElement, nothing } from 'lit';
import { customElement, property, query, state } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { toggleEmbedCardEditModal } from '../../../../_common/components/embed-card/modal/embed-card-edit-modal.js';
import { toast } from '../../../../_common/components/toast.js';
import { EMBED_CARD_HEIGHT, EMBED_CARD_WIDTH, } from '../../../../_common/consts.js';
import { BookmarkIcon } from '../../../../_common/icons/edgeless.js';
import { CaptionIcon, CopyIcon, EditIcon, EmbedWebIcon, OpenIcon, PaletteIcon, RefreshIcon, } from '../../../../_common/icons/text.js';
import { BookmarkStyles } from '../../../../bookmark-block/bookmark-model.js';
import { Bound, } from '../../../../surface-block/index.js';
import { isBookmarkBlock, isEmbedGithubBlock, isEmbedLinkedDocBlock, } from '../../utils/query.js';
import { createButtonPopper } from '../utils.js';
let EdgelessChangeEmbedCardButton = class EdgelessChangeEmbedCardButton extends WithDisposable(LitElement) {
    constructor() {
        super(...arguments);
        this._showPopper = false;
        this._embedOptions = null;
        this._embedCardStylePopper = null;
    }
    get _page() {
        return this.model.page;
    }
    get _pageService() {
        const pageService = this.surface.std.spec.getService('affine:page');
        assertExists(pageService);
        return pageService;
    }
    get _blockElement() {
        const blockSelection = this.surface.edgeless.selectionManager.selections.filter(sel => sel.elements.includes(this.model.id));
        if (blockSelection.length !== 1) {
            return;
        }
        const blockElement = this.std.view.viewFromPath('block', blockSelection[0].path);
        assertExists(blockElement);
        return blockElement;
    }
    get _canShowUrlOptions() {
        return ('url' in this.model &&
            (isBookmarkBlock(this.model) ||
                isEmbedGithubBlock(this.model) ||
                isEmbedLinkedDocBlock(this.model)));
    }
    get _canShowOpenButton() {
        return isEmbedLinkedDocBlock(this.model);
    }
    get _isCardView() {
        if (isBookmarkBlock(this.model) || isEmbedLinkedDocBlock(this.model)) {
            return true;
        }
        return this._embedOptions?.viewType === 'card';
    }
    get _isEmbedView() {
        if (isBookmarkBlock(this.model) || isEmbedLinkedDocBlock(this.model)) {
            return false;
        }
        return this._embedOptions?.viewType === 'embed';
    }
    get _canConvertToEmbedView() {
        return this._embedOptions?.viewType === 'embed';
    }
    get _canShowCardStylePanel() {
        return (isBookmarkBlock(this.model) ||
            isEmbedGithubBlock(this.model) ||
            isEmbedLinkedDocBlock(this.model));
    }
    _open() {
        this._blockElement?.open();
    }
    _showCaption() {
        const blockElement = this._blockElement;
        if (blockElement) {
            blockElement.showCaption = true;
            blockElement.updateComplete
                .then(() => blockElement.captionElement.input.focus())
                .catch(console.error);
        }
    }
    _refreshData() {
        this._blockElement?.refreshData();
    }
    _copyUrl() {
        if (!('url' in this.model)) {
            return;
        }
        navigator.clipboard.writeText(this.model.url).catch(console.error);
        toast(this.std.host, 'Copied link to clipboard');
        this.surface.selection.clear();
    }
    _setEmbedCardStyle(style) {
        const bounds = Bound.deserialize(this.model.xywh);
        bounds.w = EMBED_CARD_WIDTH[style];
        bounds.h = EMBED_CARD_HEIGHT[style];
        const xywh = bounds.serialize();
        this.model.page.updateBlock(this.model, { style, xywh });
        this._embedCardStylePopper?.hide();
    }
    _convertToCardView() {
        if (this._isCardView || !('url' in this.model)) {
            return;
        }
        const { url, xywh, style } = this.model;
        let targetFlavour = 'affine:bookmark', targetStyle = style;
        if (this._embedOptions && this._embedOptions.viewType === 'card') {
            const { flavour, styles } = this._embedOptions;
            targetFlavour = flavour;
            targetStyle = styles.includes(style) ? style : styles[0];
        }
        else {
            targetStyle = BookmarkStyles.includes(style) ? style : BookmarkStyles[0];
        }
        const bound = Bound.deserialize(xywh);
        bound.w = EMBED_CARD_WIDTH[targetStyle];
        bound.h = EMBED_CARD_HEIGHT[targetStyle];
        const blockId = this.surface.addElement(targetFlavour, { url, xywh: bound.serialize(), style: targetStyle }, this.surface.model);
        this.surface.edgeless.selectionManager.set({
            editing: false,
            elements: [blockId],
        });
        this._page.deleteBlock(this.model);
    }
    _convertToEmbedView() {
        if (this._isEmbedView || !('url' in this.model)) {
            return;
        }
        if (!this._embedOptions)
            return;
        const { flavour, styles } = this._embedOptions;
        const { url, xywh, style } = this.model;
        const targetStyle = styles.includes(style) ? style : styles[0];
        const bound = Bound.deserialize(xywh);
        bound.w = EMBED_CARD_WIDTH[targetStyle];
        bound.h = EMBED_CARD_HEIGHT[targetStyle];
        const blockId = this.surface.addElement(flavour, {
            url,
            xywh: bound.serialize(),
            style: targetStyle,
        }, this.surface.model);
        this.surface.edgeless.selectionManager.set({
            editing: false,
            elements: [blockId],
        });
        this._page.deleteBlock(this.model);
    }
    updated(changedProperties) {
        this._embedCardStylePopper?.dispose();
        if (this._canShowCardStylePanel) {
            this._embedCardStylePopper = createButtonPopper(this._embedCardStyleButton, this._embedCardStylePanel, ({ display }) => {
                this._showPopper = display === 'show';
            });
            this._disposables.add(this._embedCardStylePopper);
        }
        super.firstUpdated(changedProperties);
    }
    render() {
        const model = this.model;
        if ('url' in this.model) {
            this._embedOptions = this._pageService.getEmbedBlockOptions(this.model.url);
        }
        return html `
      <div class="change-embed-card-container">
        ${this._canShowUrlOptions && 'url' in model
            ? html `<div
                class="change-embed-card-button url"
                @click=${this._copyUrl}
              >
                <span>${model.url}</span>
              </div>

              <edgeless-tool-icon-button
                .tooltip=${'Click to copy link'}
                class="change-embed-card-button copy"
                ?disabled=${this._page.readonly}
                @click=${() => this._copyUrl()}
              >
                ${CopyIcon}
              </edgeless-tool-icon-button>

              <edgeless-tool-icon-button
                .tooltip=${'Edit'}
                class="change-embed-card-button edit"
                ?disabled=${this._page.readonly}
                @click=${() => toggleEmbedCardEditModal(this.std.host, model)}
              >
                ${EditIcon}
              </edgeless-tool-icon-button>

              <component-toolbar-menu-divider
                .vertical=${true}
              ></component-toolbar-menu-divider>`
            : nothing}
        ${this._canShowOpenButton
            ? html `<edgeless-tool-icon-button
                .tooltip=${'Open'}
                class="change-embed-card-button open"
                @click=${this._open}
              >
                ${OpenIcon}
              </edgeless-tool-icon-button>

              <component-toolbar-menu-divider
                .vertical=${true}
              ></component-toolbar-menu-divider>`
            : nothing}

        <div class="change-embed-card-view-style">
          ${this._canConvertToEmbedView
            ? html `
                <div class="change-embed-card-button-view-selector">
                  <edgeless-tool-icon-button
                    class=${classMap({
                'change-embed-card-button': true,
                card: true,
                'current-view': this._isCardView,
            })}
                    .tooltip=${'Card view'}
                    ?disabled=${this._page.readonly}
                    .iconContainerPadding=${2}
                    .hover=${false}
                    @click=${() => this._convertToCardView()}
                  >
                    ${BookmarkIcon}
                  </edgeless-tool-icon-button>

                  <edgeless-tool-icon-button
                    class=${classMap({
                'change-embed-card-button': true,
                embed: true,
                'current-view': this._isEmbedView,
            })}
                    .tooltip=${'Embed view'}
                    ?disabled=${this._page.readonly}
                    .iconContainerPadding=${2}
                    .hover=${false}
                    @click=${() => this._convertToEmbedView()}
                  >
                    ${EmbedWebIcon}
                  </edgeless-tool-icon-button>
                </div>
              `
            : nothing}
          ${this._canShowCardStylePanel
            ? html `
                <div class="change-embed-card-button card-style">
                  <edgeless-tool-icon-button
                    .tooltip=${this._showPopper ? '' : 'Card style'}
                    ?disabled=${this._page.readonly}
                    @click=${() => this._embedCardStylePopper?.toggle()}
                  >
                    ${PaletteIcon}
                  </edgeless-tool-icon-button>
                </div>

                <embed-card-style-panel
                  .value=${model.style}
                  .onSelect=${(value) => this._setEmbedCardStyle(value)}
                >
                </embed-card-style-panel>
              `
            : nothing}
        </div>

        <component-toolbar-menu-divider
          .vertical=${true}
        ></component-toolbar-menu-divider>

        <edgeless-tool-icon-button
          .tooltip=${'Add Caption'}
          class="change-embed-card-button caption"
          ?disabled=${this._page.readonly}
          @click=${() => this._showCaption()}
        >
          ${CaptionIcon}
        </edgeless-tool-icon-button>

        <component-toolbar-menu-divider
          .vertical=${true}
        ></component-toolbar-menu-divider>

        <edgeless-tool-icon-button
          .tooltip=${'Reload'}
          class="change-embed-card-button reload"
          ?disabled=${this._page.readonly}
          @click=${() => this._refreshData()}
        >
          ${RefreshIcon}
        </edgeless-tool-icon-button>
      </div>
    `;
    }
};
EdgelessChangeEmbedCardButton.styles = css `
    .change-embed-card-container {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .change-embed-card-button {
      width: 24px;
      height: 24px;
      border-radius: 4px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .change-embed-card-button.url {
      display: flex;
      width: 180px;
      padding: var(--1, 0px);
      align-items: flex-start;
      gap: 10px;
      border-radius: var(--1, 0px);
      opacity: var(--add, 1);
      margin-right: 6px;
      user-select: none;
      cursor: pointer;
    }

    .change-embed-card-button.url > span {
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;

      color: var(--affine-link-color);
      font-feature-settings:
        'clig' off,
        'liga' off;
      font-family: var(--affine-font-family);
      font-size: 15px;
      font-style: normal;
      font-weight: 400;
      line-height: 24px;
      text-overflow: ellipsis;
      overflow: hidden;
      opacity: var(--add, 1);
    }

    .change-embed-card-view-style {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .change-embed-card-button-view-selector {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 2px;
      border-radius: 6px;
      background: var(--affine-hover-color);
    }
    .change-embed-card-button-view-selector .change-embed-card-button {
      width: 24px;
      height: 24px;
    }
    .change-embed-card-button-view-selector > icon-button {
      padding: 0px;
    }
    .change-embed-card-button-view-selector .current-view {
      background: var(--affine-background-overlay-panel-color);
      border-radius: 6px;
    }

    component-toolbar-menu-divider {
      height: 24px;
    }

    embed-card-style-panel {
      display: none;
    }
    embed-card-style-panel[data-show] {
      display: flex;
    }
  `;
__decorate([
    property({ attribute: false })
], EdgelessChangeEmbedCardButton.prototype, "model", void 0);
__decorate([
    property({ attribute: false })
], EdgelessChangeEmbedCardButton.prototype, "std", void 0);
__decorate([
    property({ attribute: false })
], EdgelessChangeEmbedCardButton.prototype, "surface", void 0);
__decorate([
    state()
], EdgelessChangeEmbedCardButton.prototype, "_showPopper", void 0);
__decorate([
    query('.change-embed-card-button.card-style')
], EdgelessChangeEmbedCardButton.prototype, "_embedCardStyleButton", void 0);
__decorate([
    query('embed-card-style-panel')
], EdgelessChangeEmbedCardButton.prototype, "_embedCardStylePanel", void 0);
EdgelessChangeEmbedCardButton = __decorate([
    customElement('edgeless-change-embed-card-button')
], EdgelessChangeEmbedCardButton);
export { EdgelessChangeEmbedCardButton };
//# sourceMappingURL=change-embed-card-button.js.map