@extends('layouts.student')

@section('title', 'Live Preview - Lindsay\'s Leather')

@section('head')
<!-- Konva.js CDN -->
<script src="https://unpkg.com/konva@9/konva.min.js"></script>

<style>
            * {
                box-sizing: border-box;
            }
            
            html, body {
                overflow-x: hidden;
                max-width: 100vw;
            }
            
            body.with-order-header {
                font-family: 'Montserrat', sans-serif;
                background-color: #f8f9fa;
                margin: 0;
                padding: 0;
                min-height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
                overflow-x: hidden;
                max-width: 100vw;
            }
            
            .preview-container {
                max-width: 900px;
                width: 100%;
                padding: 2rem;
                margin: 0 auto; /* Center the container */
            }
            
            .lindsay-card {
                background: white;
                border-radius: 16px;
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
                padding: 2rem;
                border: 1px solid rgba(181, 112, 47, 0.1);
            }
            
            .flex {
                display: flex;
            }
            
            .flex-col {
                flex-direction: column;
            }
            
            .items-center {
                align-items: center;
            }
            
            .justify-center {
                justify-content: center;
            }
            
            .space-x-4 > * + * {
                margin-left: 1rem;
            }
            
            .space-y-4 > * + * {
                margin-top: 1rem;
            }
            
            .mb-8 {
                margin-bottom: 2rem;
            }
            
            .mb-4 {
                margin-bottom: 1rem;
            }
            
            .mb-2 {
                margin-bottom: 0.5rem;
            }
            
            .mt-4 {
                margin-top: 1rem;
            }
            
            .text-center {
                text-align: center;
            }
            
            .heading {
                font-family: 'Lato', sans-serif;
                font-weight: 700;
            }
            
            .body-text {
                font-family: 'Montserrat', sans-serif;
                font-weight: 400;
            }
            
            .text-primary-brown {
                color: #371C16;
            }
            
            .text-accent-brown {
                color: #B5702F;
            }
            
            .text-gray-600 {
                color: #6b7280;
            }
            
            .text-gray-500 {
                color: #9ca3af;
            }
            
            .bg-accent-brown {
                background-color: #B5702F;
            }
            
            .bg-gray-100 {
                background-color: #f3f4f6;
            }
            
            .text-white {
                color: white;
            }
            
            .rounded-lg {
                border-radius: 0.5rem;
            }
            
            .rounded-full {
                border-radius: 9999px;
            }
            
            .px-4 {
                padding-left: 1rem;
                padding-right: 1rem;
            }
            
            .py-2 {
                padding-top: 0.5rem;
                padding-bottom: 0.5rem;
            }
            
            .py-3 {
                padding-top: 0.75rem;
                padding-bottom: 0.75rem;
            }
            
            .px-6 {
                padding-left: 1.5rem;
                padding-right: 1.5rem;
            }
            
            .text-sm {
                font-size: 0.875rem;
            }
            
            .text-lg {
                font-size: 1.125rem;
            }
            
            .text-xl {
                font-size: 1.25rem;
            }
            
            .text-2xl {
                font-size: 1.5rem;
            }
            
            .text-3xl {
                font-size: 1.875rem;
            }
            
            .font-semibold {
                font-weight: 600;
            }
            
            .font-bold {
                font-weight: 700;
            }
            
            .border {
                border-width: 1px;
            }
            
            .border-gray-200 {
                border-color: #e5e7eb;
            }
            
            .shadow-lg {
                box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            }
            
            .hover\:bg-opacity-90:hover {
                background-color: rgba(181, 112, 47, 0.9);
            }
            
            .transition-colors {
                transition-property: color, background-color, border-color, text-decoration-color, fill, stroke;
                transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
                transition-duration: 150ms;
            }
            
            .lindsay-btn {
                font-family: 'Lato', sans-serif;
                font-weight: 600;
                border-radius: 12px;
                padding: 16px 32px;
                min-height: 52px;
                transition: all 0.3s ease;
                border: none;
                cursor: pointer;
                text-decoration: none;
                display: inline-flex;
                align-items: center;
                justify-content: center;
                font-size: 16px;
            }
            
            .lindsay-btn-primary {
                background: #B5702F;
                color: white;
            }
            
            .lindsay-btn-primary:hover {
                background: #371C16;
                transform: translateY(-1px);
                box-shadow: 0 6px 20px rgba(181, 112, 47, 0.3);
            }
            
            
            .preview-workspace {
                display: flex;
                grid-template-columns: 1fr 300px;
                gap: 2rem;
                margin-bottom: 2rem;
            }
            
            /* Mobile-first responsive layout */
            @media (max-width: 768px) {
                .preview-workspace {
                    display: flex;
                    flex-direction: column;
                    gap: 1rem;
                }
                
                .flex.justify-between.items-center {
                    flex-wrap: wrap;
                    gap: 0.75rem;
                }
                
                /* Force back button styling on mobile */
                a.back-button {
                    all: unset !important;
                    display: inline-flex !important;
                    align-items: center !important;
                    justify-content: center !important;
                    padding: 12px 16px !important;
                    font-size: 15px !important;
                    min-height: 48px !important;
                    background-color: white !important;
                    border: 1px solid #d1d5db !important;
                    border-radius: 8px !important;
                    color: #374151 !important;
                    font-weight: 500 !important;
                    text-decoration: none !important;
                    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05) !important;
                    cursor: pointer !important;
                    touch-action: manipulation !important;
                }
                
                a.back-button:hover {
                    background-color: #f9fafb !important;
                    border-color: #9ca3af !important;
                }
                
                a.back-button svg {
                    width: 16px !important;
                    height: 16px !important;
                    margin-right: 8px !important;
                    display: inline-block !important;
                }
                }
                
                .canvas-container {
                background: #f8f9fa;
                border: 2px solid #e5e7eb;
                border-radius: 12px;
                padding: 1rem;
                display: flex;
                align-items: center;
                justify-content: center;
                min-height: 560px;
                height: auto;
                position: relative;
                width: 100%;
                max-width: 100%;
                overflow: hidden;
                }
                
                .canvas-wrapper {
                position: relative;
                border-radius: 8px;
                overflow: hidden;
                background: white;
                width: 100%;
                height: 100%;
                min-height: 500px;
                max-width: 100%;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            
            #konvaContainer {
                width: 100% !important;
                height: 100% !important;
                min-width: 300px;
                min-height: 500px;
                max-width: 100%;
                display: block;
                position: relative;
            }
            
            #konvaContainer canvas {
                display: block;
                margin: 0 auto;
            }
                
                @if($product->name === 'bookmark')
                /* Bookmark-specific: Increase canvas height for tall products */
                .canvas-container {
                    min-height: 600px !important;
                }
                
                .canvas-wrapper {
                    min-height: 600px !important;
                }
                
                #konvaContainer {
                    min-height: 600px !important;
                }
                @endif
                
                .stamp-controls {
                background: #f8f9fa;
                border-radius: 12px;
                padding: 1.5rem;
                border: 1px solid #e5e7eb;
            }
            
            .stamp-list {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
                    gap: 0.5rem;
                    margin-bottom: 1rem;
                }
                
            .stamp-item {
                aspect-ratio: 1;
                border: 2px solid #e5e7eb;
                    border-radius: 8px;
                cursor: pointer;
                transition: all 0.2s ease;
                display: flex;
                align-items: center;
                justify-content: center;
                background: white;
                position: relative;
                overflow: hidden;
            }
            
            .stamp-item:hover {
                border-color: #B5702F;
                transform: scale(1.02);
                }
                
                .stamp-thumbnail {
                max-width: 70%;
                max-height: 70%;
                object-fit: contain;
            }
            
            .control-buttons {
                display: flex;
                gap: 0.5rem;
                    margin-bottom: 1rem;
            }
            
            .control-btn {
                padding: 0.5rem 1rem;
                    border: none;
                    border-radius: 6px;
                cursor: pointer;
                font-size: 14px;
                font-weight: 500;
                transition: all 0.2s ease;
            }
            
            .control-btn:hover {
                transform: translateY(-1px);
            }
            
            /* Mobile Responsive - Critical Fixes (Tablets & Large Phones) */
            @media (max-width: 768px) {
                * {
                    -webkit-tap-highlight-color: rgba(181, 112, 47, 0.1);
                }
                
                html, body {
                    overflow-x: hidden !important;
                    max-width: 100vw !important;
                }
                
                body.with-order-header {
                    padding: 0 !important;
                }
                
                .lindsay-btn-back {
                    min-height: 48px;
                    padding: 12px 18px;
                    font-size: 15px;
                    touch-action: manipulation;
                }
                
                .preview-container {
                    padding: 1rem !important;
                    max-width: 100vw !important;
                    overflow-x: hidden !important;
                    width: 100% !important;
                }
                
                .lindsay-card {
                    padding: 1.25rem 1rem !important;
                    margin: 0 !important;
                    border-radius: 12px;
                }
                
                .preview-workspace {
                    display: flex;
                    flex-direction: column;
                    gap: 1.25rem;
                    width: 100%;
            }
            
                .canvas-container {
                    min-height: @if($product->name === 'bookmark') 650px @else 550px @endif !important;
                    height: auto !important;
                    padding: 0 !important;
                    width: 100% !important;
                    max-width: 100% !important;
                    overflow: visible !important;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                
                .canvas-wrapper {
                    width: 100% !important;
                    height: auto !important;
                    min-height: @if($product->name === 'bookmark') 650px @else 550px @endif !important;
                    max-width: 100% !important;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                
                #konvaContainer {
                    width: 100% !important;
                    height: auto !important;
                    min-height: @if($product->name === 'bookmark') 650px @else 550px @endif !important;
                    max-width: 100% !important;
                }
                
                #konvaContainer canvas {
                    max-width: 100% !important;
                    height: auto !important;
                }
                
                .stamp-controls {
                    padding: 1.25rem 1rem;
                    width: 100%;
                }
                
                .stamp-list {
                    grid-template-columns: repeat(auto-fill, minmax(64px, 1fr));
                    gap: 0.75rem;
                }
                
                .control-btn {
                    padding: 12px 18px;
                    font-size: 15px;
                    min-height: 48px;
                    touch-action: manipulation;
                }
                
                .lindsay-btn {
                    padding: 16px 24px;
                    min-height: 56px;
                    font-size: 17px;
                    width: 100%;
                    touch-action: manipulation;
                }
                
                /* Form field mobile styling - Prevent zoom on iOS */
                input[type="text"], 
                input[type="email"],
                input[type="tel"] {
                    padding: 14px 16px !important;
                    font-size: 16px !important;
                    min-height: 52px !important;
                    width: 100% !important;
                    max-width: 100% !important;
                    box-sizing: border-box !important;
                    border-radius: 8px !important;
                    -webkit-appearance: none !important;
                }
                
                /* Order Summary mobile styling */
                .order-summary {
                    width: 100% !important;
                    max-width: 100% !important;
                    padding: 1.25rem 1rem !important;
                    margin-bottom: 1.25rem !important;
                    box-sizing: border-box !important;
                }
                
                .order-summary h3 {
                    font-size: 17px !important;
                    margin-bottom: 1rem !important;
                }
                
                .order-summary label {
                    font-size: 15px !important;
                    margin-bottom: 0.5rem !important;
                }
                
                .order-summary .space-y-4 {
                    width: 100%;
                }
                
                .text-center.mb-8 h1 {
                    font-size: 2rem !important;
                    margin-bottom: 0.75rem !important;
                }
                
                .text-center.mb-8 p {
                    font-size: 15px !important;
                }
            }
            
            /* Mobile Phones (480px and below) */
            @media (max-width: 480px) {
                .preview-container {
                    padding: 0.75rem 0.5rem !important;
                }
                
                .lindsay-card {
                    padding: 1rem 0.75rem !important;
                    margin: 0 !important;
                    border-radius: 10px;
                }
                
                .canvas-container {
                    min-height: @if($product->name === 'bookmark') 600px @else 500px @endif !important;
                    padding: 0 !important;
                }
                
                .canvas-wrapper {
                    height: auto !important;
                    min-height: @if($product->name === 'bookmark') 600px @else 500px @endif !important;
                }
                
                #konvaContainer {
                    width: 100% !important;
                    min-height: @if($product->name === 'bookmark') 600px @else 500px @endif !important;
                }
                
                .stamp-list {
                    grid-template-columns: repeat(auto-fill, minmax(56px, 1fr));
                    gap: 0.5rem;
                }
                
                .control-btn {
                    padding: 10px 14px;
                    font-size: 14px;
                    min-height: 44px;
                }
                
                .back-button {
                    padding: 10px 14px !important;
                    font-size: 14px !important;
                    min-height: 44px !important;
                    background-color: white !important;
                    border: 1px solid #d1d5db !important;
                    color: #374151 !important;
                    text-decoration: none !important;
                    display: inline-flex !important;
                    align-items: center !important;
                }
                
                .order-summary {
                    padding: 1rem 0.75rem !important;
                }
                
                .order-summary h3 {
                    font-size: 16px !important;
                }
                
                .order-summary label {
                    font-size: 14px !important;
                }
                
                input[type="text"],
                input[type="email"],
                input[type="tel"] {
                    padding: 12px 14px !important;
                    font-size: 16px !important;
                    min-height: 48px !important;
                }
                
                .lindsay-btn {
                    padding: 14px 20px;
                    min-height: 52px;
                    font-size: 16px;
                }
                
                .text-center.mb-8 h1 {
                    font-size: 1.75rem !important;
                    margin-bottom: 0.5rem !important;
                }
                
                .text-center.mb-8 p {
                    font-size: 14px !important;
                }
            }
            
            /* Extra Small Mobile (375px and below) */
            @media (max-width: 375px) {
                .preview-container {
                    padding: 0.5rem 0.35rem !important;
                }
                
                .lindsay-card {
                    padding: 0.85rem 0.6rem !important;
                }
                
                .canvas-container {
                    min-height: @if($product->name === 'bookmark') 550px @else 480px @endif !important;
                }
                
                .canvas-wrapper {
                    min-height: @if($product->name === 'bookmark') 550px @else 480px @endif !important;
                }
                
                #konvaContainer {
                    min-height: @if($product->name === 'bookmark') 550px @else 480px @endif !important;
                }
                
                .stamp-list {
                    grid-template-columns: repeat(auto-fill, minmax(50px, 1fr));
                    gap: 0.4rem;
                }
                
                .control-btn {
                    padding: 9px 12px;
                    font-size: 13px;
                    min-height: 40px;
                }
                
                .order-summary {
                    padding: 0.85rem 0.65rem !important;
                }
                
                .order-summary h3 {
                    font-size: 15px !important;
                }
                
                input[type="text"],
                input[type="email"],
                input[type="tel"] {
                    padding: 11px 12px !important;
                    font-size: 16px !important;
                    min-height: 46px !important;
                }
                
                .lindsay-btn {
                    padding: 13px 18px;
                    min-height: 50px;
                    font-size: 15px;
                }
                
                .text-center.mb-8 h1 {
                    font-size: 1.5rem !important;
                }
                
                .text-center.mb-8 p {
                    font-size: 13px !important;
                }
            }
            
            /* Error alert animation */
            @keyframes pulse {
                0%, 100% {
                    transform: scale(1);
                    box-shadow: 0 4px 6px rgba(220, 38, 38, 0.1);
                }
                50% {
                    transform: scale(1.02);
                    box-shadow: 0 6px 12px rgba(220, 38, 38, 0.2);
                }
            }
        </style>
