import { html, ref, repeat, slotted, when } from '@genesislcap/web-core';
import { ANIMATION_DEFS } from '../../main/main.types';
import { formatCostSessionDate, } from '../../utils/cost-session-history';
import { formatCompactTokenCountPlain, formatCompactTokenCountSafe } from '../../utils/sum-tokens';
const SESSION_COST_DECIMALS = 2;
/** Animation options grouped by {@link ANIMATION_DEFS} category for the settings list. */
const animationCategoryGroups = (() => {
    var _a;
    const groups = new Map();
    for (const [value, def] of Object.entries(ANIMATION_DEFS)) {
        const items = (_a = groups.get(def.category)) !== null && _a !== void 0 ? _a : [];
        items.push({ value, label: def.label, description: def.description });
        groups.set(def.category, items);
    }
    return [...groups.entries()].map(([category, items]) => ({ category, items }));
})();
const animationPickerRows = animationCategoryGroups.flatMap((group) => [
    { kind: 'category', category: group.category },
    ...group.items.map((item) => ({
        kind: 'option',
        value: item.value,
        label: item.label,
        description: item.description,
    })),
]);
const toggleAnimationEnabled = (host, value, enabled) => {
    var _a;
    const next = enabled
        ? [...host.enabledAnimations, value]
        : (_a = host.enabledAnimations) === null || _a === void 0 ? void 0 : _a.filter((animation) => animation !== value);
    host.setEnabledAnimations(next);
};
const readSwitchChecked = (event) => event.target.checked;
/** Inline animation picker — categories and options always visible (no multiselect popup). */
const animationsPickerTemplate = (switchTag) => html `
  <div class="settings-animation-list" part="toggle-animations">
    ${repeat((x) => {
    void x.enabledAnimations;
    return animationPickerRows;
}, html `
        ${when((row) => row.kind === 'category', html `
            <div class="settings-animation-category-label" part="animation-category">
              ${(row) => (row.kind === 'category' ? row.category : '')}
            </div>
          `)}
        ${when((row) => row.kind === 'option', html `
            <div class="settings-toggle-row settings-animation-option" part="animation-option">
              <div class="settings-toggle-text">
                <div class="settings-toggle-title">
                  ${(row) => (row.kind === 'option' ? row.label : '')}
                </div>
                <div class="settings-toggle-desc">
                  ${(row) => (row.kind === 'option' ? row.description : '')}
                </div>
              </div>
              <div class="settings-toggle-control">
                <${switchTag}
                  part="animation-toggle"
                  :checked=${(row, c) => row.kind === 'option' && c.parent.enabledAnimations.includes(row.value)}
                  @change=${(row, c) => {
    if (row.kind !== 'option')
        return;
    toggleAnimationEnabled(c.parent, row.value, readSwitchChecked(c.event));
}}
                ></${switchTag}>
              </div>
            </div>
          `)}
      `)}
  </div>
`;
/** Shared label + control row used for switches, buttons, and multiselects. */
const settingsToggleRow = (title, description, part, control, layout = 'row') => html `
  <div class="settings-toggle-row ${layout === 'column' ? 'is-stacked' : ''}" part="${part}-row">
    <div class="settings-toggle-text">
      <div class="settings-toggle-title">${title}</div>
      <div class="settings-toggle-desc">${description}</div>
    </div>
    <div class="settings-toggle-control">${control}</div>
  </div>
`;
const chatBotToggleRow = (title, description, switchTag, part, checked, onChange) => settingsToggleRow(title, description, part, html `
      <${switchTag}
        part="${part}"
        :checked=${checked}
        @change=${onChange}
      ></${switchTag}>
    `);
