frappe.ui.form.on('Amas Employees', {
    refresh: function(frm) {
        // Add "View Contract" button if contract HTML exists
        if (frm.doc.contract_html && frm.doc.contract_html.trim().length > 0) {
            frm.add_custom_button(__('View Contract'), function() {
                show_contract_dialog(frm.doc.contract_html, frm.doc.full_name);
            });
        }
    }
});

function show_contract_dialog(html_content, employee_name) {
    // Create dialog with proper size
    const d = new frappe.ui.Dialog({
        title: __('Employment Contract') + (employee_name ? ': ' + employee_name : ''),
        size: 'large',
        fields: [
            {
                fieldname: 'contract_preview',
                fieldtype: 'HTML',
                options: '<div id="contract-iframe-wrapper"></div>'
            }
        ],
        primary_action_label: __('Print'),
        primary_action: function() {
            // Get iframe and trigger print
            const iframe = document.getElementById('contract-iframe');
            if (iframe && iframe.contentWindow) {
                iframe.contentWindow.print();
            }
        },
        secondary_action_label: __('Close')
    });

    d.show();

    // Set dialog to full width
    d.$wrapper.find('.modal-dialog').css({
        'max-width': '90%',
        'width': '90%',
        'margin': '30px auto'
    });

    // Wait for dialog to fully render, then create iframe
    setTimeout(() => {
        const wrapper = d.$wrapper.find('#contract-iframe-wrapper');

        // Create iframe with proper styling
        wrapper.html(`
            <iframe
                id="contract-iframe"
                style="width: 100%; height: 70vh; border: 1px solid #d1d8dd; border-radius: 4px;">
            </iframe>
        `);

        // Wait a bit more for iframe to be added to DOM
        setTimeout(() => {
            const iframe = d.$wrapper.find('#contract-iframe')[0];

            if (iframe) {
                // Wrap content in proper HTML structure
                const full_html = `<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        /* Ensure print styles work correctly */
        @media print {
            body {
                margin: 0;
                padding: 20px;
            }
        }
    </style>
</head>
<body>
${html_content}
</body>
</html>`;

                // Use contentWindow.document.write for better compatibility
                const doc = iframe.contentDocument || iframe.contentWindow.document;
                doc.open();
                doc.write(full_html);
                doc.close();
            }
        }, 200);
    }, 100);
}