@endsection

@section('content')
<div class="preview-container">
    <!-- Error Message Display -->
    @if(session('error'))
        <div class="error-alert" style="background: #fee2e2; border: 2px solid #dc2626; border-radius: 12px; padding: 1.5rem; margin-bottom: 2rem; display: flex; align-items: start; gap: 1rem;">
            <svg width="24" height="24" fill="none" stroke="#dc2626" viewBox="0 0 24 24" style="flex-shrink: 0; margin-top: 2px;">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
            </svg>
            <div style="flex: 1;">
                <h3 style="font-family: 'Lato', sans-serif; font-weight: 600; color: #991b1b; margin: 0 0 0.5rem 0; font-size: 1.125rem;">
                    Order Already Submitted
                </h3>
                <p style="font-family: 'Montserrat', sans-serif; color: #7f1d1d; margin: 0; line-height: 1.5;">
                    {{ session('error') }}
                </p>
            </div>
        </div>
    @endif

    @if(session('success'))
        <div class="success-alert" style="background: #d1fae5; border: 2px solid #059669; border-radius: 12px; padding: 1.5rem; margin-bottom: 2rem; display: flex; align-items: start; gap: 1rem;">
            <svg width="24" height="24" fill="none" stroke="#059669" viewBox="0 0 24 24" style="flex-shrink: 0; margin-top: 2px;">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
            <div style="flex: 1;">
                <p style="font-family: 'Montserrat', sans-serif; color: #065f46; margin: 0; line-height: 1.5; font-weight: 500;">
                    {{ session('success') }}
                </p>
            </div>
        </div>
    @endif

            <div class="lindsay-card">
                <!-- Header -->
                <div class="text-center mb-8">
                    <h1 class="heading text-3xl text-primary-brown mb-2">Live Preview</h1>
                    <p class="body-text text-gray-600">Customize your {{ ucfirst($product->name) }} design</p>
                </div>

                <!-- Back Button and Step Indicator -->
                <div class="flex justify-between items-center mb-6">
                    @if($product->name === 'bracelet')
                        <x-back-button route="student.bracelet-customize" />
                    @elseif($product->name === 'keychain')
                        @if($keychainVersion == 1)
                            <x-back-button route="student.keychain-customize" />
                        @else
                            <x-back-button route="student.keychain-customize" />
                        @endif
                    @elseif($product->name === 'bookmark')
                        <x-back-button :href="route('student.bookmark-customize', ['style' => $bookmarkStyle])" />
                    @else
                        <x-back-button route="student.index" />
                    @endif
                    <span class="body-text" style="color: #6b7280; font-family: 'Montserrat', sans-serif;">Step 4 of 4</span>
                </div>

            <!-- Order Summary -->
                <div class="order-summary bg-gray-100 rounded-lg p-4 mb-8">
                    <h3 class="heading text-lg text-primary-brown mb-4">Enter Your Name</h3>
                    <div class="space-y-4">
                        <div>
                            <label for="customer_name" class="block body-text text-sm font-medium text-gray-700 mb-2">
                                Your Name <span class="text-red-500">*</span>
                            </label>
                    <input type="text" 
                                   id="customer_name" 
                           name="customer_name" 
                                   value=""
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-accent-brown focus:border-accent-brown body-text bg-white"
                           placeholder="Enter your full name"
                                   required>
                </div>
        </div>
    </div>

                <!-- Konva.js Canvas Workspace -->
            <div class="preview-workspace">
                <div class="canvas-container">
                    <div class="canvas-wrapper">
                            <div id="konvaContainer"></div>
        </div>
    </div>

                @if($product->name !== 'bracelet' && $product->name !== 'keychain' && $product->name !== 'bookmark')
                <div class="stamp-controls">
                        <h4 class="heading text-lg text-primary-brown mb-4">Design Your Product</h4>
                        <p class="body-text text-gray-600 text-sm mb-4">
                        @if(count($selectedStamps) > 0)
                            Click stamps below to add them to your product. Select objects on canvas to move, rotate, or delete.
                        @else
                                Your design will be text only. Click "Place Order" when ready.
                    @endif
                    </p>
                    
                            <div class="control-buttons">
                        <button class="control-btn" onclick="deleteSelected()" style="background: #dc2626; color: white;">Delete Selected</button>
            </div>
            
                    <div class="stamp-list" id="stampList">
                        @if(count($selectedStamps) > 0)
                            @foreach($selectedStamps as $stamp)
                                @php
                                    // Handle both old format (string) and new format (array with filename/directory)
                                    $filename = is_array($stamp) ? $stamp['filename'] : $stamp;
                                    $directory = is_array($stamp) ? $stamp['directory'] : 'small';
                                @endphp
                                <div class="stamp-item" 
                                     data-stamp="{{ $filename }}" 
                                     data-directory="{{ $directory }}"
                                     onclick="addStampToCanvas('{{ $filename }}', '{{ $directory }}')" 
                                     title="{{ pathinfo($filename, PATHINFO_FILENAME) }}">
                                    <img src="/images/stamps/{{ $directory }}/{{ $filename }}" 
                                         alt="{{ pathinfo($filename, PATHINFO_FILENAME) }}" 
                                         class="stamp-thumbnail">
                                </div>
                            @endforeach
                        @else
                            <div style="grid-column: 1 / -1; text-align: center; padding: 2rem; color: #6b7280; font-style: italic;">
                                No symbols selected - your design will be text only
                            </div>
                        @endif
                    </div>

                        <div style="margin-top: 1rem; padding-top: 1rem; border-top: 1px solid #e5e7eb;">
                            <p style="font-size: 12px; color: #6b7280; margin-bottom: 0.5rem;"><strong>Canvas Controls:</strong></p>
                            <p style="font-size: 11px; color: #6b7280; line-height: 1.4;">
                                • Click to select objects<br>
                                • Drag to move<br>
                                • Use corner handles to rotate<br>
                                • Drag corners to resize
                            </p>
            </div>
        </div>
                @endif
    </div>

            <!-- Place Order Button -->
            <form method="POST" action="{{ route('order.submit') }}" id="orderForm">
        @csrf
                <input type="hidden" name="preview_json" id="previewJsonInput">
                <input type="hidden" name="customer_name" id="customerNameInput">
                <!-- Device Fingerprint Fields -->
                <input type="hidden" name="device_ip" id="deviceIpInput">
                <input type="hidden" name="device_user_agent" id="deviceUserAgentInput">
                <input type="hidden" name="device_screen_resolution" id="deviceScreenResolutionInput">
                <button type="submit" class="lindsay-btn lindsay-btn-primary w-full">
                    Place Order →
            </button>
    </form>
    </div>