const platformContextUsageTemplate = (progressTag) => html `
  ${when((x) => {
    var _a;
    return ((_a = x.chatConfig.ui) === null || _a === void 0 ? void 0 : _a.showContextUsage) !== false &&
        x.contextTokens != null &&
        x.contextLimit != null;
}, html `
      <div class="settings-context-usage" part="context-usage">
        <div class="settings-context-header">
          <span class="settings-context-label">Context window</span>
          <span class="settings-context-tokens">
            ${(x) => x.contextTokens.toLocaleString()} /
            ${(x) => x.contextLimit.toLocaleString()} tokens
            (${(x) => Math.round((x.contextTokens / x.contextLimit) * 100)}%)
          </span>
        </div>
        <${progressTag}
          part="context-progress"
          value="${(x) => Math.min(100, Math.round((x.contextTokens / x.contextLimit) * 100))}"
        ></${progressTag}>
      </div>
    `)}
`;
const chatBotSettingsTemplate = (switchTag, buttonTag) => html `
  ${when((x) => { var _a; return ((_a = x.chatConfig.ui) === null || _a === void 0 ? void 0 : _a.showToolCalls) != null; }, chatBotToggleRow('Show tool calls', "Display each tool the chatbot invokes — file reads, searches, edits and commands — inline as it works, so you can follow exactly what it's doing behind the scenes.", switchTag, 'toggle-tool-calls', (x) => x.showToolCalls, (x, c) => {
    x.showToolCalls = readSwitchChecked(c.event);
}))}
  ${when((x) => { var _a; return ((_a = x.chatConfig.ui) === null || _a === void 0 ? void 0 : _a.showThinkingSteps) != null; }, chatBotToggleRow('Show thinking', "Reveal the assistant's reasoning as it works through your request, surfacing its intermediate thought process before it commits to a response.", switchTag, 'toggle-thinking', (x) => x.showThinkingSteps, (x, c) => {
    x.showThinkingSteps = readSwitchChecked(c.event);
}))}
  ${when((x) => { var _a; return ((_a = x.chatConfig.ui) === null || _a === void 0 ? void 0 : _a.showNarration) != null; }, chatBotToggleRow('Show working', "Show the assistant's running commentary — the short notes it writes alongside its actions as it works, separate from its reasoning and its final answer.", switchTag, 'toggle-narration', (x) => x.showNarration, (x, c) => {
    x.showNarration = readSwitchChecked(c.event);
}))}
  ${when((x) => { var _a; return ((_a = x.chatConfig.ui) === null || _a === void 0 ? void 0 : _a.showAgentSwitchIndicator) != null; }, chatBotToggleRow('Show delegation', 'Show in the chat window when tasks are delegated to different agents.', switchTag, 'toggle-agent-switch', (x) => x.showAgentSwitchIndicator, (x, c) => {
    x.showAgentSwitchIndicator = readSwitchChecked(c.event);
}))}
  ${when((x) => x.persistenceToggleable, chatBotToggleRow('Remember chat', 'Save this conversation so it can be restored after a page refresh. Turning this off deletes the saved copy.', switchTag, 'toggle-remember-chat', (x) => x.persistenceActive, (x, c) => {
    x.setPersistenceEnabled(readSwitchChecked(c.event));
}))}
  ${when((x) => { var _a, _b; return ((_b = (_a = x.chatConfig.ui) === null || _a === void 0 ? void 0 : _a.animations) === null || _b === void 0 ? void 0 : _b.userConfigurable) === true; }, settingsToggleRow('Animations', 'Choose which loading and activity indicators appear while the assistant is working.', 'toggle-animations', animationsPickerTemplate(switchTag), 'column'))}
`;
const appSettingsTemplate = (switchTag) => html `
  ${repeat((x) => x.visibleAppSettingsToggles, html `
      <div class="settings-app-toggle-block">
        <div
          class="settings-toggle-row"
          part="${(toggle) => { var _a; return `${(_a = toggle.part) !== null && _a !== void 0 ? _a : `app-toggle-${toggle.id}`}-row`; }}"
        >
          <div class="settings-toggle-text">
            <div class="settings-toggle-title">${(toggle) => toggle.title}</div>
            <div class="settings-toggle-desc">${(toggle) => toggle.description}</div>
          </div>
          <div class="settings-toggle-control">
            <${switchTag}
              part="${(toggle) => { var _a; return (_a = toggle.part) !== null && _a !== void 0 ? _a : `app-toggle-${toggle.id}`; }}"
              :checked=${(toggle, c) => c.parent.getAppSettingValue(toggle.id)}
              ?disabled=${(toggle) => { var _a, _b; return (_b = (_a = toggle.disabled) === null || _a === void 0 ? void 0 : _a.call(toggle)) !== null && _b !== void 0 ? _b : false; }}
              @change=${(toggle, c) => {
    c.parent.setAppSettingValue(toggle.id, readSwitchChecked(c.event));
}}
            ></${switchTag}>
          </div>
        </div>
        ${when((toggle) => { var _a; return !!((_a = toggle.hint) === null || _a === void 0 ? void 0 : _a.call(toggle)); }, html `
            <div class="settings-toggle-hint">${(toggle) => { var _a, _b; return (_b = (_a = toggle.hint) === null || _a === void 0 ? void 0 : _a.call(toggle)) !== null && _b !== void 0 ? _b : ''; }}</div>
          `)}
      </div>
    `)}
  <slot name="settings-app" ${slotted('settingsAppSlotted')}></slot>
`;
const sessionCostSummaryTemplate = () => html `
    ${when((x) => x.settingsCostSummaryVisible, html `
        <div class="settings-current-build" part="session-cost-summary">
          <div class="settings-current-build-top">
            <span class="settings-live-badge">
              <span class="settings-live-dot"></span>
              ${(x) => x.resolvedCostHistory.badgeLabel}
            </span>
            ${when((x) => !!x.liveCostSessionTitle, html `
                <span class="settings-current-build-name">${(x) => x.liveCostSessionTitle}</span>
              `)}
          </div>
          <div class="settings-current-build-stats">
            <div
              class="settings-build-stat"
              part="session-cost"
              ?hidden=${(x) => !x.resolvedCostHistory.showCost}
            >
              <div class="settings-build-stat-label">Current session cost</div>
              <div class="settings-build-stat-value">
                <span class="prefix">$</span>
                <span class="value">${(x) => x.sessionCostUsd.toFixed(SESSION_COST_DECIMALS)}</span>
              </div>
            </div>
            <div
              class="settings-build-stat"
              part="session-tokens"
              ?hidden=${(x) => !x.resolvedCostHistory.showTokens}
            >
              <div class="settings-build-stat-label">Tokens consumed</div>
              <div
                class="settings-build-stat-value"
                :innerHTML="${(x) => formatCompactTokenCountSafe(x.sessionTokensConsumed)}"
              ></div>
            </div>
            <div
              class="settings-build-stat"
              part="session-cumulative-cost"
              ?hidden=${(x) => !x.resolvedCostHistory.showCost}
            >
              <div class="settings-build-stat-label">Total build cost</div>
              <div class="settings-build-stat-value">
                <span class="prefix">$</span>
                <span class="value">
                  ${(x) => x.cumulativeCostUsd.toFixed(SESSION_COST_DECIMALS)}
                </span>
              </div>
            </div>
          </div>
          ${when((x) => { var _a; return ((_a = x.chatConfig.ui) === null || _a === void 0 ? void 0 : _a.showActiveModel) !== false && x.providerStatuses.length > 0; }, html `
              <div class="settings-model-tags" part="session-model-tags">
                ${repeat((x) => x.providerStatuses, html `
                    <span
                      class="settings-model-tag vendor-${(entry) => { var _a; return ((_a = entry.status) === null || _a === void 0 ? void 0 : _a.provider) || 'generic'; }}"
                    >
                      ${(entry) => { var _a, _b; return (_b = (_a = entry.status) === null || _a === void 0 ? void 0 : _a.model) !== null && _b !== void 0 ? _b : entry.name; }}
                    </span>
                  `)}
              </div>
            `)}
        </div>
      `)}
  `;
