<!DOCTYPE html>
<html lang="lt">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Paminklų Konstruktorius</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/emailjs-com@3/dist/email.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Montserrat', sans-serif;
        }

        :root {
            --primary: #00A0E3;
            --primary-dark: #0085C7;
            --primary-light: #E6F5FC;
            --secondary: #FFC107;
            --dark: #333333;
            --gray: #666666;
            --light-gray: #F5F5F5;
            --white: #FFFFFF;
            --success: #4CAF50;
            --error: #F44336;
            --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            --shadow-hover: 0 6px 16px rgba(0, 0, 0, 0.12);
            --border-radius: 12px;
        }

        body {
            background-color: var(--light-gray);
            color: var(--dark);
            line-height: 1.6;
            min-height: 100vh;
            padding-bottom: 40px;
        }

        .container {
            width: 100%;
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 20px;
        }

        header {
            background-color: var(--white);
            box-shadow: var(--shadow);
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .navbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 0;
        }

        .logo {
            font-size: 24px;
            font-weight: 700;
            color: var(--primary);
            text-decoration: none;
            display: flex;
            align-items: center;
        }

        .logo i {
            margin-right: 10px;
            color: var(--primary);
        }

        .nav-links {
            display: flex;
            list-style: none;
        }

        .nav-links li {
            margin-left: 30px;
        }

        .nav-links a {
            text-decoration: none;
            color: var(--dark);
            font-weight: 500;
            transition: color 0.3s;
            position: relative;
            padding: 5px 0;
        }

        .nav-links a::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 0;
            height: 2px;
            background: var(--primary);
            transition: width 0.3s ease;
        }

        .nav-links a:hover::after {
            width: 100%;
        }

        .nav-links a:hover {
            color: var(--primary);
        }

        .hero {
            padding: 60px 0 40px;
            text-align: center;
        }

        .hero h1 {
            font-size: 2.8rem;
            margin-bottom: 20px;
            color: var(--dark);
            font-weight: 700;
            line-height: 1.2;
        }

        .hero p {
            font-size: 1.2rem;
            max-width: 700px;
            margin: 0 auto 40px;
            color: var(--gray);
        }

        .section-title {
            font-size: 1.8rem;
            margin-bottom: 25px;
            color: var(--dark);
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: 600;
        }

        .section-title i {
            color: var(--primary);
            background: var(--primary-light);
            width: 45px;
            height: 45px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 40px;
            margin-top: 30px;
        }

        @media (max-width: 992px) {
            .main-content {
                grid-template-columns: 1fr;
            }
        }

        .preview-section {
            background: var(--white);
            border-radius: var(--border-radius);
            padding: 30px;
            box-shadow: var(--shadow);
            display: flex;
            flex-direction: column;
            height: fit-content;
        }

        .monument-preview {
            position: relative;
            width: 100%;
            height: 500px;
            background: var(--primary-light);
            border-radius: var(--border-radius);
            overflow: hidden;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid #e0e0e0;
        }

        .monument-base {
            position: relative;
            width: 300px;
            height: 400px;
        }

        .monument-part {
            position: absolute;
            width: 100%;
            height: 100%;
            background-size: contain;
            background-position: center;
            background-repeat: no-repeat;
            transition: all 0.5s ease;
            left: 50%;
            transform: translateX(-50%);
        }

        #paminklai-part {
            z-index: 40;
        }

        #plokstes-part {
            z-index: 30;
        }

        #sonai-part {
            z-index: 20;
        }

        #takai-part {
            z-index: 10;
        }

        .controls-section {
            background: var(--white);
            border-radius: var(--border-radius);
            padding: 30px;
            box-shadow: var(--shadow);
        }

        /* Тип выбора в правой колонке */
        .type-selection {
            background: var(--white);
            border-radius: var(--border-radius);
            padding: 20px;
            margin-bottom: 30px;
            box-shadow: var(--shadow);
        }

        .type-title {
            font-size: 1.3rem;
            margin-bottom: 20px;
            color: var(--dark);
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .type-options {
            display: flex;
            gap: 15px;
        }

        .type-option {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            cursor: pointer;
            padding: 15px;
            border-radius: var(--border-radius);
            transition: all 0.3s;
            background: var(--white);
            border: 2px solid #eee;
            box-shadow: var(--shadow);
        }

        .type-option:hover {
            transform: translateY(-3px);
            box-shadow: var(--shadow-hover);
        }

        .type-option.active {
            background-color: var(--primary-light);
            border: 2px solid var(--primary);
        }

        .type-icon {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            color: var(--white);
            margin-bottom: 10px;
            background: var(--primary);
        }

        .type-name {
            font-weight: 600;
            font-size: 1rem;
            color: var(--dark);
            text-align: center;
        }

        /* Изменение здесь: вместо grid используем flex в колонку */
        .controls-grid {
            display: flex;
            flex-direction: column;
            gap: 25px;
        }

        .control-group {
            background: var(--white);
            border-radius: var(--border-radius);
            padding: 0;
            border: 1px solid #eee;
            transition: transform 0.3s, box-shadow 0.3s;
            box-shadow: var(--shadow);
            overflow: hidden;
        }

        .control-group:hover {
            transform: translateY(-5px);
            box-shadow: var(--shadow-hover);
        }

        .group-header {
            padding: 20px;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .group-title {
            font-size: 1.3rem;
            color: var(--dark);
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 600;
            margin: 0;
        }

        .group-title i {
            color: var(--primary);
        }

        .group-content {
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease-out;
        }

        .group-content.active {
            max-height: 800px;
            /* Достаточно большое значение для контента */
        }

        .group-inner {
            padding: 0 20px 20px;
        }

        .component-select {
            width: 100%;
            padding: 12px 15px;
            border-radius: 8px;
            border: 2px solid #e0e0e0;
            background-color: var(--white);
            font-size: 1rem;
            color: var(--dark);
            cursor: pointer;
            transition: all 0.3s;
            margin-bottom: 15px;
            font-weight: 500;
        }

        .component-select:hover {
            border-color: var(--primary);
        }

        .component-select:focus {
            border-color: var(--primary);
            outline: none;
            box-shadow: 0 0 0 3px rgba(0, 160, 227, 0.2);
        }

        .loader {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(0, 160, 227, 0.3);
            border-radius: 50%;
            border-top-color: var(--primary);
            animation: spin 1s ease-in-out infinite;
            margin-left: 10px;
            vertical-align: middle;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        .disabled {
            opacity: 0.6;
            pointer-events: none;
        }

        .preview-gallery {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 10px;
        }

        .preview-item {
            width: 80px;
            height: 80px;
            border-radius: 8px;
            overflow: hidden;
            cursor: pointer;
            border: 2px solid transparent;
            transition: all 0.3s;
            position: relative;
            background: #e0e0e0;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .preview-item:hover {
            border-color: var(--primary);
            transform: scale(1.05);
        }

        .preview-item.active {
            border-color: var(--primary);
            box-shadow: 0 0 10px rgba(0, 160, 227, 0.3);
        }

        .preview-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .preview-label {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0, 0, 0, 0.6);
            color: white;
            font-size: 0.7rem;
            padding: 3px;
            text-align: center;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .preview-icon {
            font-size: 24px;
            color: #999;
        }

        .toggle-icon {
            transition: transform 0.3s;
        }

        .toggle-icon.rotate {
            transform: rotate(180deg);
        }

        /* Стили для полноэкранного просмотра */
        .preview-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.95);
            z-index: 2000;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background: none;
            border-radius: 0;
            padding: 0;
            max-width: 90%;
            max-height: 90%;
            text-align: center;
            position: relative;
        }

        .modal-content img {
            max-width: 100%;
            max-height: 80vh;
            border-radius: 0;
            border: 1px solid rgba(255, 255, 255, 0.1);
            box-shadow: 0 0 50px rgba(0, 0, 0, 0.5);
        }

        .modal-title {
            position: absolute;
            bottom: 20px;
            left: 0;
            right: 0;
            color: white;
            font-size: 1.5rem;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.7);
            padding: 10px 20px;
            background: rgba(0, 0, 0, 0.5);
        }

        .close-modal {
            position: absolute;
            top: 30px;
            right: 40px;
            color: white;
            font-size: 40px;
            cursor: pointer;
            transition: color 0.3s;
            z-index: 10;
        }

        .close-modal:hover {
            color: var(--primary);
        }

        .nav-arrows {
            position: absolute;
            top: 50%;
            width: 100%;
            display: flex;
            justify-content: space-between;
            padding: 0 20px;
            transform: translateY(-50%);
            z-index: 5;
        }

        .arrow {
            color: white;
            font-size: 40px;
            cursor: pointer;
            background: rgba(0, 0, 0, 0.3);
            border-radius: 50%;
            width: 60px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s;
        }

        .arrow:hover {
            background: rgba(0, 0, 0, 0.6);
            transform: scale(1.1);
        }

        .preview-item:hover::after {
            content: '\f00e';
            font-family: 'Font Awesome 5 Free';
            font-weight: 900;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }

        .save-button {
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            color: var(--white);
            padding: 16px 45px;
            border: none;
            border-radius: 30px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: var(--shadow);
            display: block;
            margin: 40px auto 0;
            letter-spacing: 0.5px;
        }

        .save-button:hover {
            transform: translateY(-3px);
            box-shadow: var(--shadow-hover);
            background: linear-gradient(135deg, var(--primary-dark), var(--primary));
        }

        .save-button:active {
            transform: translateY(-1px);
        }

        .status-message {
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
            text-align: center;
            font-weight: 500;
            display: none;
        }

        .status-success {
            background-color: rgba(76, 175, 80, 0.15);
            color: var(--success);
            border: 1px solid var(--success);
        }

        .status-error {
            background-color: rgba(244, 67, 54, 0.15);
            color: var(--error);
            border: 1px solid var(--error);
        }

        .price-button {
            background: linear-gradient(135deg, var(--secondary), #ff9800);
            color: var(--dark);
            padding: 16px 45px;
            border: none;
            border-radius: 30px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: var(--shadow);
            display: block;
            margin: 30px auto 0;
            letter-spacing: 0.5px;
        }

        .price-button:hover {
            transform: translateY(-3px);
            box-shadow: var(--shadow-hover);
        }

        .price-button:active {
            transform: translateY(-1px);
        }

        .price-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
            z-index: 3000;
            justify-content: center;
            align-items: center;
        }

        .price-form-container {
            background: var(--white);
            border-radius: var(--border-radius);
            padding: 40px;
            max-width: 500px;
            width: 90%;
            box-shadow: var(--shadow-hover);
        }

        .form-title {
            font-size: 1.8rem;
            margin-bottom: 30px;
            color: var(--dark);
            text-align: center;
            font-weight: 600;
        }

        .price-form-group {
            margin-bottom: 25px;
        }

        .price-form-group label {
            display: block;
            margin-bottom: 10px;
            font-weight: 500;
            color: var(--dark);
        }

        .price-form-group input,
        .price-form-group textarea {
            width: 100%;
            padding: 15px;
            border-radius: 8px;
            border: 2px solid #e0e0e0;
            font-size: 1rem;
            transition: all 0.3s;
            background: var(--white);
        }

        .price-form-group input:focus,
        .price-form-group textarea:focus {
            border-color: var(--primary);
            outline: none;
            box-shadow: 0 0 0 3px rgba(0, 160, 227, 0.2);
        }

        .price-form-group textarea {
            min-height: 120px;
            resize: vertical;
        }

        .submit-button {
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            color: var(--white);
            padding: 16px;
            border: none;
            border-radius: 8px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            width: 100%;
            margin-top: 10px;
            box-shadow: var(--shadow);
        }

        .submit-button:hover {
            transform: translateY(-3px);
            box-shadow: var(--shadow-hover);
            background: linear-gradient(135deg, var(--primary-dark), var(--primary));
        }

        .close-price-modal {
            position: absolute;
            top: 25px;
            right: 35px;
            color: white;
            font-size: 40px;
            cursor: pointer;
            transition: color 0.3s;
        }

        .close-price-modal:hover {
            color: var(--primary);
        }

        .confirmation-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
            z-index: 4000;
            justify-content: center;
            align-items: center;
        }

        .confirmation-content {
            background: var(--white);
            border-radius: var(--border-radius);
            padding: 50px;
            text-align: center;
            max-width: 500px;
            width: 90%;
            box-shadow: var(--shadow-hover);
        }

        .confirmation-icon {
            font-size: 60px;
            color: var(--success);
            margin-bottom: 25px;
        }

        .confirmation-text {
            font-size: 1.5rem;
            margin-bottom: 35px;
            color: var(--dark);
            font-weight: 600;
        }

        .confirmation-button {
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            color: var(--white);
            padding: 14px 40px;
            border: none;
            border-radius: 30px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: var(--shadow);
        }

        .confirmation-button:hover {
            transform: translateY(-3px);
            box-shadow: var(--shadow-hover);
        }

        @media (max-width: 768px) {
            .navbar {
                flex-direction: column;
                gap: 15px;
            }

            .nav-links {
                margin-top: 10px;
            }

            .nav-links li {
                margin: 0 15px;
            }

            .hero {
                padding: 40px 0 30px;
            }

            .hero h1 {
                font-size: 2.2rem;
            }

            .monument-base {
                width: 250px;
                height: 350px;
            }

            .type-options {
                flex-direction: column;
            }

            .type-option {
                width: 100%;
            }

            .preview-item {
                width: 70px;
                height: 70px;
            }

            .price-form-container {
                padding: 25px;
            }

            .form-title {
                font-size: 1.6rem;
            }

            .close-modal {
                top: 20px;
                right: 25px;
                font-size: 35px;
            }

            .arrow {
                font-size: 35px;
                width: 55px;
                height: 55px;
            }

            .modal-title {
                font-size: 1.3rem;
                bottom: 15px;
            }

            /* Уменьшаем отступы между группами на мобильных */
            .controls-grid {
                gap: 15px;
            }
        }

        @media (max-width: 576px) {
            .nav-links {
                flex-wrap: wrap;
                justify-content: center;
            }

            .nav-links li {
                margin: 5px 10px;
            }

            .hero h1 {
                font-size: 1.9rem;
            }

            .section-title {
                font-size: 1.5rem;
            }

            .monument-preview {
                height: 400px;
            }

            .preview-gallery {
                justify-content: center;
            }

            .save-button,
            .price-button {
                width: 100%;
                max-width: 300px;
            }

            /* Еще меньше отступы между группами на маленьких экранах */
            .controls-grid {
                gap: 10px;
            }
        }
    </style>
