<?php
$pageTitle = isset($pageTitle) ? $pageTitle : 'Dashboard';
$showAddProduct = isset($showAddProduct) ? $showAddProduct : false;
$showAddCategory = isset($showAddCategory) ? $showAddCategory : false;

$currentStore = isset($store) && is_array($store) ? $store : null;
if (!is_array($currentStore) || empty($currentStore)) {
    if (function_exists('getCurrentStore')) {
        $currentStore = getCurrentStore();
    } else {
        $currentStore = [];
    }
}

$ownerName = $currentStore['name'] ?? (defined('STORE_NAME') ? STORE_NAME : 'Administrador');
$ownerRole = 'Dono da Loja';
$ownerAvatar = $currentStore['logo_url'] ?? 'https://ui-avatars.com/api/?name=' . urlencode($ownerName) . '&background=CCA43B&color=1A1A1A&bold=true';
$catalogUrl = defined('STORE_URL') ? rtrim(STORE_URL, '/') : '#';
$whatsappNumber = $currentStore['whatsapp_number'] ?? (defined('WHATSAPP_NUMBER') ? WHATSAPP_NUMBER : '');

$formatContact = function (?string $value): string {
    $digits = preg_replace('/\D+/', '', (string) $value);
    if (strlen($digits) >= 11) {
        $country = substr($digits, 0, 2);
        $ddd = substr($digits, 2, 2);
        $bodyLength = max(strlen($digits) - 8, 0);
        $body = $bodyLength > 0 ? substr($digits, 4, $bodyLength) : '';
        $suffix = substr($digits, -4);
        $prefix = $body !== '' ? $body : substr($digits, 4, strlen($digits) - 4);
        return sprintf('+%s (%s) %s-%s', $country, $ddd, $prefix, $suffix);
    }
    return $digits !== '' ? '+' . $digits : 'Não informado';
};

$whatsappDisplay = $formatContact($whatsappNumber);
$catalogLabel = preg_replace('#^https?://#', '', $catalogUrl);
?>
<header class="topbar">
    <div class="topbar-left">
        <h2 class="topbar-title"><?= htmlspecialchars($pageTitle) ?></h2>
    </div>
    <div class="topbar-right">
        <?php if ($showAddProduct): ?>
        <button class="btn-primary" onclick="openProductModal()">
            <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
            <span>Novo Produto</span>
        </button>
        <?php endif; ?>
        
        <?php if ($showAddCategory): ?>
        <button class="btn-primary" onclick="openCategoryModal()">
            <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
            <span>Nova Categoria</span>
        </button>
        <?php endif; ?>
        
        <button class="topbar-btn notification">
            <iconify-icon icon="solar:bell-bold"></iconify-icon>
            <span class="notification-dot"></span>
        </button>

    </div>
</header>
<script>
(function() {
    const wrapper = document.getElementById('ownerMenuWrapper');
    const toggle = document.getElementById('ownerMenuToggle');
    const dropdown = document.getElementById('ownerMenuDropdown');

    if (!wrapper || !toggle || !dropdown) {
        return;
    }

    const closeMenu = () => {
        wrapper.classList.remove('is-open');
        toggle.setAttribute('aria-expanded', 'false');
        dropdown.setAttribute('aria-hidden', 'true');
    };

    toggle.addEventListener('click', function(event) {
        event.stopPropagation();
        const isOpen = wrapper.classList.toggle('is-open');
        toggle.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
        dropdown.setAttribute('aria-hidden', isOpen ? 'false' : 'true');
    });

    document.addEventListener('click', function(event) {
        if (!wrapper.contains(event.target)) {
            closeMenu();
        }
    });

    const fallbackCopy = (text, onSuccess) => {
        const tempField = document.createElement('textarea');
        tempField.value = text;
        tempField.style.position = 'fixed';
        tempField.style.opacity = '0';
        document.body.appendChild(tempField);
        tempField.focus();
        tempField.select();
        try {
            document.execCommand('copy');
            onSuccess();
        } catch (error) {
            console.error('Copy fallback failed', error);
        }
        document.body.removeChild(tempField);
    };

    dropdown.querySelectorAll('[data-copy-value]').forEach(function(button) {
        button.addEventListener('click', function(event) {
            event.preventDefault();
            event.stopPropagation();
            const value = button.getAttribute('data-copy-value');
            if (!value) {
                return;
            }
            const successText = button.getAttribute('data-copy-success') || 'Copiado!';
            const actionLabel = button.querySelector('.dropdown-link-action');
            if (actionLabel && !actionLabel.hasAttribute('data-default')) {
                actionLabel.setAttribute('data-default', actionLabel.textContent);
            }

            const showFeedback = () => {
                button.classList.add('copied');
                if (actionLabel) {
                    actionLabel.textContent = successText;
                }
                setTimeout(() => {
                    button.classList.remove('copied');
                    if (actionLabel) {
                        const defaultText = actionLabel.getAttribute('data-default') || 'Copiar';
                        actionLabel.textContent = defaultText;
                    }
                }, 1600);
            };

            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(value).then(showFeedback).catch(function() {
                    fallbackCopy(value, showFeedback);
                });
            } else {
                fallbackCopy(value, showFeedback);
            }
        });
    });
})();
</script>