const costSessionHistoryTemplate = (iconTag, buttonTag) => html `
  ${repeat((x) => x.costSessionHistory, html `
      <div class="settings-cost-history-row" part="cost-history-row">
        <div class="settings-cost-history-row-content">
          <span class="settings-cost-history-icon" part="cost-history-icon" aria-hidden="true">
            <${iconTag} name="table-cells-large"></${iconTag}>
          </span>
          <div class="settings-cost-history-row-body">
            <div class="settings-cost-history-row-left">
              <div class="settings-cost-history-row-title">
                ${(record) => record.title}
              </div>
              <div class="settings-cost-history-row-date">
                ${(record) => formatCostSessionDate(record.endedAt)}
              </div>
            </div>
            <div class="settings-cost-history-row-right">
              <div class="settings-cost-history-row-metrics">
                <div class="settings-cost-history-row-cost">
                  $${(record) => record.costUsd.toFixed(SESSION_COST_DECIMALS)}
                </div>
                <div class="settings-cost-history-row-tokens">
                  ${(record) => formatCompactTokenCountPlain(record.tokensConsumed)} tokens
                </div>
              </div>
            </div>
          </div>
          <${buttonTag}
            class="settings-cost-history-delete"
            part="cost-history-delete"
            appearance="stealth"
            aria-label="Remove from build history"
            @click=${(record, c) => c.parent.showConfirmationDialog('Are you sure you want to remove this build from history?', c.parent.settingsModal, () => c.parent.removeCostSessionFromHistory(record.id))}
          >
            <${iconTag} name="trash"></${iconTag}>
          </${buttonTag}>
        </div>
        ${when((record) => record.models.length > 0, html `
            <div
              class="settings-cost-history-row-content settings-model-tags settings-cost-history-model-tags"
            >
              ${repeat((record) => record.models, html `
                  <span class="settings-model-tag vendor-${(model) => model.provider || 'generic'}">
                    ${(model) => model.model}
                  </span>
                `)}
            </div>
          `)}
      </div>
    `)}
`;
/**
 * Modal shell for assistant settings — Settings and Cost tabs, section slots for
 * app-specific UI, and built-in chat-bot toggles.
 */