</head>

<body>


    <!-- Hero Section -->
    <section class="hero">
        <div class="container">
            <div style="
            background-color: rgba(0, 0, 0, 0.3);
            padding: 30px;
            border-radius: 12px;
            display: inline-block;
            color: white;
            font-size: 2rem;
            font-weight: 600;
            backdrop-filter: blur(4px);
        ">
                Slinkite pelės ratuku vaizdui keisti.
                2D vizualizacija
                Suplanuokite kapavietę pasirinkdami variantus apačioje. Baigę, spustelėkite „Pateikti užklausą“ –
                susisieksime su Jumis per 24 valandas.
            </div>
        </div>
    </section>

    <!-- Status Message -->
    <div class="container">
        <div id="statusMessage" class="status-message"></div>
    </div>

    <!-- Main Content -->
    <div class="container">
        <div class="main-content">
            <!-- Preview Section -->
            <div class="preview-section">
                <h2 class="section-title">
                    <i class="fas fa-eye"></i>
                    Jūsų paminklo peržiūra
                </h2>
                <div class="monument-preview">
                    <div class="monument-base">
                        <div id="plokstes-part" class="monument-part"></div>
                        <div id="takai-part" class="monument-part"></div>
                        <div id="sonai-part" class="monument-part"></div>
                        <div id="paminklai-part" class="monument-part"></div>
                    </div>
                </div>
            </div>

            <!-- Controls Section -->
            <div class="controls-section">
                <h2 class="section-title">
                    <i class="fas fa-sliders-h"></i>
                    Komponentų pasirinkimas
                </h2>

                <!-- Type Selection moved to right column -->
                <div class="type-selection">
                    <h3 class="type-title">
                        <i class="fas fa-archway"></i>
                        Pasirinkite paminklo tipą
                    </h3>
                    <div class="type-options">
                        <div class="type-option active" data-type="Didesne">
                            <div class="type-icon">
                                <i class="fas fa-landmark"></i>
                            </div>
                            <span class="type-name">Didėsnė</span>
                        </div>
                        <div class="type-option" data-type="Vienviete">
                            <div class="type-icon">
                                <i class="fas fa-monument"></i>
                            </div>
                            <span class="type-name">Vienvietė</span>
                        </div>
                    </div>
                </div>

                <div class="controls-grid">
                    <!-- Paminklai Group -->
                    <div class="control-group">
                        <div class="group-header" data-group="paminklai">
                            <h3 class="group-title">
                                <i class="fas fa-chess-queen"></i>
                                Paminklai
                            </h3>
                            <i class="fas fa-chevron-down toggle-icon"></i>
                        </div>
                        <div class="group-content" id="paminklai-content">
                            <div class="group-inner">
                                <select class="component-select" id="paminklai-select" data-specification="Paminklai">
                                    <option value="">Pasirinkite paminklą...</option>
                                </select>
                                <div class="preview-gallery" id="paminklai-gallery"></div>
                            </div>
                        </div>
                    </div>

                    <!-- Šonai Group -->
                    <div class="control-group">
                        <div class="group-header" data-group="sonai">
                            <h3 class="group-title">
                                <i class="fas fa-border-style"></i>
                                Šonai
                            </h3>
                            <i class="fas fa-chevron-down toggle-icon"></i>
                        </div>
                        <div class="group-content" id="sonai-content">
                            <div class="group-inner">
                                <select class="component-select" id="sonai-select" data-specification="Sonai">
                                    <option value="">Pasirinkite šonus...</option>
                                </select>
                                <div class="preview-gallery" id="sonai-gallery"></div>
                            </div>
                        </div>
                    </div>

                    <!-- Takai Group -->
                    <div class="control-group">
                        <div class="group-header" data-group="takai">
                            <h3 class="group-title">
                                <i class="fas fa-road"></i>
                                Takai
                            </h3>
                            <i class="fas fa-chevron-down toggle-icon"></i>
                        </div>
                        <div class="group-content" id="takai-content">
                            <div class="group-inner">
                                <select class="component-select" id="takai-select" data-specification="Takai">
                                    <option value="">Pasirinkite takus...</option>
                                </select>
                                <div class="preview-gallery" id="takai-gallery"></div>
                            </div>
                        </div>
                    </div>

                    <!-- Plokštės Group -->
                    <div class="control-group">
                        <div class="group-header" data-group="plokstes">
                            <h3 class="group-title">
                                <i class="fas fa-th-large"></i>
                                Plokštės
                            </h3>
                            <i class="fas fa-chevron-down toggle-icon"></i>
                        </div>
                        <div class="group-content" id="plokstes-content">
                            <div class="group-inner">
                                <select class="component-select" id="plokstes-select" data-specification="Plokstes">
                                    <option value="">Pasirinkite plokštę...</option>
                                </select>
                                <div class="preview-gallery" id="plokstes-gallery"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Price Button -->
                <button class="price-button" id="priceButton">
                    <i class="fas fa-tag"></i> Sužinoti kainą
                </button>

                <!-- Save Button -->
                <button class="save-button" id="saveButton">
                    <i class="fas fa-save"></i> Išsaugoti konfigūraciją
                </button>
            </div>
        </div>
    </div>

    <!-- Preview Modal -->
    <div class="preview-modal" id="previewModal">
        <span class="close-modal">&times;</span>
        <div class="nav-arrows">
            <div class="arrow prev-arrow">
                <i class="fas fa-chevron-left"></i>
            </div>
            <div class="arrow next-arrow">
                <i class="fas fa-chevron-right"></i>
            </div>
        </div>
        <div class="modal-content">
            <img id="modalImage" src="" alt="Komponento peržiūra">
            <h3 class="modal-title" id="modalTitle"></h3>
        </div>
    </div>

    <!-- Price Modal -->
    <div class="price-modal" id="priceModal">
        <span class="close-price-modal">&times;</span>
        <div class="price-form-container">
            <h2 class="form-title">
                <i class="fas fa-tag"></i> Sužinoti paminklo kainą
            </h2>
            <form id="priceForm">
                <div class="price-form-group">
                    <label for="name">Vardas *</label>
                    <input type="text" id="name" name="name" required placeholder="Jūsų vardas">
                </div>

                <div class="price-form-group">
                    <label for="email">El. paštas *</label>
                    <input type="email" id="email" name="email" required placeholder="Jūsų el. paštas">
                </div>

                <div class="price-form-group">
                    <label for="phone">Telefonas *</label>
                    <input type="tel" id="phone" name="phone" required placeholder="Jūsų telefono numeris">
                </div>

                <div class="price-form-group">
                    <label for="location">Kapinių vieta (adresas) *</label>
                    <input type="text" id="location" name="location" required placeholder="Kapinių adresas">
                </div>

                <div class="price-form-group">
                    <label for="message">Papildoma informacija</label>
                    <textarea id="message" name="message" placeholder="Papildomi klausimai ar pastabos..."></textarea>
                </div>

                <button type="submit" id="submit-button-to-send" class="submit-button">
                    <i class="fas fa-paper-plane"></i> Pateikti užklausą
                </button>
            </form>
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <!-- Confirmation Modal -->
    <div class="preview-modal" id="fullPreviewModal">
        <span class="close-modal" id="closeFullPreviewModal">&times;</span>
        <div class="modal-content">
            <img id="fullPreviewImage" src="" alt="Visas paminklas">
        </div>
    </div>
    <div class="confirmation-modal" id="confirmationModal">
        <div class="confirmation-content">
            <div class="confirmation-icon">
                <i class="fas fa-check-circle"></i>
            </div>
            <h2 class="confirmation-text" id="confirmationMessage">Konfigūracija sėkmingai išsiųsta!</h2>
            <button class="confirmation-button" id="closeConfirmation">Gerai</button>
        </div>
    </div>

    <script>
        // Инициализация EmailJS
        (function () {
            emailjs.init('F4Pl7rQvg4bT01FFI');
        })();

        document.addEventListener('DOMContentLoaded', function () {
            // Текущие выборы пользователя
            const selections = {
                type: 'Didesne',
                paminklai: null,
                sonai: null,
                takai: null,
                plokstes: null
            };

            // DOM Elements
            const typeOptions = document.querySelectorAll('.type-option');
            const componentSelects = document.querySelectorAll('.component-select');
            const statusMessage = document.getElementById('statusMessage');
            const monumentParts = document.querySelectorAll('.monument-part');
            const priceButton = document.getElementById('priceButton');
            const priceModal = document.getElementById('priceModal');
            const priceForm = document.getElementById('priceForm');
            const closePriceModal = document.querySelector('.close-price-modal');
            const saveButton = document.getElementById('saveButton');
            const confirmationModal = document.getElementById('confirmationModal');
            const closeConfirmation = document.getElementById('closeConfirmation');
            const confirmationMessage = document.getElementById('confirmationMessage');
            const previewModal = document.getElementById('previewModal');

            // Переменные для полноэкранного просмотра
            let currentGallery = null;
            let currentItems = [];
            let currentIndex = 0;

            // Закрытие модальных окон
            closePriceModal.addEventListener('click', function () {
                priceModal.style.display = 'none';
            });

            closeConfirmation.addEventListener('click', function () {
                confirmationModal.style.display = 'none';
            });

            // Закрытие модальных окон при клике вне их
            window.addEventListener('click', function (event) {
                if (event.target === priceModal) {
                    priceModal.style.display = 'none';
                }
                if (event.target === confirmationModal) {
                    confirmationModal.style.display = 'none';
                }
            });

            // Функция для показа сообщения
            function showMessage(message, type) {
                statusMessage.textContent = message;
                statusMessage.className = `status-message status-${type}`;
                statusMessage.style.display = 'block';

                // Автоматическое скрытие сообщения через 5 секунд
                setTimeout(() => {
                    statusMessage.style.display = 'none';
                }, 5000);
            }

            // Функция для полного сброса превью
            function resetAllPreviews() {
                monumentParts.forEach(part => {
                    part.style.backgroundImage = 'none';
                });

                componentSelects.forEach(select => {
                    select.value = '';
                });

                const galleries = document.querySelectorAll('.preview-gallery');
                galleries.forEach(gallery => {
                    const items = gallery.querySelectorAll('.preview-item');
                    items.forEach(item => {
                        item.classList.remove('active');
                    });
                });

                selections.paminklai = null;
                selections.sonai = null;
                selections.takai = null;
                selections.plokstes = null;
            }

            // Сохранение состояния в localStorage
            function saveStateToLocalStorage() {
                localStorage.setItem('monumentBuilderSelections', JSON.stringify(selections));
            }

            // Восстановление состояния из localStorage
            function loadStateFromLocalStorage() {
                const saved = localStorage.getItem('monumentBuilderSelections');
                if (saved) {
                    try {
                        const parsed = JSON.parse(saved);
                        Object.assign(selections, parsed);

                        document.querySelectorAll('.type-option').forEach(option => {
                            option.classList.remove('active');
                            if (option.dataset.type === selections.type) {
                                option.classList.add('active');
                            }
                        });
                    } catch (e) {
                        console.error('Error loading state:', e);
                    }
                }
            }

            // Загрузка компонентов с сервера
            async function loadComponents(specification) {
                const gallery = document.getElementById(`${specification.toLowerCase()}-gallery`);
                const select = document.getElementById(`${specification.toLowerCase()}-select`);
                const content = document.getElementById(`${specification.toLowerCase()}-content`);

                gallery.innerHTML = '<div class="loader" style="margin: 20px auto;"></div>';
                select.innerHTML = '<option value="">Kraunama...</option>';
                select.disabled = true;

                try {
                    // ЗАМЕНИТЕ НА РЕАЛЬНЫЙ API-ЭНДПОИНТ
                    const response = await fetch(`/v1/components/?type=${selections.type}&specification=${specification}`);

                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }

                    const items = await response.json();

                    populateSelect(specification, items);
                    populateGallery(specification, items);

                } catch (error) {
                    console.error('Error loading components:', error);
                    gallery.innerHTML = '<div class="preview-icon"><i class="fas fa-exclamation-triangle"></i></div>';
                    select.innerHTML = '<option value="">Įvyko klaida</option>';
                    showMessage(`Klaida įkeliant ${specification.toLowerCase()} komponentus: ${error.message}`, 'error');
                } finally {
                    select.disabled = false;
                }
            }

            // Заполнение выпадающего списка
            function populateSelect(specification, items) {
                const select = document.getElementById(`${specification.toLowerCase()}-select`);
                select.innerHTML = '<option value="">Pasirinkite...</option>';

                items.forEach(item => {
                    const option = document.createElement('option');
                    option.value = item.id;
                    option.textContent = item.name;
                    select.appendChild(option);
                });

                if (selections[specification.toLowerCase()]) {
                    select.value = selections[specification.toLowerCase()];
                }
            }

            // Заполнение галереи миниатюр
            function populateGallery(specification, items) {
                const gallery = document.getElementById(`${specification.toLowerCase()}-gallery`);
                gallery.innerHTML = '';

                if (items.length === 0) {
                    gallery.innerHTML = '<p>Nėra prieinamų komponentų</p>';
                    return;
                }

                items.forEach(item => {
                    const previewItem = document.createElement('div');
                    previewItem.className = 'preview-item';
                    previewItem.dataset.id = item.id;
                    previewItem.dataset.image = item.image_url;
                    previewItem.dataset.name = item.name;

                    const img = document.createElement('img');
                    img.src = '/' + item.image_url;
                    img.alt = item.name;
                    img.loading = "lazy";

                    const label = document.createElement('div');
                    label.className = 'preview-label';
                    label.textContent = item.name;

                    previewItem.appendChild(img);
                    previewItem.appendChild(label);
                    gallery.appendChild(previewItem);

                    // Обработчик для выбора компонента
                    previewItem.addEventListener('click', function () {
                        const select = document.getElementById(`${specification.toLowerCase()}-select`);
                        select.value = item.id;

                        selections[specification.toLowerCase()] = item.id;
                        updatePreview(specification);

                        document.querySelectorAll(`#${specification.toLowerCase()}-gallery .preview-item`).forEach(el => {
                            el.classList.remove('active');
                        });
                        this.classList.add('active');

                        saveStateToLocalStorage();
                    });

                    // Обработчик для полноэкранного просмотра (двойной клик)
                    previewItem.addEventListener('dblclick', function () {
                        openFullscreenView(`${specification.toLowerCase()}`, item.id);
                    });
                });

                if (selections[specification.toLowerCase()]) {
                    const activeThumb = gallery.querySelector(`.preview-item[data-id="${selections[specification.toLowerCase()]}"]`);
                    if (activeThumb) {
                        activeThumb.classList.add('active');
                    }
                }
            }

            // Обновление превью
            async function updatePreview(specification) {
                const value = selections[specification.toLowerCase()];
                const part = document.getElementById(`${specification.toLowerCase()}-part`);

                if (!value) {
                    part.style.backgroundImage = 'none';
                    return;
                }

                try {
                    const previewItem = document.querySelector(`#${specification.toLowerCase()}-gallery .preview-item[data-id="${value}"]`);

                    if (previewItem) {
                        const imageUrl = previewItem.dataset.image;
                        part.style.backgroundImage = `url('/${imageUrl}')`;
                        part.style.backgroundSize = 'contain';
                        part.style.backgroundPosition = 'center';
                        part.style.backgroundRepeat = 'no-repeat';
                    } else {
                        // ЗАМЕНИТЕ НА РЕАЛЬНЫЙ API-ЭНДПОИНТ
                        const response = await fetch(`/v1/component-image/?id=${value}`);

                        if (!response.ok) {
                            throw new Error(`HTTP error! status: ${response.status}`);
                        }

                        const data = await response.json();
                        part.style.backgroundImage = `url('${data.image_url}')`;
                        part.style.backgroundSize = 'contain';
                        part.style.backgroundPosition = 'center';
                        part.style.backgroundRepeat = 'no-repeat';
                    }
                } catch (error) {
                    console.error('Error loading image:', error);
                    part.style.backgroundImage = 'none';
                    showMessage(`Klaida įkeliant vaizdą: ${error.message}`, 'error');
                }
            }

            // Обновление компонентов при смене типа
            function updateComponentSelects() {
                resetAllPreviews();

                const specifications = ['Paminklai', 'Sonai', 'Takai', 'Plokstes'];
                specifications.forEach(spec => {
                    loadComponents(spec);
                });
            }

            // Открытие модального окна запроса цены
            priceButton.addEventListener('click', function () {
                priceModal.style.display = 'flex';
            });

            // Функция для получения названия компонента
            function getComponentName(type) {
                const select = document.getElementById(`${type}-select`);
                return select.options[select.selectedIndex]?.text || 'Nepasirinkta';
            }

            // Функция для генерации изображения превью
            async function generatePreviewImage() {
                try {
                    const previewElement = document.querySelector('.monument-preview');
                    const canvas = await html2canvas(previewElement, {
                        useCORS: true,
                        scale: 0.5,
                        logging: false,
                        backgroundColor: null
                    });

                    // Конвертируем в Data URL с качеством 80%
                    return canvas.toDataURL('image/jpeg', 0.8);
                } catch (error) {
                    console.error('Error generating preview:', error);
                    return ''; // Возвращаем пустую строку при ошибке
                }
            }

            // Функция для сжатия изображения
            function compressImage(dataUrl, quality = 0.6) {
                return new Promise((resolve) => {
                    const img = new Image();
                    img.src = dataUrl;

                    img.onload = () => {
                        const canvas = document.createElement('canvas');
                        const ctx = canvas.getContext('2d');
                        canvas.width = img.width;
                        canvas.height = img.height;
                        ctx.drawImage(img, 0, 0);
                        resolve(canvas.toDataURL('image/jpeg', quality));
                    };

                    img.onerror = () => resolve(dataUrl);
                });
            }

            // Обработчик формы запроса цены
            document.getElementById('priceForm').addEventListener('submit', async function (event) {
                event.preventDefault();

                const submitButton = document.getElementById('submit-button-to-send');
                const originalContent = submitButton.innerHTML;
                submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Siunčiama...';
                submitButton.disabled = true;

                try {
                    // Собираем данные формы
                    const formData = {
                        from_name: this.name.value,
                        email: this.email.value,
                        phone: this.phone.value,
                        location: this.location.value,
                        message: this.message.value,
                        configuration: getConfigurationHTML()
                    };

                    // Генерируем превью
                    formData.preview_image = await generatePreviewImage();

                    // Если изображение слишком большое, сжимаем его
                    if (formData.preview_image.length > 500000) {
                        formData.preview_image = await compressImage(formData.preview_image, 0.5);
                    }

                    // Отправка через EmailJS
                    const serviceID = 'service_jbu2wwo';
                    const templateID = 'template_vblsqn6';

                    await emailjs.send(serviceID, templateID, formData);

                    // Успешная отправка
                    showMessage('Užklausa sėkmingai išsiųsta! Atsakysime kuo skubiau.', 'success');
                    this.reset();
                    priceModal.style.display = 'none';
                } catch (err) {
                    console.error('Klaida:', err);
                    showMessage(`Siuntimo klaida: ${err.message || err}`, 'error');
                } finally {
                    submitButton.innerHTML = originalContent;
                    submitButton.disabled = false;
                }
            });

            // Упрощенная функция для получения HTML-описания конфигурации
            function getConfigurationHTML() {
                return `
                <h4>Paminklo konfigūracija:</h4>
                <ul>
                    <li><strong>Tipas:</strong> ${selections.type}</li>
                    <li><strong>Paminklai:</strong> ${getComponentName('paminklai')}</li>
                    <li><strong>Šonai:</strong> ${getComponentName('sonai')}</li>
                    <li><strong>Takai:</strong> ${getComponentName('takai')}</li>
                    <li><strong>Plokštės:</strong> ${getComponentName('plokstes')}</li>
                </ul>
            `;
            }

            // Сохранение конфигурации в историю
            function saveConfigurationToHistory() {
                const history = JSON.parse(localStorage.getItem('monumentConfigHistory') || '[]');

                const config = {
                    id: Date.now(),
                    date: new Date().toISOString(),
                    type: selections.type,
                    paminklai: {
                        id: selections.paminklai,
                        name: getComponentName('paminklai')
                    },
                    sonai: {
                        id: selections.sonai,
                        name: getComponentName('sonai')
                    },
                    takai: {
                        id: selections.takai,
                        name: getComponentName('takai')
                    },
                    plokstes: {
                        id: selections.plokstes,
                        name: getComponentName('plokstes')
                    }
                };

                history.unshift(config);

                if (history.length > 5) {
                    history.pop();
                }

                localStorage.setItem('monumentConfigHistory', JSON.stringify(history));
            }

            // Обработчик кнопки сохранения
            saveButton.addEventListener('click', function () {
                const isComplete = Object.values(selections).every(
                    (value, index) => index === 0 || value !== null
                );

                if (!isComplete) {
                    showMessage('Prašome pasirinkti visus komponentus prieš išsaugant.', 'error');
                    return;
                }

                saveConfigurationToHistory();
                confirmationMessage.textContent = 'Konfigūracija sėkmingai išsaugota!';
                confirmationModal.style.display = 'flex';
            });

            // Функция для открытия полноэкранного просмотра
            function openFullscreenView(galleryType, itemId) {
                const gallery = document.getElementById(`${galleryType}-gallery`);
                const items = Array.from(gallery.querySelectorAll('.preview-item'));

                currentGallery = galleryType;
                currentItems = items;
                currentIndex = items.findIndex(item => item.dataset.id === itemId);

                if (currentIndex === -1) currentIndex = 0;

                updateFullscreenView();
                previewModal.style.display = 'flex';
                document.body.style.overflow = 'hidden'; // Блокируем прокрутку страницы
            }

            // Обновление полноэкранного вида
            function updateFullscreenView() {
                if (currentItems.length === 0) return;

                const currentItem = currentItems[currentIndex];
                const modalImage = document.getElementById('modalImage');
                const modalTitle = document.getElementById('modalTitle');

                modalImage.src = '/' + currentItem.dataset.image;
                modalTitle.textContent = currentItem.dataset.name;

                // Показываем/скрываем стрелки навигации
                document.querySelector('.prev-arrow').style.display = currentIndex > 0 ? 'flex' : 'none';
                document.querySelector('.next-arrow').style.display = currentIndex < currentItems.length - 1 ? 'flex' : 'none';
            }

            // Переключение изображений
            function navigateFullscreen(direction) {
                if (direction === 'prev' && currentIndex > 0) {
                    currentIndex--;
                } else if (direction === 'next' && currentIndex < currentItems.length - 1) {
                    currentIndex++;
                }

                updateFullscreenView();
            }

            // Закрытие полноэкранного просмотра
            function closeFullscreenView() {
                previewModal.style.display = 'none';
                document.body.style.overflow = 'auto'; // Восстанавливаем прокрутку
            }

            // Обработчики событий для полноэкранного просмотра
            document.querySelector('.prev-arrow').addEventListener('click', () => navigateFullscreen('prev'));
            document.querySelector('.next-arrow').addEventListener('click', () => navigateFullscreen('next'));
            document.querySelector('.close-modal').addEventListener('click', closeFullscreenView);

            // Закрытие при клике вне изображения
            previewModal.addEventListener('click', function (event) {
                if (event.target === previewModal) {
                    closeFullscreenView();
                }
            });

            // Навигация с помощью клавиатуры
            document.addEventListener('keydown', function (event) {
                if (previewModal.style.display === 'flex') {
                    if (event.key === 'ArrowLeft') {
                        navigateFullscreen('prev');
                    } else if (event.key === 'ArrowRight') {
                        navigateFullscreen('next');
                    } else if (event.key === 'Escape') {
                        closeFullscreenView();
                    }
                }
            });

            // Обработчики для аккордеона
            document.querySelectorAll('.group-header').forEach(header => {
                header.addEventListener('click', function () {
                    const group = this.dataset.group;
                    const content = document.getElementById(`${group}-content`);
                    const icon = this.querySelector('.toggle-icon');

                    content.classList.toggle('active');
                    icon.classList.toggle('rotate');
                });
            });

            // Инициализация приложения
            function initApp() {
                loadStateFromLocalStorage();

                typeOptions.forEach(option => {
                    option.addEventListener('click', function () {
                        const type = this.dataset.type;

                        if (selections.type === type) return;

                        selections.type = type;

                        typeOptions.forEach(opt => opt.classList.remove('active'));
                        this.classList.add('active');

                        updateComponentSelects();
                        saveStateToLocalStorage();
                    });
                });

                componentSelects.forEach(select => {
                    select.addEventListener('change', function () {
                        const specification = this.dataset.specification;
                        const value = this.value;

                        selections[specification.toLowerCase()] = value;
                        updatePreview(specification);

                        document.querySelectorAll(`#${specification.toLowerCase()}-gallery .preview-item`).forEach(el => {
                            el.classList.remove('active');
                        });

                        const activeThumb = document.querySelector(`#${specification.toLowerCase()}-gallery .preview-item[data-id="${value}"]`);
                        if (activeThumb) {
                            activeThumb.classList.add('active');
                        }

                        saveStateToLocalStorage();
                    });
                });

                updateComponentSelects();
            }
            const fullPreviewModal = document.getElementById('fullPreviewModal');
            const fullPreviewImage = document.getElementById('fullPreviewImage');
            const closeFullPreviewModal = document.getElementById('closeFullPreviewModal');
            const monumentPreview = document.querySelector('.monument-preview');

            monumentPreview.style.cursor = 'zoom-in';
            monumentPreview.addEventListener('click', async () => {
                try {
                    const canvas = await html2canvas(monumentPreview, {
                        useCORS: true,
                        scale: 1.5,
                        backgroundColor: null
                    });
                    fullPreviewImage.src = canvas.toDataURL('image/png');
                    fullPreviewModal.style.display = 'flex';
                    document.body.style.overflow = 'hidden';
                } catch (error) {
                    console.error('Klaida generuojant peržiūros paveikslėlį:', error);
                }
            });

            closeFullPreviewModal.addEventListener('click', () => {
                fullPreviewModal.style.display = 'none';
                document.body.style.overflow = 'auto';
            });

            fullPreviewModal.addEventListener('click', (e) => {
                if (e.target === fullPreviewModal) {
                    fullPreviewModal.style.display = 'none';
                    document.body.style.overflow = 'auto';
                }
            });
            // Запускаем приложение
            initApp();
        });
    </script>
</body>

</html>