</div>
@endsection

@section('scripts')
<script>
            let stage;
            let layer;
            let transformer;
            let selectedNode = null;
            let backgroundImage = null;
            let textNode = null;
            let stampNodes = [];
            let backgroundImageDimensions = { width: 0, height: 0, x: 0, y: 0 }; // Store actual displayed dimensions

            // Initialize Konva stage
            function initKonva() {
                const container = document.getElementById('konvaContainer');
                const productName = '{{ $product->name }}';
                const isBracelet = productName === 'bracelet';
                const isBookmark = productName === 'bookmark';
                
                // Get container dimensions with mobile optimization
                const isMobile = window.innerWidth <= 768;
                const isSmallMobile = window.innerWidth <= 480;
                const isTinyMobile = window.innerWidth <= 375;
                
                // Calculate responsive container dimensions
                let containerWidth = container.offsetWidth || container.parentElement.offsetWidth;
                let containerHeight = container.offsetHeight;
                
                // Mobile-optimized fallback dimensions
                if (containerWidth === 0 || containerWidth < 100) {
                    const availableWidth = Math.min(window.innerWidth - 32, window.innerWidth * 0.95);
                    containerWidth = availableWidth;
                    console.log('Using calculated mobile width:', containerWidth);
                }
                
                // Set appropriate height based on screen size and product type
                // Bookmarks need more vertical space due to their tall aspect ratio
                if (containerHeight === 0 || containerHeight < 100) {
                    if (isBookmark) {
                        // Bookmark-specific heights (taller canvas for tall products)
                        if (isTinyMobile) {
                            containerHeight = 550;
                        } else if (isSmallMobile) {
                            containerHeight = 600;
                        } else if (isMobile) {
                            containerHeight = 650;
                        } else {
                            containerHeight = 600; // Desktop height for bookmarks
                        }
                    } else {
                        // Standard heights for other products
                        if (isTinyMobile) {
                            containerHeight = 480;
                        } else if (isSmallMobile) {
                            containerHeight = 500;
                        } else if (isMobile) {
                            containerHeight = 550;
                        } else {
                            containerHeight = 500;
                        }
                    }
                    console.log('Using calculated height for', productName, ':', containerHeight);
                }
                
                // Ensure we don't exceed viewport width on mobile
                if (isMobile) {
                    const maxMobileWidth = window.innerWidth - 32;
                    containerWidth = Math.min(containerWidth, maxMobileWidth);
                }
                
                console.log('Final container dimensions:', containerWidth, 'x', containerHeight);
                console.log('Device type:', isTinyMobile ? 'Tiny Mobile' : isSmallMobile ? 'Small Mobile' : isMobile ? 'Mobile/Tablet' : 'Desktop');
                console.log('Is bracelet (locked preview):', isBracelet);
                
                // Create stage
                stage = new Konva.Stage({
                    container: 'konvaContainer',
                    width: containerWidth,
                    height: containerHeight,
                });
                
                // Verify stage was created with correct dimensions
                console.log('Stage created with dimensions:', stage.width(), 'x', stage.height());
                
                if (stage.width() === 0 || stage.height() === 0) {
                    console.error('Stage created with 0 dimensions, retrying...');
                    setTimeout(() => {
                        stage.destroy();
                        initKonva();
                    }, 500);
                    return;
                }

                // Create layer
                layer = new Konva.Layer();
                stage.add(layer);
                
                console.log('Konva stage and layer created');
                console.log('Layer ID:', layer.id());
                console.log('Stage container element:', stage.container());
                
                // Canvas is ready for content
                console.log('Canvas initialized and ready');
                
                // Force initial draw
                layer.draw();

                // Create transformer for resize/rotate handles (NOT for bracelets)
                if (!isBracelet) {
                    transformer = new Konva.Transformer({
                        anchorSize: 12,
                        borderStroke: '#B5702F',
                        borderStrokeWidth: 2,
                        anchorStroke: '#371C16',
                        anchorFill: '#B5702F',
                        anchorCornerRadius: 6,
                        rotateAnchorOffset: 30,
                        enabledAnchors: ['top-left', 'top-right', 'bottom-left', 'bottom-right', 'top-center', 'bottom-center', 'middle-left', 'middle-right', 'rotater'],
                    });
                    layer.add(transformer);
                }

                // Set up event listeners first
                setupEventListeners();
                
                // Load product background first, then add other elements
                setTimeout(() => {
                    loadProductBackground();
                }, 100);
                
                // Determine product type and render accordingly
                const isKeychain = productName === 'keychain';
                const keychainVersion = '{{ $keychainVersion ?? '' }}';
                // isBookmark already declared above
                const bookmarkStyle = '{{ $bookmarkStyle ?? '' }}';
                
                if (isBracelet) {
                    console.log('Bracelet detected - will render sequential elements');
                    setTimeout(() => {
                        renderSequentialElements();
                    }, 300);
                } else if (isKeychain && keychainVersion) {
                    console.log('Keychain detected - version', keychainVersion);
                    // Increase timeout to ensure background image is fully loaded
                    setTimeout(() => {
                        if (!backgroundImage) {
                            console.error('Background image still not loaded, retrying...');
                            setTimeout(() => {
                                if (keychainVersion === '1') {
                                    renderKeychainV1();
                                } else if (keychainVersion === '2') {
                                    renderKeychainV2();
                                }
                            }, 300);
                        } else {
                            if (keychainVersion === '1') {
                                renderKeychainV1();
                            } else if (keychainVersion === '2') {
                                renderKeychainV2();
                            }
                        }
                    }, 500);
                } else if (isBookmark && bookmarkStyle) {
                    console.log('Bookmark detected - style', bookmarkStyle);
                    setTimeout(() => {
                        if (!backgroundImage) {
                            console.error('Background image still not loaded, retrying...');
                            setTimeout(() => {
                                if (bookmarkStyle === '1') {
                                    renderBookmarkStyle1();
                                } else if (bookmarkStyle === '2') {
                                    renderBookmarkStyle2();
                                } else if (bookmarkStyle === '3') {
                                    renderBookmarkStyle3();
                                }
                            }, 300);
                        } else {
                            if (bookmarkStyle === '1') {
                                renderBookmarkStyle1();
                            } else if (bookmarkStyle === '2') {
                                renderBookmarkStyle2();
                            } else if (bookmarkStyle === '3') {
                                renderBookmarkStyle3();
                            }
                        }
                    }, 500);
                } else {
                    // Add user text after background loads (other products)
                    setTimeout(() => {
                        addUserText();
                    }, 300);
                }
            }

            // Load product background image
            function loadProductBackground() {
                if (!stage || !layer) {
                    console.error('Stage or layer not initialized yet');
                    return;
                }
                
                const productName = '{{ $product->name }}';
                const productImageUrl = `/images/products/${productName}.png`;
                console.log('Loading product image:', productImageUrl, 'for product:', productName);
                console.log('Stage dimensions:', stage.width(), 'x', stage.height());
                console.log('Layer children count:', layer.children.length);
                
                // No loading indicator needed - image will load directly
                
                // Test if image URL is accessible
                fetch(productImageUrl, { method: 'HEAD' })
                    .then(response => {
                        console.log('Image URL test:', response.status, response.ok ? 'OK' : 'FAILED');
                        if (!response.ok) {
                            console.error('Image not accessible:', productImageUrl);
                        }
                    })
                    .catch(error => {
                        console.error('Image URL test failed:', error);
                    });
                
                const imageObj = new Image();
                imageObj.crossOrigin = 'anonymous'; // Handle CORS if needed
                
                imageObj.onload = function() {
                    console.log('Image onload callback triggered');
                    
                    console.log('Product image loaded successfully:', imageObj.width, 'x', imageObj.height);
                    
                    // Calculate dimensions to fit canvas while maintaining aspect ratio
                    const canvasWidth = stage.width();
                    const canvasHeight = stage.height();
                    const imageAspect = imageObj.width / imageObj.height;
                    const canvasAspect = canvasWidth / canvasHeight;
                    
                    console.log('Image dimensions:', imageObj.width, 'x', imageObj.height);
                console.log('Canvas dimensions:', canvasWidth, 'x', canvasHeight);
                    console.log('Image aspect ratio:', imageAspect);
                    console.log('Canvas aspect ratio:', canvasAspect);
                    
                    let imageWidth, imageHeight;
                    // Scale to fit canvas while maintaining aspect ratio
                const isMobile = window.innerWidth <= 768;
                    const isTinyMobile = window.innerWidth <= 375;
                    
                    // Check if this is a bookmark (tall and narrow product)
                    const isBookmarkProduct = productName === 'bookmark';
                    
                    // INCREASED scaling percentages for better visibility
                    // Bookmarks need higher scaling since they're very narrow
                    let mobileScale, desktopScale;
                    
                    if (isBookmarkProduct) {
                        mobileScale = isTinyMobile ? 0.95 : 0.92; // Higher scale for bookmarks
                        desktopScale = 0.95; // Fill 95% of canvas for bookmarks
                    } else {
                        mobileScale = isTinyMobile ? 0.92 : 0.90;
                        desktopScale = 0.8;
                    }
                    
                    const maxWidth = canvasWidth * (isMobile ? mobileScale : desktopScale);
                    const maxHeight = canvasHeight * (isMobile ? mobileScale : desktopScale);
                    
                    console.log('Product type:', productName, '| Using scale:', isMobile ? mobileScale : desktopScale);
                
                if (isMobile) {
                        // On mobile, prioritize filling canvas height for maximum visibility
                        if (imageAspect > canvasAspect) {
                            // Image is wider - fit to height first, then check width
                            imageHeight = maxHeight;
                            imageWidth = maxHeight * imageAspect;
                            
                            // If too wide, fit to width instead
                            if (imageWidth > maxWidth) {
                                imageWidth = maxWidth;
                                imageHeight = maxWidth / imageAspect;
                            }
                } else {
                            // Image is taller - fit to height (better for bracelets)
                            imageHeight = maxHeight;
                            imageWidth = maxHeight * imageAspect;
                        }
                    } else {
                        // Desktop scaling (original logic)
                        if (imageAspect > canvasAspect) {
                            // Image is wider than canvas - fit to width
                            imageWidth = maxWidth;
                            imageHeight = maxWidth / imageAspect;
                        } else {
                            // Image is taller than canvas - fit to height
                            imageHeight = maxHeight;
                            imageWidth = maxHeight * imageAspect;
                        }
                    }
                    
                    // Center the image on canvas
                    const x = (canvasWidth - imageWidth) / 2;
                    const y = (canvasHeight - imageHeight) / 2;
                    
                    console.log('=== BACKGROUND IMAGE CENTERING ===');
                    console.log('Canvas size:', canvasWidth, 'x', canvasHeight);
                    console.log('Image size:', imageWidth, 'x', imageHeight);
                    console.log('Calculated center position:', x, y);
                    console.log('Image will span X from', x, 'to', (x + imageWidth));
                    console.log('Image will span Y from', y, 'to', (y + imageHeight));
                    console.log('Canvas center X:', canvasWidth / 2);
                    console.log('Image center X:', x + (imageWidth / 2));
                    
                    backgroundImage = new Konva.Image({
                        x: x,
                        y: y,
                        image: imageObj,
                        width: imageWidth,
                        height: imageHeight,
                        draggable: false,
                        selectable: false,
                        listening: false, // Make it non-interactive
                        name: 'background', // Add name for identification
                        offsetX: 0, // Explicitly set offset to 0
                        offsetY: 0,  // Explicitly set offset to 0
                        visible: true, // Explicitly set visible
                        opacity: 1 // Explicitly set opacity
                    });
                    
                    // Store the actual dimensions for later use
                    backgroundImageDimensions = {
                        width: imageWidth,
                        height: imageHeight,
                        x: x,
                        y: y
                    };
                    
                    console.log('Created background image node:', backgroundImage);
                    console.log('Stored dimensions:', backgroundImageDimensions);
                    
                    // Add to bottom of layer (index 0)
                    layer.add(backgroundImage);
                    backgroundImage.moveToBottom();
                    
                    // Verify positioning after adding to layer
                    console.log('=== VERIFICATION AFTER ADDING TO LAYER ===');
                    console.log('Background image X:', backgroundImage.x());
                    console.log('Background image Y:', backgroundImage.y());
                    console.log('Background image width:', backgroundImage.width());
                    console.log('Background image height:', backgroundImage.height());
                    console.log('Background image offsetX:', backgroundImage.offsetX());
                    console.log('Background image offsetY:', backgroundImage.offsetY());
                    console.log('Background image visible:', backgroundImage.visible());
                    console.log('Background image opacity:', backgroundImage.opacity());
                    console.log('Background actual center X:', backgroundImage.x() + (backgroundImage.width() / 2));
                    console.log('Canvas center X:', canvasWidth / 2);
                    console.log('Difference:', Math.abs((backgroundImage.x() + (backgroundImage.width() / 2)) - (canvasWidth / 2)));
                    console.log('Layer children count:', layer.children.length);
                    console.log('Stage size:', stage.width(), 'x', stage.height());
                    
                    // Force redraw with batchDraw for performance
                    layer.batchDraw();
                    
                    // Additional verification
                    setTimeout(() => {
                        console.log('=== POST-RENDER CHECK ===');
                        console.log('Background still in layer:', layer.findOne('.background') ? 'YES' : 'NO');
                        console.log('Layer visible:', layer.visible());
                        console.log('Stage container:', stage.container());
                    }, 100);
                };
                
                imageObj.onerror = function() {
                    console.error('Failed to load product image:', productImageUrl);
                    
                    // Create a placeholder rectangle if image fails to load
                    backgroundImage = new Konva.Rect({
                        x: 0,
                        y: 0,
                        width: stage.width(),
                        height: stage.height(),
                        fill: '#D2B48C', // Tan color for leather
                        stroke: '#8B4513',
                        strokeWidth: 2,
                        draggable: false,
                        selectable: false,
                        listening: false,
                        name: 'background'
                    });
                    
                    // Add product name as text overlay
                    const productLabel = new Konva.Text({
                        x: stage.width() / 2,
                        y: stage.height() / 2,
                        text: productName.toUpperCase(),
                        fontSize: 24,
                        fontFamily: 'Arial',
                        fill: '#8B4513',
                        align: 'center',
                        verticalAlign: 'middle',
                        draggable: false,
                        selectable: false,
                        listening: false,
                        name: 'background'
                    });
                    productLabel.offsetX(productLabel.width() / 2);
                    productLabel.offsetY(productLabel.height() / 2);
                    
                    layer.add(backgroundImage);
                    layer.add(productLabel);
                    backgroundImage.moveToBottom();
                    productLabel.moveToBottom();
                    layer.draw();
                    
                    console.log('Created placeholder background for product:', productName);
                };
                
                imageObj.src = productImageUrl;
            }

            // Add user text to canvas
        function addUserText() {
                const productName = '{{ $product->name }}';
                const isBracelet = productName === 'bracelet';
                
                // For bracelets, build text from only the text/number selections (stamps handled separately)
                let userText;
                if (isBracelet) {
                    const selections = @json($selections ?? []);
                    const textOnly = selections.filter(s => s.type === 'letter' || s.type === 'number').map(s => s.value).join('');
                    userText = textOnly || '';
                    console.log('Bracelet - using selections for text:', selections);
                    console.log('Bracelet - text only:', textOnly);
                } else {
                    userText = '{{ implode("", $textCharacters) }}';
                }
                
                console.log('Adding user text:', userText, 'for product:', productName);
                
                // Check if product is vertical (bracelet or bookmark)
                const isVerticalProduct = productName === 'bracelet' || productName === 'bookmark';
                
                // Only add text node if there's text to display
                if (userText && userText.length > 0) {
                    textNode = new Konva.Text({
                        x: stage.width() / 2,
                        y: stage.height() / 2,
                        text: userText,
                        fontSize: isVerticalProduct ? 20 : 24,
                        fontFamily: 'Arial',
            fill: '#371C16',
                        align: 'center',
                        verticalAlign: 'middle',
                        draggable: !isBracelet, // Lock dragging for bracelets
                        selectable: !isBracelet, // Lock selection for bracelets
                        listening: !isBracelet, // Disable interaction for bracelets
                        name: 'userText',
                        rotation: isVerticalProduct ? 90 : 0 // Rotate 90 degrees for vertical products
                    });
                    
                    // Center the text
                    textNode.offsetX(textNode.width() / 2);
                    textNode.offsetY(textNode.height() / 2);
                    
                    layer.add(textNode);
                    textNode.moveToTop(); // Ensure text is on top
                    console.log('User text added to canvas with rotation:', isVerticalProduct ? '90 degrees' : '0 degrees');
                    console.log('Text interaction locked:', isBracelet);
                } else {
                    console.log('No text to display (stamps only)');
                }
                
                layer.draw();
            }

            // Add stamp to canvas
            function addStampToCanvas(stampFile, stampDirectory) {
                // Use provided directory or default to 'small' for backward compatibility
                const directory = stampDirectory || 'small';
                const stampUrl = `/images/stamps/${directory}/${stampFile}`;
                const productName = '{{ $product->name }}';
                const isBracelet = productName === 'bracelet';
                console.log('Adding stamp:', stampUrl, 'from directory:', directory);
                console.log('Is bracelet (locked):', isBracelet);
                
                const imageObj = new Image();
                imageObj.crossOrigin = 'anonymous';
                
                imageObj.onload = function() {
                    console.log('Stamp image loaded:', imageObj.width, 'x', imageObj.height);
                    
                    // Calculate size (max 80px while maintaining aspect ratio)
                    const maxSize = 80;
                    const aspect = imageObj.width / imageObj.height;
                    let width, height;
                    
                    if (aspect > 1) {
                        width = maxSize;
                        height = maxSize / aspect;
                    } else {
                        height = maxSize;
                        width = maxSize * aspect;
                    }
                    
                    // Position stamp - centered for bracelets, random for others
                    let x, y;
                    if (isBracelet) {
                        // Center stamps for bracelets
                        x = (stage.width() - width) / 2;
                        y = (stage.height() - height) / 2 + (stampNodes.length * 20); // Offset each stamp slightly
                    } else {
                        // Position randomly for other products
                        const maxX = Math.max(0, stage.width() - width);
                        const maxY = Math.max(0, stage.height() - height);
                        x = Math.random() * maxX;
                        y = Math.random() * maxY;
                    }
                    
                    const stampNode = new Konva.Image({
                        x: x,
                        y: y,
                        image: imageObj,
                        width: width,
                        height: height,
                        draggable: !isBracelet, // Lock dragging for bracelets
                        selectable: !isBracelet, // Lock selection for bracelets
                        listening: !isBracelet, // Disable interaction for bracelets
                        name: 'stamp'
                    });
                    
                    layer.add(stampNode);
                    stampNodes.push(stampNode);
                    stampNode.moveToTop(); // Ensure stamp is on top
                    
                    console.log('Stamp added to canvas:', x, y, width, height);
                    console.log('Stamp interaction locked:', isBracelet);
                    layer.draw();
                    
                    // Auto-select the newly added stamp (only for non-bracelets)
                    if (!isBracelet) {
                        selectNode(stampNode);
                    }
                };
                
                imageObj.onerror = function() {
                    console.error('Failed to load stamp image:', stampUrl);
                    alert('Failed to load stamp image. Please try again.');
                };
                
                imageObj.src = stampUrl;
            }

            // Set up event listeners
            function setupEventListeners() {
                const productName = '{{ $product->name }}';
                const isBracelet = productName === 'bracelet';
                
                // Only set up interaction listeners for non-bracelets
                if (!isBracelet) {
                    // Handle clicks on the stage
                    stage.on('click tap', function(e) {
                        // If clicked on empty area or background, deselect
                        if (e.target === stage || e.target.name() === 'background') {
                            deselectAll();
                            return;
                        }
                        
                        // Only select interactive elements (not background)
                        if (e.target.name() !== 'background') {
                            selectNode(e.target);
                        }
                    });

                    // Handle drag end to update preview JSON
                    stage.on('dragend', function(e) {
                        // Only update if dragging interactive elements
                        if (e.target.name() !== 'background') {
                            updatePreviewJson();
                        }
                    });

                    // Handle transform end to update preview JSON
                    if (transformer) {
                        transformer.on('transformend', function() {
                            updatePreviewJson();
                        });
                    }
                } else {
                    console.log('Event listeners disabled for bracelet (locked preview)');
                }
            }

            // Select a node
            function selectNode(node) {
                // Deselect all first
                deselectAll();
                
                // Select the node (only if transformer exists - not for bracelets)
                selectedNode = node;
                if (transformer) {
                    transformer.nodes([node]);
                    transformer.getLayer().batchDraw();
                }
            }

            // Deselect all nodes
            function deselectAll() {
                selectedNode = null;
                if (transformer) {
                    transformer.nodes([]);
                    transformer.getLayer().batchDraw();
                }
            }

            // Delete selected node
        function deleteSelected() {
                if (selectedNode) {
                    // Remove from stampNodes array if it's a stamp
                    const index = stampNodes.indexOf(selectedNode);
                    if (index > -1) {
                        stampNodes.splice(index, 1);
                    }
                    
                    selectedNode.destroy();
                    deselectAll();
            updatePreviewJson();
                }
            }

            // Render elements in sequence for bracelets (text + stamps in order)
            function renderSequentialElements() {
                const productName = '{{ $product->name }}';
                const braceletSize = '{{ $size }}';
                console.log('=== RENDERING SEQUENTIAL ELEMENTS FOR BRACELET ===');
                console.log('Bracelet size:', braceletSize);
                
                // Get selections array (preserves order)
                const selections = @json($selections ?? []);
                console.log('Selections:', selections);
                
                if (!selections || selections.length === 0) {
                    console.log('No selections to render');
                    return;
                }
                
                const totalElements = selections.length;
                const canvasHeight = stage.height();
                const canvasWidth = stage.width();
                
                // Define safe zones - bracelet boundaries (exclude button hole areas)
                // Corrected positioning to account for 2 steel buttons at each end
                const topButtonZone = canvasHeight * 0.22; // Below the second (lower) top steel button
                const bottomButtonZone = canvasHeight * 0.78; // Above the first (upper) bottom steel button
                const padding = 12; // Adequate padding from steel buttons (10-15px range)
                
                // Calculate usable bracelet area
                const usableStartY = topButtonZone + padding;
                const usableEndY = bottomButtonZone - padding;
                const usableHeight = usableEndY - usableStartY;
                
                console.log(`Canvas height: ${canvasHeight}px`);
                console.log(`Usable area: ${usableStartY}px to ${usableEndY}px (${usableHeight}px total)`);
                
                // Calculate element size and spacing to fit within boundaries
                // Proper spacing between steel buttons with 2-3px gaps
                const maxElementSize = Math.min(30, usableHeight / (totalElements * 1.1)); // 1.1 factor for proper spacing
                const elementSize = Math.max(18, maxElementSize); // Min 18px, max 30px (much smaller elements)
                const totalElementsHeight = elementSize * totalElements;
                const totalGapSpace = usableHeight - totalElementsHeight;
                const spacing = Math.max(2, totalGapSpace / (totalElements + 1)); // Min 2px spacing (proper gaps)
                
                console.log(`Element size: ${elementSize}px, Spacing: ${spacing}px`);
                console.log(`Total elements height: ${totalElementsHeight}px`);
                console.log(`Total gap space: ${totalGapSpace}px`);
                
                // Calculate starting Y position to center content between steel buttons
                // Ensure content starts below top steel button with proper padding
                const totalContentHeight = totalElementsHeight + (spacing * (totalElements - 1));
                const startY = usableStartY + ((usableHeight - totalContentHeight) / 2); // Center content in available space
                
                console.log(`Starting Y: ${startY}px`);
                console.log(`Content will span from ${startY}px to ${startY + totalContentHeight}px`);
                
                // Verify all elements will be within boundaries
                const lastElementY = startY + (totalElements - 1) * (elementSize + spacing) + elementSize;
                if (lastElementY > usableEndY) {
                    console.warn(`WARNING: Last element at ${lastElementY}px exceeds boundary ${usableEndY}px`);
                }
                
                // Render each element in sequence
                selections.forEach((selection, index) => {
                    const posY = startY + (index * (elementSize + spacing)) + (elementSize / 2);
                    const posX = canvasWidth / 2;
                    
                    console.log(`Element ${index + 1}/${totalElements}: type=${selection.type}, value=${selection.value}, pos=(${posX}, ${posY})`);
                    
                    if (selection.type === 'stamp') {
                        // Render stamp at calculated position
                        setTimeout(() => {
                            addSequentialStamp(selection.value, posX, posY, elementSize);
                        }, index * 100);
                    } else {
                        // Render text character at calculated position
                        addSequentialText(selection.value, posX, posY, elementSize);
                    }
                });
            }
            
            // Add text character at specific position (for sequential rendering) - ROTATED 90° for bracelet
            function addSequentialText(character, x, y, size) {
                console.log(`Adding ROTATED text "${character}" at (${x}, ${y})`);
                
                const textElement = new Konva.Text({
                    x: x,
                    y: y,
                    text: character,
                    fontSize: size * 0.7, // Reduced to 70% of element size for subtle engraved appearance
                    fontFamily: 'Arial',
                    fontWeight: 'bold',
                    fill: '#371C16',
                    align: 'center',
                    verticalAlign: 'middle',
                    draggable: false,
                    selectable: false,
                    listening: false,
                    name: 'sequentialText',
                    rotation: 90, // ROTATE 90° clockwise for vertical bracelet orientation
                });
                
                // Center the text at the position
                textElement.offsetX(textElement.width() / 2);
                textElement.offsetY(textElement.height() / 2);
                
                layer.add(textElement);
                textElement.moveToTop();
                layer.draw();
            }
            
            // Add stamp at specific position (for sequential rendering) - ROTATED 90° for bracelet
            function addSequentialStamp(filename, x, y, size) {
                const directory = 'small'; // Always small for bracelets
                const stampUrl = `/images/stamps/${directory}/${filename}`;
                console.log(`Adding ROTATED stamp "${filename}" at (${x}, ${y})`);
                
                const imageObj = new Image();
                imageObj.crossOrigin = 'anonymous';
                
                imageObj.onload = function() {
                    const stampNode = new Konva.Image({
                        x: x,
                        y: y,
                        image: imageObj,
                        width: size * 0.8, // Reduced to 80% of element size for subtle appearance
                        height: size * 0.8, // Reduced to 80% of element size for subtle appearance
                        draggable: false,
                        selectable: false,
                        listening: false,
                        name: 'sequentialStamp',
                        rotation: 90, // ROTATE 90° clockwise for vertical bracelet orientation
                    });
                    
                    // Center the stamp at the position
                    stampNode.offsetX((size * 0.8) / 2);
                    stampNode.offsetY((size * 0.8) / 2);
                    
                    layer.add(stampNode);
                    stampNodes.push(stampNode);
                    stampNode.moveToTop();
                    layer.draw();
                    
                    console.log(`ROTATED stamp "${filename}" rendered successfully`);
                };
                
                imageObj.onerror = function() {
                    console.error('Failed to load stamp:', stampUrl);
                };
                
                imageObj.src = stampUrl;
            }

            // Add text character for keychain (HORIZONTAL orientation - NO rotation)
            function addKeychainText(character, x, y, size) {
                console.log(`Adding HORIZONTAL keychain text "${character}" at (${x}, ${y})`);
                
                const textElement = new Konva.Text({
                    x: x,
                    y: y,
                    text: character,
                    fontSize: size * 0.8, // 80% of element size
                    fontFamily: 'Arial',
                    fontWeight: 'bold',
                    fill: '#371C16',
                    align: 'center',
                    verticalAlign: 'middle',
                    draggable: false,
                    selectable: false,
                    listening: false,
                    name: 'keychainText',
                    rotation: 0, // NO ROTATION - always horizontal for keychain
                });
                
                // Center the text at the position
                textElement.offsetX(textElement.width() / 2);
                textElement.offsetY(textElement.height() / 2);
                
                layer.add(textElement);
                textElement.moveToTop();
                layer.draw();
            }

            // Add stamp for keychain (HORIZONTAL orientation - NO rotation)
            function addKeychainStamp(filename, x, y, size, directory = 'large') {
                const stampUrl = `/images/stamps/${directory}/${filename}`;
                console.log(`Adding HORIZONTAL keychain stamp "${filename}" at (${x}, ${y}) from ${directory} directory`);
                
                const imageObj = new Image();
                imageObj.crossOrigin = 'anonymous';
                
                imageObj.onload = function() {
                    const stampNode = new Konva.Image({
                        x: x,
                        y: y,
                        image: imageObj,
                        width: size,
                        height: size,
                        draggable: false,
                        selectable: false,
                        listening: false,
                        name: 'keychainStamp',
                        rotation: 0, // NO ROTATION - always horizontal for keychain
                    });
                    
                    // Center the stamp at the position
                    stampNode.offsetX(size / 2);
                    stampNode.offsetY(size / 2);
                    
                    layer.add(stampNode);
                    stampNodes.push(stampNode);
                    stampNode.moveToTop();
                    layer.draw();
                    
                    console.log(`HORIZONTAL keychain stamp "${filename}" rendered successfully`);
                };
                
                imageObj.onerror = function() {
                    console.error('Failed to load keychain stamp:', stampUrl);
                };
                
                imageObj.src = stampUrl;
            }

            // Render Keychain Version 1: 3 letters HORIZONTALLY + 1 large stamp below
            function renderKeychainV1() {
                console.log('=== RENDERING KEYCHAIN VERSION 1 (HORIZONTAL TEXT LAYOUT) ===');
                
                const letters = @json($textCharacters ?? []);
                const stamps = @json($selectedStamps ?? []);
                
                console.log('Letters:', letters);
                console.log('Stamps:', stamps);
                
                if (letters.length !== 3) {
                    console.error('Expected 3 letters for keychain v1, got:', letters.length);
                    return;
                }
                
                // Use actual background image dimensions
                if (!backgroundImage) {
                    console.error('Background image not loaded yet!');
                    return;
                }
                
                // Get actual keychain image boundaries
                const imageX = backgroundImage.x();
                const imageY = backgroundImage.y();
                const imageWidth = backgroundImage.width();
                const imageHeight = backgroundImage.height();
                const keychainCenterX = imageX + (imageWidth / 2);
                
                console.log('Keychain image:', imageWidth, 'x', imageHeight, 'at', imageX, imageY);
                
                // Define button position relative to keychain image - OPTIMIZED positioning
                const buttonY = imageY + (imageHeight * 0.26);
                const buttonSize = imageWidth * 0.08;
                const buttonClearance = imageWidth * 0.15; // OPTIMIZED clearance (15% for perfect separation)
                
                // Define safe zone below button - OPTIMIZED for perfect clearance
                const bottomSafeZone = {
                    start: buttonY + buttonSize + buttonClearance + 20, // Extra 20px buffer for guaranteed clearance
                    end: imageY + (imageHeight * 0.80) // Conservative end (80% for better fit)
                };
                
                console.log('=== OPTIMIZED BUTTON CLEARANCE (VERSION 1 ONLY) ===');
                console.log('Button at Y:', buttonY.toFixed(1));
                console.log('Button size:', buttonSize.toFixed(1), 'px');
                console.log('Button clearance:', buttonClearance.toFixed(1), 'px (15% - OPTIMIZED)');
                console.log('Extra buffer:', '20px');
                console.log('Bottom safe zone:', bottomSafeZone.start.toFixed(1), 'to', bottomSafeZone.end.toFixed(1));
                console.log('Safe zone height:', (bottomSafeZone.end - bottomSafeZone.start).toFixed(1), 'px');
                
                // Scale element sizes relative to keychain - optimized for horizontal layout
                const letterSize = imageWidth * 0.18; // 18% for good readability in horizontal arrangement
                const stampSize = imageWidth * 0.35; // 35% for prominent stamp below text
                const letterSpacing = imageWidth * 0.04; // Horizontal spacing between letters
                
                console.log('Letter size:', letterSize.toFixed(1), 'px (18% - HORIZONTAL LAYOUT)');
                console.log('Stamp size:', stampSize.toFixed(1), 'px (35% - PROMINENT FOCAL POINT)');
                console.log('Letter spacing:', letterSpacing.toFixed(1), 'px (4% horizontal gap)');
                
                // Position 3 letters HORIZONTALLY in bottom safe zone - OPTIMIZED positioning
                const lettersAreaWidth = (letterSize * 3) + (letterSpacing * 2);
                const lettersStartX = keychainCenterX - (lettersAreaWidth / 2) + (letterSize / 2);
                const textRowY = bottomSafeZone.start + 30 + (letterSize / 2); // OPTIMIZED buffer (30px for perfect clearance)
                
                console.log('Horizontal text layout:');
                console.log('- Text row width:', lettersAreaWidth.toFixed(1), 'px');
                console.log('- Text row Y:', textRowY.toFixed(1), 'px');
                console.log('- Starting X:', lettersStartX.toFixed(1), 'px');
                
                letters.forEach((letter, index) => {
                    const posX = lettersStartX + (index * (letterSize + letterSpacing));
                    console.log(`Letter ${index + 1} "${letter}" at (${posX.toFixed(1)}, ${textRowY.toFixed(1)})`);
                    addKeychainText(letter, posX, textRowY, letterSize); // Use keychain-specific function for horizontal text
                });
                
                // Position large stamp DIRECTLY BELOW the horizontal text - REDUCED spacing
                if (stamps.length > 0) {
                    const stamp = stamps[0];
                    const filename = stamp.filename || stamp;
                    const directory = stamp.directory || 'large';
                    const stampY = textRowY + (letterSize / 2) + 15 + (stampSize / 2); // REDUCED gap (15px for closer alignment)
                    
                    console.log(`Stamp centered below text at (${keychainCenterX.toFixed(1)}, ${stampY.toFixed(1)}) - REDUCED spacing (15px gap)`);
                    
                    setTimeout(() => {
                        addKeychainStamp(filename, keychainCenterX, stampY, stampSize, 'large'); // Use keychain-specific function for horizontal stamp
                    }, 200);
                }
                
                console.log('Keychain V1 rendering complete');
            }

            // Render Keychain Version 2: 6 letters in circle + 1 small stamp in center
            function renderKeychainV2() {
                console.log('=== RENDERING KEYCHAIN VERSION 2 (EMERGENCY FIX) ===');
                
                const letters = @json($textCharacters ?? []);
                const stamps = @json($selectedStamps ?? []);
                
                console.log('Letters:', letters);
                console.log('Stamps:', stamps);
                
                if (letters.length !== 6) {
                    console.error('Expected 6 letters for keychain v2, got:', letters.length);
                    return;
                }
                
                // CRITICAL FIX: Use actual background image dimensions, not canvas dimensions
                if (!backgroundImage) {
                    console.error('Background image not loaded yet!');
                    return;
                }
                
                // Get actual keychain image boundaries
                const imageX = backgroundImage.x();
                const imageY = backgroundImage.y();
                const imageWidth = backgroundImage.width();
                const imageHeight = backgroundImage.height();
                
                console.log('=== KEYCHAIN IMAGE BOUNDARIES ===');
                console.log('Image position:', imageX, imageY);
                console.log('Image dimensions:', imageWidth, 'x', imageHeight);
                
                // Calculate center of the actual keychain image
                const keychainCenterX = imageX + (imageWidth / 2);
                const keychainCenterY = imageY + (imageHeight / 2);
                
                console.log('Keychain center:', keychainCenterX, keychainCenterY);
                
                // Define button/rivet position relative to keychain image
                // Button is at approximately 26% from top of the keychain
                const buttonY = imageY + (imageHeight * 0.26);
                const buttonSize = imageWidth * 0.08; // Button is about 8% of keychain width
                const buttonClearance = imageHeight * 0.15; // AGGRESSIVE: 15% of height clearance
                
                // Calculate visual center for circular arrangement
                // AGGRESSIVE DOWNWARD SHIFT - Position circle in BOTTOM 2/3 of keychain
                // Top 40% = button safe zone (NO RENDERING)
                // Bottom 60% = text zone
                const visualCenterY = imageY + (imageHeight * 0.72); // 72% down from top (MAJOR SHIFT)
                
                // CRITICAL: Define circle radius based on KEYCHAIN IMAGE size, not canvas
                // Increase radius to accommodate MUCH LARGER text elements
                const circleRadius = imageWidth * 0.33; // 33% of keychain width (larger for bigger text)
                
                // Scale text sizes relative to keychain image - DRAMATICALLY INCREASED for readability
                const letterSize = imageWidth * 0.18; // 18% of keychain width (DOUBLED from original 8.5%)
                const stampSize = imageWidth * 0.28; // 28% of keychain width (DOUBLED from original 13%)
                
                console.log('=== POSITIONING PARAMETERS (MUCH LARGER READABLE SIZES) ===');
                console.log('Keychain image top:', imageY.toFixed(1));
                console.log('Keychain image height:', imageHeight.toFixed(1));
                console.log('Button Y position:', buttonY.toFixed(1), `(${((buttonY - imageY) / imageHeight * 100).toFixed(0)}% from top)`);
                console.log('Button clearance zone:', buttonClearance.toFixed(1), 'px');
                console.log('No-render zone: 0% - 45% of keychain height');
                console.log('Visual center Y:', visualCenterY.toFixed(1), `(${((visualCenterY - imageY) / imageHeight * 100).toFixed(0)}% from top)`);
                console.log('Circle radius:', circleRadius.toFixed(1), 'px (33% of width)');
                console.log('Letter size:', letterSize.toFixed(1), 'px (18% - DOUBLED FOR READABILITY)');
                console.log('Stamp size:', stampSize.toFixed(1), 'px (28% - DOUBLED FOR VISIBILITY)');
                console.log('Minimum safe Y for text:', (imageY + (imageHeight * 0.45)).toFixed(1), '(45% mark)');
                
                // Arrange 6 letters in circle around the perimeter
                // Start from top and go clockwise with equal spacing
                const angleStep = (2 * Math.PI) / 6; // 60 degrees between each letter
                const startAngle = -Math.PI / 2; // Start at top (270°)
                
                console.log('=== LETTER POSITIONING ===');
                
                letters.forEach((letter, index) => {
                    const angle = startAngle + (index * angleStep);
                    
                    // Calculate position on circle relative to visual center
                    let x = keychainCenterX + (circleRadius * Math.cos(angle));
                    let y = visualCenterY + (circleRadius * Math.sin(angle));
                    
                    // Calculate minimum safe Y position (below button + AGGRESSIVE clearance)
                    const buttonBottom = buttonY + (buttonSize / 2);
                    const minSafeY = buttonBottom + buttonClearance + (letterSize / 2);
                    
                    // Define strict boundaries based on keychain image
                    const padding = letterSize / 2 + 5; // Half letter size plus 5px safety margin
                    const minX = imageX + padding;
                    const maxX = imageX + imageWidth - padding;
                    // AGGRESSIVE: Top 45% of keychain is NO-RENDER zone
                    const minY = Math.max(imageY + (imageHeight * 0.45), minSafeY); // Stricter: 45% from top
                    const maxY = imageY + (imageHeight * 0.92); // Allow text up to 92% (tighter bottom)
                    
                    // Enforce button clearance - push down if too close
                    if (y < minSafeY) {
                        const originalY = y;
                        y = minSafeY;
                        console.log(`  Letter ${index + 1} "${letter}" adjusted Y: ${originalY.toFixed(1)} -> ${y.toFixed(1)} (button clearance)`);
                    }
                    
                    // Enforce strict boundaries - clamp to keychain image area
                    x = Math.max(minX, Math.min(maxX, x));
                    y = Math.max(minY, Math.min(maxY, y));
                    
                    const angleDegrees = (angle * 180 / Math.PI + 360) % 360;
                    const percentFromTop = ((y - imageY) / imageHeight * 100).toFixed(0);
                    console.log(`Letter ${index + 1} "${letter}" at ${angleDegrees.toFixed(0)}° => (${x.toFixed(1)}, ${y.toFixed(1)}) [${percentFromTop}% from top]`);
                    
                    // Verify not in button zone
                    if (y < minSafeY) {
                        console.warn(`  ⚠️ WARNING: Letter still too close to button!`);
                    } else {
                        const clearance = y - (buttonY + buttonSize/2);
                        console.log(`  ✓ Button clearance: ${clearance.toFixed(1)}px`);
                    }
                    
                    addKeychainText(letter, x, y, letterSize); // Use keychain-specific function for horizontal text
                });
                
                // Position small stamp in center of keychain body, below button
                // Use keychain center, not canvas center
                const stampCenterX = keychainCenterX;
                const stampCenterY = visualCenterY; // Use exact visual center
                
                console.log('=== STAMP POSITIONING ===');
                console.log(`Stamp center at (${stampCenterX.toFixed(1)}, ${stampCenterY.toFixed(1)})`);
                console.log(`Stamp will be ${(stampCenterY - buttonY).toFixed(1)}px below button`);
                console.log(`Stamp size: ${stampSize.toFixed(1)}px`);
                
                if (stamps.length > 0) {
                    const stamp = stamps[0];
                    const filename = stamp.filename || stamp;
                    const directory = stamp.directory || 'small';
                    
                    setTimeout(() => {
                        addKeychainStamp(filename, stampCenterX, stampCenterY, stampSize, 'small'); // Use keychain-specific function for horizontal stamp
                    }, 400);
                }
                
                console.log('Keychain V2 rendering complete');
            }

            // ========== BOOKMARK RENDER FUNCTIONS ==========
            
            // Render Bookmark Style 1: Top stamp + 7 text + Bottom stamp
            function renderBookmarkStyle1() {
                console.log('=== RENDERING BOOKMARK STYLE 1 ===');
                
                const letters = @json($textCharacters ?? []);
                const stamps = @json($selectedStamps ?? []);
                
                console.log('Letters:', letters);
                console.log('Stamps:', stamps);
                
                if (!backgroundImage) {
                    console.error('Background image not loaded yet');
                    return;
                }
                
                // Get bookmark dimensions from stored values
                const imageWidth = backgroundImageDimensions.width;
                const imageHeight = backgroundImageDimensions.height;
                const imageX = backgroundImageDimensions.x;
                const imageY = backgroundImageDimensions.y;
                
                // Calculate center position with slight right adjustment for perfect centering
                const centerX = imageX + (imageWidth / 2) + (imageWidth * 0.16); // 16% offset to the right
                
                console.log(`=== BOOKMARK STYLE 1 POSITIONING ===`);
                console.log(`Image: ${imageWidth.toFixed(1)}w x ${imageHeight.toFixed(1)}h`);
                console.log(`Image position: (${imageX.toFixed(1)}, ${imageY.toFixed(1)})`);
                console.log(`Image bounds: X from ${imageX.toFixed(1)} to ${(imageX + imageWidth).toFixed(1)}`);
                console.log(`Center X: ${centerX.toFixed(1)}`);
                
                // Define elements to distribute evenly from below the hole to bottom
                const stampSize = imageWidth * 0.28; // 28% of bookmark width
                const letterSize = imageWidth * 0.18; // 18% of bookmark width
                const topStartOffsetPx = 160; // starting boundary below hole (closer to hole)

                const elements = [];
                if (stamps.length > 0 && stamps[0]) {
                    const topStamp = stamps[0];
                    elements.push({ type: 'stamp', data: topStamp });
                }
                letters.forEach((letter) => {
                    if (letter && letter.trim() !== '') {
                        elements.push({ type: 'letter', data: letter });
                    }
                });
                if (stamps.length > 1 && stamps[1]) {
                    const bottomStamp = stamps[1];
                    elements.push({ type: 'stamp', data: bottomStamp });
                }

                const maxElementSize = Math.max(stampSize, letterSize);
                const safeTop = imageY + topStartOffsetPx + (maxElementSize / 2);
                const safeBottom = imageY + imageHeight - (maxElementSize / 2);
                const spacing = elements.length > 0 ? (safeBottom - safeTop) / (elements.length + 1) : 0;
                console.log(`Even distribution: safeTop=${safeTop.toFixed(1)}, safeBottom=${safeBottom.toFixed(1)}, spacing=${spacing.toFixed(1)}, elements=${elements.length}`);

                elements.forEach((el, idx) => {
                    const y = safeTop + (idx + 1) * spacing;
                    if (el.type === 'stamp') {
                        const item = el.data;
                        const filename = item.filename || item;
                        const directory = item.directory || 'large';
                        setTimeout(() => {
                            addStampImage(`/images/stamps/${directory}/${filename}`, centerX, y, stampSize);
                        }, 100 * (idx + 1));
                    } else if (el.type === 'letter') {
                        const letter = el.data;
                        setTimeout(() => {
                            addBookmarkText(letter, centerX, y, letterSize);
                        }, 100 * (idx + 1));
                    }
                });
                
                console.log('Bookmark Style 1 rendering complete');
            }
            
            // Render Bookmark Style 2: 6 stamps only
            function renderBookmarkStyle2() {
                console.log('=== RENDERING BOOKMARK STYLE 2 ===');
                
                const stamps = @json($selectedStamps ?? []);
                
                console.log('Stamps:', stamps);
                
                if (!backgroundImage) {
                    console.error('Background image not loaded yet');
                    return;
                }
                
                // Get bookmark dimensions from stored values
                const imageWidth = backgroundImageDimensions.width;
                const imageHeight = backgroundImageDimensions.height;
                const imageX = backgroundImageDimensions.x;
                const imageY = backgroundImageDimensions.y;
                
                // Calculate center position with slight right adjustment for perfect centering
                const centerX = imageX + (imageWidth / 2) + (imageWidth * 0.16); // 16% offset to the right
                
                console.log(`=== BOOKMARK STYLE 2 POSITIONING ===`);
                console.log(`Image: ${imageWidth.toFixed(1)}w x ${imageHeight.toFixed(1)}h`);
                console.log(`Image position: (${imageX.toFixed(1)}, ${imageY.toFixed(1)})`);
                console.log(`Image bounds: X from ${imageX.toFixed(1)} to ${(imageX + imageWidth).toFixed(1)}`);
                console.log(`Center X: ${centerX.toFixed(1)}`);
                
                // Even distribution for stamps-only style
                const stampSize = imageWidth * 0.28; // 28% of bookmark width for better proportion
                const topStartOffsetPx = 160; // starting boundary below hole (closer to hole)
                const maxElementSize = stampSize;
                const safeTop = imageY + topStartOffsetPx + (maxElementSize / 2);
                const safeBottom = imageY + imageHeight - (maxElementSize / 2);
                const spacing = stamps.length > 0 ? (safeBottom - safeTop) / (stamps.length + 1) : 0;
                console.log(`Even distribution (style 2): safeTop=${safeTop.toFixed(1)}, safeBottom=${safeBottom.toFixed(1)}, spacing=${spacing.toFixed(1)}, elements=${stamps.length}`);

                // Render each stamp with even spacing
                stamps.forEach((stamp, index) => {
                    if (stamp) {
                        const filename = stamp.filename || stamp;
                        const directory = stamp.directory || 'large';
                        const y = safeTop + (index + 1) * spacing;
                        setTimeout(() => {
                            addStampImage(`/images/stamps/${directory}/${filename}`, centerX, y, stampSize);
                        }, 100 * (index + 1));
                    }
                });
                
                console.log('Bookmark Style 2 rendering complete');
            }
            
            // Render Bookmark Style 3: 8 text + Bottom stamp
            function renderBookmarkStyle3() {
                console.log('=== RENDERING BOOKMARK STYLE 3 ===');
                
                const letters = @json($textCharacters ?? []);
                const stamps = @json($selectedStamps ?? []);
                
                console.log('Letters:', letters);
                console.log('Stamps:', stamps);
                
                if (!backgroundImage) {
                    console.error('Background image not loaded yet');
                    return;
                }
                
                // Get bookmark dimensions from stored values
                const imageWidth = backgroundImageDimensions.width;
                const imageHeight = backgroundImageDimensions.height;
                const imageX = backgroundImageDimensions.x;
                const imageY = backgroundImageDimensions.y;
                
                // Calculate center position with slight right adjustment for perfect centering
                const centerX = imageX + (imageWidth / 2) + (imageWidth * 0.16); // 16% offset to the right
                
                console.log(`=== BOOKMARK STYLE 3 POSITIONING ===`);
                console.log(`Image: ${imageWidth.toFixed(1)}w x ${imageHeight.toFixed(1)}h`);
                console.log(`Image position: (${imageX.toFixed(1)}, ${imageY.toFixed(1)})`);
                console.log(`Image bounds: X from ${imageX.toFixed(1)} to ${(imageX + imageWidth).toFixed(1)}`);
                console.log(`Center X: ${centerX.toFixed(1)}`);
                
                // Even distribution for text plus optional bottom stamp
                const topStartOffsetPx = 160; // starting boundary below hole (closer to hole)
                const stampSize = imageWidth * 0.28; // 28% of bookmark width
                const letterSize = imageWidth * 0.18; // 18% of bookmark width

                const elements = [];
                letters.forEach((letter) => {
                    if (letter && letter.trim() !== '') {
                        elements.push({ type: 'letter', data: letter });
                    }
                });
                if (stamps.length > 0 && stamps[0]) {
                    const bottomStamp = stamps[0];
                    elements.push({ type: 'stamp', data: bottomStamp });
                }

                const maxElementSize = Math.max(stampSize, letterSize);
                const safeTop = imageY + topStartOffsetPx + (maxElementSize / 2);
                const safeBottom = imageY + imageHeight - (maxElementSize / 2);
                const spacing = elements.length > 0 ? (safeBottom - safeTop) / (elements.length + 1) : 0;
                console.log(`Even distribution (style 3): safeTop=${safeTop.toFixed(1)}, safeBottom=${safeBottom.toFixed(1)}, spacing=${spacing.toFixed(1)}, elements=${elements.length}`);

                elements.forEach((el, idx) => {
                    const y = safeTop + (idx + 1) * spacing;
                    if (el.type === 'stamp') {
                        const item = el.data;
                        const filename = item.filename || item;
                        const directory = item.directory || 'large';
                        setTimeout(() => {
                            addStampImage(`/images/stamps/${directory}/${filename}`, centerX, y, stampSize);
                        }, 100 * (idx + 1));
                    } else {
                        const letter = el.data;
                        setTimeout(() => {
                            addBookmarkText(letter, centerX, y, letterSize);
                        }, 100 * (idx + 1));
                    }
                });
                
                console.log('Bookmark Style 3 rendering complete');
            }
            
            // Helper function to add stamp to bookmark
            function addStampImage(stampUrl, x, y, size) {
                console.log(`Adding bookmark stamp at (${x.toFixed(1)}, ${y.toFixed(1)}), size: ${size.toFixed(1)}`);
                
                const imageObj = new Image();
                imageObj.crossOrigin = 'anonymous';
                
                imageObj.onload = function() {
                    const stampNode = new Konva.Image({
                        x: x,
                        y: y,
                        image: imageObj,
                        width: size,
                        height: size,
                        draggable: false,
                        selectable: false,
                        listening: false,
                        name: 'bookmarkStamp',
                        rotation: 0,
                    });
                    
                    // Center the stamp at the position
                    stampNode.offsetX(size / 2);
                    stampNode.offsetY(size / 2);
                    
                    layer.add(stampNode);
                    stampNode.moveToTop();
                    layer.batchDraw();
                    
                    console.log(`Stamp centered at X:${x.toFixed(1)} with offset ${(size / 2).toFixed(1)}, final position: ${(x - size/2).toFixed(1)} to ${(x + size/2).toFixed(1)}`);
                };
                
                imageObj.onerror = function() {
                    console.error('Failed to load bookmark stamp:', stampUrl);
                };
                
                imageObj.src = stampUrl;
            }
            
            // Helper function to add text to bookmark (vertical layout)
            function addBookmarkText(text, x, y, size) {
                const textNode = new Konva.Text({
                    x: x,
                    y: y,
                    text: text,
                    fontSize: size,
                    fontFamily: 'Lato',
                    fontStyle: 'bold',
                    fill: '#371C16',
                    align: 'center',
                    verticalAlign: 'middle',
                });
                
                // Center the text at the position using actual text dimensions
                textNode.offsetX(textNode.width() / 2);
                textNode.offsetY(textNode.height() / 2);
                
                layer.add(textNode);
                layer.batchDraw();
                
                console.log(`Bookmark text "${text}" added at (${x}, ${y})`);
            }

            // Update preview JSON
        function updatePreviewJson() {
                const json = stage.toJSON();
                document.getElementById('previewJsonInput').value = JSON.stringify(json);
            }
            
            // Sync customer name from visible input to hidden form input
            function syncCustomerName() {
                const visibleInput = document.getElementById('customer_name');
                const hiddenInput = document.getElementById('customerNameInput');
                if (visibleInput && hiddenInput) {
                    hiddenInput.value = visibleInput.value;
                }
            }
            
            // Capture device fingerprint data
            function captureDeviceFingerprint() {
                try {
                    // Get screen resolution
                    const screenResolution = `${window.screen.width}x${window.screen.height}`;
                    
                    // Get user agent
                    const userAgent = navigator.userAgent;
                    
                    // Populate hidden fields
                    document.getElementById('deviceUserAgentInput').value = userAgent;
                    document.getElementById('deviceScreenResolutionInput').value = screenResolution;
                    
                    console.log('Device fingerprint captured:', {
                        userAgent: userAgent.substring(0, 50) + '...',
                        screenResolution: screenResolution
                    });
                } catch (error) {
                    console.error('Error capturing device fingerprint:', error);
                }
            }
            
            // Handle form submission
            function handleFormSubmission(event) {
                console.log('=== FORM SUBMISSION DEBUG START ===');
                console.log('Form submission started');
                console.log('Event type:', event.type);
                console.log('Form element:', event.target);
                
                // Capture device fingerprint
                captureDeviceFingerprint();
                
                // Sync customer name
                syncCustomerName();
                
                // Update preview JSON
                updatePreviewJson();
                
                // Validate required fields
                const customerName = document.getElementById('customerNameInput').value.trim();
                const previewJson = document.getElementById('previewJsonInput').value;
                
                console.log('Customer name:', customerName);
                console.log('Preview JSON length:', previewJson.length);
                console.log('Preview JSON preview:', previewJson.substring(0, 100) + '...');
                
                if (!customerName) {
                    console.log('Validation failed: No customer name');
                    event.preventDefault();
                    alert('Please enter your name before placing the order.');
                    return false;
                }
                
                if (!previewJson || previewJson === 'null') {
                    console.log('Validation failed: No preview JSON');
                    event.preventDefault();
                    alert('Please design your product before placing the order.');
                    return false;
                }
                
                console.log('Form validation passed, submitting...');
                console.log('Form action:', event.target.action);
                console.log('Form method:', event.target.method);
                console.log('=== FORM SUBMISSION DEBUG END ===');
                return true;
            }

            // Clean canvas functions removed - no longer needed

            // Initialize when DOM is loaded
            document.addEventListener('DOMContentLoaded', function() {
                console.log('DOM loaded, initializing Konva...');
                
                // Handle error message display
                const errorAlert = document.querySelector('.error-alert');
                if (errorAlert) {
                    // Scroll to error message
                    errorAlert.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    
                    // Add attention animation
                    errorAlert.style.animation = 'pulse 0.5s ease-in-out 3';
                    
                    // Disable submit button to prevent resubmission
                    const submitBtn = document.querySelector('button[type="submit"]');
                    if (submitBtn) {
                        submitBtn.disabled = true;
                        submitBtn.style.opacity = '0.5';
                        submitBtn.style.cursor = 'not-allowed';
                        submitBtn.textContent = '❌ Order Already Submitted';
                        submitBtn.style.background = '#6b7280';
                    }
                    
                    // Show browser alert for immediate attention
                    const errorText = errorAlert.querySelector('p').textContent.trim();
                    setTimeout(() => {
                        alert(errorText);
                    }, 500);
                    
                    console.log('Duplicate order error displayed - form disabled');
                }
                
                // Set up form submission handler
                const orderForm = document.getElementById('orderForm');
                if (orderForm) {
                    console.log('Form found:', orderForm);
                    console.log('Form action:', orderForm.action);
                    console.log('Form method:', orderForm.method);
                    orderForm.addEventListener('submit', handleFormSubmission);
                    console.log('Form submission handler attached');
                } else {
                    console.error('Form not found!');
                }
                
                // Set up real-time customer name syncing
                const customerNameInput = document.getElementById('customer_name');
                if (customerNameInput) {
                    customerNameInput.addEventListener('input', syncCustomerName);
                    customerNameInput.addEventListener('blur', syncCustomerName);
                    console.log('Customer name syncing set up');
                } else {
                    console.error('Customer name input not found!');
                }
                
                // Wait for container to be fully rendered
                setTimeout(() => {
                    const container = document.getElementById('konvaContainer');
                    console.log('Container found:', container);
                    console.log('Container dimensions before init:', container.offsetWidth, 'x', container.offsetHeight);
                    initKonva();
                }, 200);
            });

            // Handle window resize with mobile optimization - debounced
            let resizeTimeout;
            window.addEventListener('resize', function() {
                clearTimeout(resizeTimeout);
                resizeTimeout = setTimeout(function() {
                    if (stage) {
                        const container = document.getElementById('konvaContainer');
                        const productName = '{{ $product->name }}';
                        const isBookmark = productName === 'bookmark';
                        const isMobile = window.innerWidth <= 768;
                        const isSmallMobile = window.innerWidth <= 480;
                        const isTinyMobile = window.innerWidth <= 375;
                        
                        let containerWidth = container.offsetWidth || container.parentElement.offsetWidth;
                        let containerHeight;
                        
                        // Responsive height calculation - Bookmark-specific heights
                        if (isBookmark) {
                            if (isTinyMobile) {
                                containerHeight = 550;
                            } else if (isSmallMobile) {
                                containerHeight = 600;
                            } else if (isMobile) {
                                containerHeight = 650;
                            } else {
                                containerHeight = 600;
                            }
                        } else {
                            if (isTinyMobile) {
                                containerHeight = 480;
                            } else if (isSmallMobile) {
                                containerHeight = 500;
                            } else if (isMobile) {
                                containerHeight = 550;
                            } else {
                                containerHeight = 500;
                            }
                        }
                        
                        // Ensure width doesn't exceed viewport
                        if (isMobile) {
                            const maxMobileWidth = window.innerWidth - 32;
                            containerWidth = Math.min(containerWidth, maxMobileWidth);
                        }
                        
                        stage.width(containerWidth);
                        stage.height(containerHeight);
                        stage.batchDraw();
                        
                        console.log('Stage resized to:', containerWidth, 'x', containerHeight);
                    }
                }, 250); // Debounce resize events
            });
</script>
@endsection

@section('scripts')
<script>
        // Additional scripts if needed
</script>
@endsection