export const SettingsModalTemplate = (designSystemPrefix) => {
    const modalTag = `${designSystemPrefix}-modal`;
    const buttonTag = `${designSystemPrefix}-button`;
    const switchTag = `${designSystemPrefix}-switch`;
    const iconTag = `${designSystemPrefix}-icon`;
    const progressTag = `${designSystemPrefix}-progress`;
    const tabsTag = `${designSystemPrefix}-tabs`;
    const tabTag = `${designSystemPrefix}-tab`;
    const tabPanelTag = `${designSystemPrefix}-tab-panel`;
    const settingsTabPanel = html `
    <${tabPanelTag}
      slot="tabpanel"
      class="settings-modal-tab-panel"
      part="settings-tab-panel"
    >
      <div class="settings-modal-body" part="settings-modal-body">
      <section
        class="settings-modal-section"
        part="settings-section-model"
        ?hidden=${(x) => !x.settingsModelSectionVisible}
      >
        <h3 class="settings-modal-section-title">
          <${iconTag} name="microchip"></${iconTag}> AI Model Settings
        </h3>
        <div class="settings-modal-section-body">
          <slot name="settings-model" ${slotted('settingsModelSlotted')}></slot>
          ${platformContextUsageTemplate(progressTag)}
        </div>
      </section>
      <section
        class="settings-modal-section"
        part="settings-section-app"
        ?hidden=${(x) => !x.settingsAppSectionVisible}
      >
        <h3 class="settings-modal-section-title">
          <${iconTag} name="home"></${iconTag}> ${(x) => x.appSettingsSectionTitle}
        </h3>
        <div class="settings-modal-section-body">
          ${appSettingsTemplate(switchTag)}
        </div>
      </section>
      ${when((x) => { var _a; return ((_a = x.chatConfig.ui) === null || _a === void 0 ? void 0 : _a.allowDebugDownload) === true; }, html `
          <section class="settings-modal-section" part="settings-section-agent-log">
            <div class="settings-modal-section-body">
              ${settingsToggleRow('Download agent log', "Export a structured debug timeline of this session's agent activity.", 'download-agent-log', html `
                  <${buttonTag}
                    part="download-button"
                    appearance="outline"
                    ?disabled=${(x) => x.downloadingDebugLog}
                    @click=${(x) => x.downloadDebugLog()}
                  >
                    ${when((x) => x.downloadingDebugLog, html `
                        <span
                          class="download-spinner"
                          part="download-spinner"
                          aria-hidden="true"
                        ></span>
                      `)}
                    ${(x) => (x.downloadingDebugLog ? 'Downloading…' : 'Download')}
                  </${buttonTag}>
                `)}
            </div>
          </section>
        `)}
      <section class="settings-modal-section" part="settings-section-chat">
        <h3 class="settings-modal-section-title">
          <${iconTag} name="comment"></${iconTag}> AI Chat Bot Settings
        </h3>
        <p class="settings-modal-section-note">These options only control what you see in the chat window and do not control model behaviour.</p>
        <div class="settings-modal-section-body">
          ${chatBotSettingsTemplate(switchTag, buttonTag)}
        </div>
      </section>
      </div>
    </${tabPanelTag}>
  `;
    const costTabPanel = html `
    <${tabPanelTag}
      slot="tabpanel"
      class="settings-modal-tab-panel"
      part="cost-tab-panel"
    >
      <div class="settings-modal-body" part="settings-modal-body">
      ${sessionCostSummaryTemplate()}
      <div
        class="settings-cost-current"
        part="settings-cost-current"
        ?hidden=${(x) => !x.settingsCostCurrentSectionVisible}
      >
        <slot name="settings-cost-current" ${slotted('settingsCostCurrentSlotted')}></slot>
      </div>
      <p class="settings-cost-history-title" ?hidden=${(x) => !x.settingsCostHistorySectionVisible}>
        Build history
      </p>
      <div
        class="settings-cost-history"
        part="settings-cost-history"
        ?hidden=${(x) => !x.settingsCostHistorySectionVisible}
      >
        ${costSessionHistoryTemplate(iconTag, buttonTag)}
        <slot name="settings-cost-history" ${slotted('settingsCostHistorySlotted')}></slot>
      </div>
      </div>
    </${tabPanelTag}>
  `;
    return html `
    <${modalTag}
      class="settings-modal"
      part="settings-modal"
      exportparts="dialog: settings-dialog, content: settings-content, top: settings-top, bottom: settings-footer"
      ${ref('settingsModal')}
      initial-width="620"
      @close=${(x) => x.onSettingsModalClosed()}
    >
      <div slot="top" class="settings-modal-header" part="settings-modal-header">
        <h2 class="settings-modal-title">
          <${iconTag} name="cog"></${iconTag}> Settings
        </h2>
      </div>
      <div class="settings-modal-content" part="settings-modal-content">
        <${tabsTag}
          class="settings-modal-tabs"
          part="settings-modal-tabs"
          appearance="secondary"
          ${ref('settingsTabsEl')}
          @change=${(x, c) => x.onSettingsModalTabsChange(c.event)}
        ><${tabTag} 
          slot="tab" 
          id="settings" 
          appearance="secondary" 
          class="settings-modal-tab"
          part="settings-modal-tab-settings"
        ><${iconTag} name="cog"></${iconTag}> AI Assistant</${tabTag}>${when((x) => x.settingsCostTabVisible, html `<${tabTag} 
            slot="tab" 
            id="cost" 
            appearance="secondary" 
            class="settings-modal-tab"
            part="settings-modal-tab-cost"
          ><${iconTag} name="dollar-sign"></${iconTag}> Cost</${tabTag}>`)}${settingsTabPanel}${when((x) => x.settingsCostTabVisible, costTabPanel)}</${tabsTag}>
      </div>
      <div slot="bottom" class="settings-modal-footer" part="settings-modal-footer">
        <div class="settings-modal-footer-actions">
          ${when((x) => x.settingsModalTab === 'cost', html `
              <span class="settings-disclaimer">
                Costs are estimated from token usage at list price.
              </span>
            `)}
          <${buttonTag}
            appearance="outline"
            part="settings-done-button"
            class="settings-done-button"
            @click=${(x) => x.closeSettingsModal()}
          >Done</${buttonTag}>
        </div>
      </div>
    </${modalTag}>
  `;
};
