{{--
    Aurora Bildirim Sistemi — SweetAlert2'nin yerini alan özel toast + onay modalı.

    API:
      appToast({ icon, title, text?, timer? })  veya  appToast('success', 'Kaydedildi')
      appConfirm({ title, text?, icon?, confirmText?, cancelText?, danger? }) → Promise<boolean>
      appAlert({ title, text?, icon? })

    Geriye uyum: window.Swal köprüsü — mevcut tüm Swal.fire / Swal.mixin çağrıları
    (toast, input, html, preConfirm, didOpen dahil) bu bileşen üzerinden render edilir.
    SweetAlert2 kütüphanesi artık YÜKLENMEZ.
--}}
<style>
    :root {
        --apx-success: #16a34a; --apx-success-g: linear-gradient(135deg, #22c55e, #16a34a);
        --apx-error: #dc2626;   --apx-error-g: linear-gradient(135deg, #ef4444, #dc2626);
        --apx-warning: #d97706; --apx-warning-g: linear-gradient(135deg, #f59e0b, #d97706);
        --apx-info: #2563eb;    --apx-info-g: linear-gradient(135deg, #3b82f6, #2563eb);
        --apx-question: #475569;--apx-question-g: linear-gradient(135deg, #64748b, #475569);
    }

    /* ═══ TOAST'LAR — ekranın sol üstünde, soldan kibarca süzülür ═══ */
    .apx-toasts {
        position: fixed; top: 16px; left: 16px; z-index: 100000;
        display: flex; flex-direction: column; gap: .55rem; align-items: flex-start;
        pointer-events: none; max-width: min(440px, calc(100vw - 32px));
    }
    .apx-toast {
        pointer-events: auto; position: relative; overflow: hidden;
        display: flex; align-items: center; gap: .55rem;
        min-width: 210px; max-width: 100%;
        background: rgba(255, 255, 255, .92); backdrop-filter: blur(12px);
        border: 1px solid #eef1f6; border-radius: 11px;
        padding: .45rem 1.9rem .45rem .45rem;
        box-shadow: 0 8px 26px -10px rgba(15, 23, 42, .22), 0 2px 6px rgba(15, 23, 42, .05);
        animation: apxToastIn .42s cubic-bezier(.21, 1.22, .35, 1) both;
    }
    .apx-toast.leaving { animation: apxToastOut .22s ease-in forwards; }
    @keyframes apxToastIn {
        0% { opacity: 0; transform: translateX(-115%) scale(.96); }
        65% { opacity: 1; transform: translateX(5px) scale(1); }
        100% { opacity: 1; transform: translateX(0) scale(1); }
    }
    @keyframes apxToastOut {
        to { opacity: 0; transform: translateX(-24px) scale(.95); }
    }

    .apx-toast-ico {
        width: 26px; height: 26px; border-radius: 8px; flex-shrink: 0;
        display: inline-flex; align-items: center; justify-content: center;
        color: #fff; font-size: .66rem;
        background: var(--apx-question-g);
        box-shadow: 0 4px 10px -4px color-mix(in srgb, var(--tc, #475569) 65%, transparent);
    }
    .apx-toast[data-type="success"]  { --tc: var(--apx-success); }  .apx-toast[data-type="success"] .apx-toast-ico  { background: var(--apx-success-g); }
    .apx-toast[data-type="error"]    { --tc: var(--apx-error); }    .apx-toast[data-type="error"] .apx-toast-ico    { background: var(--apx-error-g); }
    .apx-toast[data-type="warning"]  { --tc: var(--apx-warning); }  .apx-toast[data-type="warning"] .apx-toast-ico  { background: var(--apx-warning-g); }
    .apx-toast[data-type="info"]     { --tc: var(--apx-info); }     .apx-toast[data-type="info"] .apx-toast-ico     { background: var(--apx-info-g); }
    .apx-toast[data-type="question"] { --tc: var(--apx-question); } .apx-toast[data-type="question"] .apx-toast-ico { background: var(--apx-question-g); }

    .apx-toast-body { min-width: 0; }
    .apx-toast-body b { display: block; font-size: .76rem; font-weight: 700; color: #0f172a; line-height: 1.3; letter-spacing: -0.01em; word-break: break-word; }
    .apx-toast-body span { display: block; font-size: .68rem; font-weight: 600; color: #64748b; margin-top: .08rem; word-break: break-word; }
    .apx-toast-body span:empty { display: none; }

    .apx-toast-x {
        position: absolute; top: 50%; right: .4rem; transform: translateY(-50%);
        width: 20px; height: 20px; border: none; border-radius: 6px; cursor: pointer;
        background: transparent; color: #cbd5e1; font-size: .62rem;
        display: inline-flex; align-items: center; justify-content: center; transition: all .15s ease;
    }
    .apx-toast-x:hover { background: #f1f5f9; color: #475569; }

    .apx-toast-bar {
        position: absolute; left: 0; right: 0; bottom: 0; height: 2px;
        background: var(--tc, #475569); opacity: .85; transform-origin: left;
        animation: apxBar linear forwards;
    }
    .apx-toast:hover .apx-toast-bar { animation-play-state: paused; }
    @keyframes apxBar { from { transform: scaleX(1); } to { transform: scaleX(0); } }

    /* ═══ ONAY / UYARI MODALI ═══ */
    .apx-overlay {
        position: fixed; inset: 0; z-index: 100001;
        background: rgba(15, 23, 42, .45); backdrop-filter: blur(5px);
        display: flex; align-items: center; justify-content: center; padding: 1rem;
        animation: apxFade .18s ease both;
    }
    .apx-overlay.leaving { animation: apxFadeOut .16s ease forwards; }
    @keyframes apxFade { from { opacity: 0; } to { opacity: 1; } }
    @keyframes apxFadeOut { to { opacity: 0; } }

    .apx-modal {
        width: 100%; max-width: 420px;
        background: #fff; border-radius: 20px; overflow: hidden;
        box-shadow: 0 30px 70px -20px rgba(15, 23, 42, .45);
        padding: 1.6rem 1.5rem 1.35rem; text-align: center;
        animation: apxPop .32s cubic-bezier(.21, 1.25, .4, 1) both;
    }
    .apx-overlay.leaving .apx-modal { animation: apxPopOut .16s ease-in forwards; }
    @keyframes apxPop { from { opacity: 0; transform: scale(.92) translateY(10px); } to { opacity: 1; transform: scale(1) translateY(0); } }
    @keyframes apxPopOut { to { opacity: 0; transform: scale(.95); } }
    .apx-modal.shake { animation: apxShake .4s ease; }
    @keyframes apxShake { 20%, 60% { transform: translateX(-7px); } 40%, 80% { transform: translateX(7px); } }

    .apx-modal-ico {
        width: 58px; height: 58px; border-radius: 18px; margin: 0 auto .85rem;
        display: flex; align-items: center; justify-content: center;
        color: #fff; font-size: 1.35rem;
        background: var(--apx-question-g);
        box-shadow: 0 12px 26px -10px color-mix(in srgb, var(--tc, #475569) 70%, transparent),
                    0 0 0 7px color-mix(in srgb, var(--tc, #475569) 8%, transparent);
    }
    .apx-modal[data-type="success"]  { --tc: var(--apx-success); }  .apx-modal[data-type="success"] .apx-modal-ico  { background: var(--apx-success-g); }
    .apx-modal[data-type="error"]    { --tc: var(--apx-error); }    .apx-modal[data-type="error"] .apx-modal-ico    { background: var(--apx-error-g); }
    .apx-modal[data-type="warning"]  { --tc: var(--apx-warning); }  .apx-modal[data-type="warning"] .apx-modal-ico  { background: var(--apx-warning-g); }
    .apx-modal[data-type="info"]     { --tc: var(--apx-info); }     .apx-modal[data-type="info"] .apx-modal-ico     { background: var(--apx-info-g); }
    .apx-modal[data-type="question"] { --tc: var(--apx-question); } .apx-modal[data-type="question"] .apx-modal-ico { background: var(--apx-question-g); }

    .apx-modal h5 { font-size: 1.06rem; font-weight: 800; color: #0f172a; letter-spacing: -0.02em; margin: 0 0 .35rem; }
    .apx-modal-text { font-size: .85rem; font-weight: 500; color: #64748b; line-height: 1.55; }
    .apx-modal-text:empty { display: none; }
    .apx-modal-text b, .apx-modal-text strong { color: #334155; }

    .apx-modal-input, .apx-modal .swal2-input {
        width: 100%; margin: .85rem 0 0; border: 1px solid #e2e8f0; border-radius: 11px;
        padding: .55rem .8rem; font-size: .86rem; color: #1e293b; text-align: center;
        transition: border-color .15s, box-shadow .15s;
    }
    .apx-modal-input:focus, .apx-modal .swal2-input:focus {
        outline: none; border-color: color-mix(in srgb, var(--tc, #4f46e5) 60%, #fff);
        box-shadow: 0 0 0 3px color-mix(in srgb, var(--tc, #4f46e5) 15%, transparent);
    }

    .apx-modal-actions { display: flex; gap: .55rem; justify-content: center; margin-top: 1.15rem; }
    .apx-btn {
        border: none; cursor: pointer; font-weight: 800; font-size: .84rem;
        padding: .58rem 1.35rem; border-radius: 12px; transition: all .15s ease; min-width: 104px;
    }
    .apx-btn:active { transform: scale(.97); }
    .apx-btn-cancel { background: #fff; border: 1px solid #e2e8f0; color: #64748b; }
    .apx-btn-cancel:hover { background: #f8fafc; color: #1e293b; border-color: #cbd5e1; }
    .apx-btn-confirm {
        color: #fff; background: linear-gradient(135deg, #6366f1, #4f46e5);
        box-shadow: 0 8px 18px -8px rgba(79, 70, 229, .65);
    }
    .apx-btn-confirm:hover { filter: brightness(1.07); transform: translateY(-1px); }
    .apx-btn-confirm.danger { background: var(--apx-error-g); box-shadow: 0 8px 18px -8px rgba(220, 38, 38, .65); }
    .apx-btn-confirm.warn { background: var(--apx-warning-g); box-shadow: 0 8px 18px -8px rgba(217, 119, 6, .65); }

    @media (max-width: 480px) {
        .apx-toasts { right: 16px; max-width: none; align-items: stretch; }
        .apx-toast { min-width: 0; }
    }
</style>

<script>
(function () {
    'use strict';

    const ICONS = {
        success: 'fa-check',
        error: 'fa-xmark',
        warning: 'fa-triangle-exclamation',
        info: 'fa-info',
        question: 'fa-question',
    };
    const norm = (icon) => ICONS[icon] ? icon : 'info';

    function onReady(fn) {
        if (document.body) fn();
        else document.addEventListener('DOMContentLoaded', fn);
    }

    // ── Toast ──────────────────────────────────────────────
    function toastWrap() {
        let el = document.querySelector('.apx-toasts');
        if (!el) {
            el = document.createElement('div');
            el.className = 'apx-toasts';
            document.body.appendChild(el);
        }
        return el;
    }

    function dismissToast(t) {
        if (t.classList.contains('leaving')) return;
        t.classList.add('leaving');
        t.addEventListener('animationend', () => t.remove(), { once: true });
    }

    function appToast(a, b, c) {
        const o = (typeof a === 'object' && a !== null) ? { ...a } : { icon: a, title: b, text: c };
        onReady(() => {
            const type = norm(o.icon);
            const timer = o.timer === undefined ? 3200 : o.timer;

            const t = document.createElement('div');
            t.className = 'apx-toast';
            t.dataset.type = type;
            t.setAttribute('role', 'status');
            t.innerHTML =
                '<span class="apx-toast-ico"><i class="fas ' + ICONS[type] + '"></i></span>' +
                '<div class="apx-toast-body"><b></b><span></span></div>' +
                '<button type="button" class="apx-toast-x" aria-label="Kapat"><i class="fas fa-xmark"></i></button>';
            t.querySelector('b').textContent = o.title || '';
            t.querySelector('.apx-toast-body span').textContent = o.text || '';
            t.querySelector('.apx-toast-x').addEventListener('click', () => dismissToast(t));

            if (timer) {
                const bar = document.createElement('span');
                bar.className = 'apx-toast-bar';
                bar.style.animationDuration = timer + 'ms';
                bar.addEventListener('animationend', () => dismissToast(t));
                t.appendChild(bar);
            }

            toastWrap().prepend(t);

            // Yığın taşmasın: en fazla 5 toast
            const all = toastWrap().querySelectorAll('.apx-toast:not(.leaving)');
            if (all.length > 5) dismissToast(all[all.length - 1]);
        });
    }

    // ── Modal (onay / uyarı / girişli) ─────────────────────
    let activeModal = null;

    function closeModal(result) {
        if (!activeModal) return;
        const { overlay, resolve, keyHandler } = activeModal;
        activeModal = null;
        document.removeEventListener('keydown', keyHandler);
        overlay.classList.add('leaving');
        overlay.addEventListener('animationend', () => overlay.remove(), { once: true });
        resolve(result);
    }

    const DANGER_COLORS = ['#ef4444', '#dc2626', '#d33', '#e74c3c', '#f43f5e'];

    function openModal(o) {
        return new Promise((resolve) => onReady(() => {
            if (activeModal) closeModal({ isConfirmed: false, isDenied: false, isDismissed: true });

            const type = norm(o.icon);
            const overlay = document.createElement('div');
            overlay.className = 'apx-overlay';

            const modal = document.createElement('div');
            modal.className = 'apx-modal';
            modal.dataset.type = type;
            modal.setAttribute('role', 'dialog');
            modal.setAttribute('aria-modal', 'true');

            modal.innerHTML =
                '<div class="apx-modal-ico"><i class="fas ' + ICONS[type] + '"></i></div>' +
                '<h5></h5><div class="apx-modal-text"></div>';
            modal.querySelector('h5').textContent = o.title || '';

            const textEl = modal.querySelector('.apx-modal-text');
            if (o.html !== undefined && o.html !== null && o.html !== '') {
                typeof o.html === 'string' ? (textEl.innerHTML = o.html) : textEl.appendChild(o.html);
            } else {
                textEl.textContent = o.text || '';
            }

            // Giriş alanı (Swal input uyumu: text / number / textarea)
            let inputEl = null;
            if (o.input) {
                inputEl = document.createElement(o.input === 'textarea' ? 'textarea' : 'input');
                if (o.input !== 'textarea') inputEl.type = o.input === 'number' ? 'number' : 'text';
                inputEl.className = 'apx-modal-input';
                inputEl.placeholder = o.inputPlaceholder || '';
                if (o.inputValue !== undefined) inputEl.value = o.inputValue;
                modal.appendChild(inputEl);
            }

            const actions = document.createElement('div');
            actions.className = 'apx-modal-actions';

            let cancelBtn = null;
            if (o.showCancelButton) {
                cancelBtn = document.createElement('button');
                cancelBtn.type = 'button';
                cancelBtn.className = 'apx-btn apx-btn-cancel';
                cancelBtn.textContent = o.cancelButtonText || 'Vazgeç';
                cancelBtn.addEventListener('click', () => closeModal({ isConfirmed: false, isDenied: false, isDismissed: true }));
                actions.appendChild(cancelBtn);
            }

            const confirmBtn = document.createElement('button');
            confirmBtn.type = 'button';
            confirmBtn.className = 'apx-btn apx-btn-confirm';
            const wantsDanger = o.danger
                || (o.confirmButtonColor && DANGER_COLORS.some(c => String(o.confirmButtonColor).toLowerCase().startsWith(c)))
                || (o.showCancelButton && (type === 'warning' || type === 'error'));
            if (wantsDanger) confirmBtn.classList.add('danger');
            else if (type === 'warning') confirmBtn.classList.add('warn');
            confirmBtn.textContent = o.confirmButtonText || 'Tamam';

            async function confirmAction() {
                let value = inputEl ? inputEl.value : true;
                if (typeof o.preConfirm === 'function') {
                    let res;
                    try { res = await o.preConfirm(value); } catch (e) { return; }
                    if (res === false) { modal.classList.remove('shake'); void modal.offsetWidth; modal.classList.add('shake'); return; }
                    if (res !== undefined && res !== null) value = res;
                }
                closeModal({ isConfirmed: true, isDenied: false, isDismissed: false, value });
            }
            confirmBtn.addEventListener('click', confirmAction);
            actions.appendChild(confirmBtn);
            modal.appendChild(actions);
            overlay.appendChild(modal);

            // Dış tıklama (Swal varsayılanıyla uyumlu: kapatır; allowOutsideClick:false ile kapanmaz)
            overlay.addEventListener('mousedown', (e) => {
                if (e.target === overlay && o.allowOutsideClick !== false) {
                    closeModal({ isConfirmed: false, isDenied: false, isDismissed: true });
                }
            });

            const keyHandler = (e) => {
                if (e.key === 'Escape' && o.allowEscapeKey !== false) {
                    closeModal({ isConfirmed: false, isDenied: false, isDismissed: true });
                }
                if (e.key === 'Enter' && !(e.target && e.target.tagName === 'TEXTAREA')) {
                    e.preventDefault();
                    confirmAction();
                }
            };
            document.addEventListener('keydown', keyHandler);

            document.body.appendChild(overlay);
            activeModal = { overlay, resolve, keyHandler };

            (inputEl || confirmBtn).focus();
            if (typeof o.didOpen === 'function') { try { o.didOpen(modal); } catch (e) {} }
        }));
    }

    // ── Genel API ──────────────────────────────────────────
    window.appToast = appToast;
    window.appAlert = (o) => openModal({ ...o });
    window.appConfirm = (o) => openModal({ showCancelButton: true, icon: 'question', ...o })
        .then(r => r.isConfirmed);

    // ── SweetAlert2 köprüsü (geriye uyum) ──────────────────
    function normalizeArgs(a, b, c) {
        if (typeof a === 'object' && a !== null) return { ...a };
        const o = {};
        if (a !== undefined) o.title = a;
        if (b !== undefined) o.text = b;
        if (c !== undefined) o.icon = c;
        return o;
    }

    const SwalBridge = {
        fire(...args) {
            const o = normalizeArgs(...args);
            if (o.toast) {
                appToast({ icon: o.icon || 'info', title: o.title || '', text: o.text || '', timer: o.timer === undefined ? 3000 : o.timer });
                return Promise.resolve({ isConfirmed: false, isDenied: false, isDismissed: true });
            }
            return openModal(o);
        },
        mixin(defaults = {}) {
            return { fire: (...args) => SwalBridge.fire({ ...defaults, ...normalizeArgs(...args) }) };
        },
        close() { closeModal({ isConfirmed: false, isDenied: false, isDismissed: true }); },
        isVisible() { return !!activeModal; },
        stopTimer() {},
        resumeTimer() {},
        showLoading() {},
        hideLoading() {},
    };

    window.Swal = SwalBridge;
})();
</script>
