<!DOCTYPE html>
<html lang="uk">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Портал Італія | Assistenza Ucraini in Italia - assistenzaucraini.it</title>
    <style>
        :root {
            --ua-blue: #0057B7;
            --ua-yellow: #FFD700;
            --dark: #1e293b;
            --light: #f8fafc;
            --border: #cbd5e1;
            --success: #16a34a;
            --whatsapp: #25D366;
            --viber: #7360f2;
            --telegram: #0088cc;
        }
        * { box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', Roboto, Arial, sans-serif;
            margin: 0; padding: 0;
            background-color: var(--light);
            color: var(--dark);
            line-height: 1.5;
        }
        header {
            background: linear-gradient(135deg, var(--ua-blue) 0%, #003d82 100%);
            color: white;
            padding: 2rem 1rem;
            text-align: center;
            border-bottom: 5px solid var(--ua-yellow);
        }
        header h1 { margin: 0 0 0.5rem 0; font-size: 2rem; }
        header p { margin: 0 auto; max-width: 750px; font-size: 1.05rem; opacity: 0.95; }
        .stats-bar {
            background: #fff;
            border-bottom: 1px solid var(--border);
            padding: 0.6rem 1rem;
            text-align: center;
            font-size: 0.9rem;
            color: #475569;
            display: flex;
            justify-content: center;
            gap: 1.5rem;
            flex-wrap: wrap;
        }
        .stats-bar strong { color: var(--ua-blue); }
        .container { max-width: 1140px; margin: 1.5rem auto; padding: 0 1rem; }
        .section-title {
            text-align: center;
            color: var(--ua-blue);
            margin: 2.5rem 0 1rem 0;
            font-size: 1.6rem;
        }
        .section-sub {
            text-align: center;
            max-width: 750px;
            margin: 0 auto 1.8rem auto;
            color: #475569;
        }
        /* Tabs Generatori */
        .tabs {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(165px, 1fr));
            gap: 0.6rem;
            margin-bottom: 1.5rem;
        }
        .tab-btn {
            background: white;
            border: 2px solid var(--ua-blue);
            color: var(--ua-blue);
            padding: 0.75rem 0.5rem;
            border-radius: 8px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.2s;
            font-size: 0.9rem;
            text-align: center;
        }
        .tab-btn.active, .tab-btn:hover {
            background: var(--ua-blue);
            color: white;
        }
        /* Pannello Modulo e Anteprima */
        .workspace {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.5rem;
            background: white;
            padding: 1.5rem;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.06);
            border: 1px solid var(--border);
        }
        @media (max-width: 860px) {
            .workspace { grid-template-columns: 1fr; }
        }
        .form-box h3 { margin-top: 0; color: var(--ua-blue); border-bottom: 2px solid var(--ua-yellow); padding-bottom: 0.5rem; }
        .field { margin-bottom: 0.9rem; }
        .field label { display: block; font-weight: 600; font-size: 0.88rem; margin-bottom: 0.25rem; color: #334155; }
        .field input, .field select, .field textarea {
            width: 100%; padding: 0.6rem 0.75rem;
            border: 1px solid var(--border);
            border-radius: 6px; font-size: 0.95rem;
        }
        .btn-row { display: flex; flex-wrap: wrap; gap: 0.6rem; margin-top: 1.2rem; }
        .btn {
            display: inline-flex; align-items: center; justify-content: center;
            padding: 0.75rem 1.1rem; border-radius: 6px;
            font-weight: 700; font-size: 0.92rem;
            text-decoration: none; border: none; cursor: pointer;
            transition: opacity 0.2s, transform 0.1s;
            color: white;
        }
        .btn:hover { opacity: 0.92; }
        .btn:active { transform: scale(0.98); }
        .btn-primary { background: var(--ua-blue); }
        .btn-success { background: var(--success); }
        .btn-dark { background: #334155; }
        .btn-wa { background: var(--whatsapp); }
        .btn-vb { background: var(--viber); }
        .btn-tg { background: var(--telegram); }
        /* Documento Ufficiale in Anteprima */
        .preview-wrapper {
            background: #f1f5f9;
            padding: 1rem;
            border-radius: 8px;
            border: 1px dashed #94a3b8;
        }
        .official-doc {
            background: white;
            padding: 1.8rem;
            border: 1px solid #cbd5e1;
            min-height: 420px;
            font-family: 'Times New Roman', Times, serif;
            color: #000;
            line-height: 1.45;
        }
        .official-doc h2 { text-align: center; font-size: 1.15rem; margin: 0 0 0.3rem 0; text-transform: uppercase; }
        .official-doc h4 { text-align: center; font-size: 0.95rem; margin: 0 0 1.2rem 0; font-weight: normal; border-bottom: 1px solid #000; padding-bottom: 0.6rem; }
        .doc-line { margin-bottom: 0.55rem; font-size: 0.98rem; }
        .doc-sign { margin-top: 2.2rem; display: flex; justify-content: space-between; font-size: 0.95rem; }
        /* Box Kit 209 */
        .kit-box { border: 1px solid #000; padding: 0.5rem; margin-bottom: 0.5rem; background: #fffbeb; font-family: monospace; font-size: 0.9rem; }
        /* Sezione Assicurazione Auto */
        .insurance-banner {
            background: linear-gradient(135deg, #0f172a 0%, #1e3a8a 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-top: 2.5rem;
            border-left: 6px solid var(--ua-yellow);
        }
        .insurance-banner h3 { margin-top: 0; color: var(--ua-yellow); font-size: 1.4rem; }
        /* Tariffe 3 colonne */
        .grid-3 {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(290px, 1fr));
            gap: 1.25rem;
            margin-top: 1.2rem;
        }
        .card {
            background: white;
            border: 1px solid var(--border);
            border-radius: 12px;
            padding: 1.6rem;
            box-shadow: 0 3px 8px rgba(0,0,0,0.04);
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }
        .card.featured {
            border: 2px solid var(--ua-blue);
            position: relative;
        }
        .badge {
            background: var(--ua-yellow);
            color: #000;
            font-weight: 800;
            font-size: 0.78rem;
            padding: 0.25rem 0.6rem;
            border-radius: 4px;
            display: inline-block;
            margin-bottom: 0.5rem;
            text-transform: uppercase;
        }
        .price { font-size: 1.9rem; font-weight: 800; color: var(--ua-blue); margin: 0.5rem 0; }
        .iban-box {
            background: #f1f5f9;
            border: 1px solid #94a3b8;
            padding: 0.65rem;
            border-radius: 6px;
            font-family: monospace;
            font-size: 0.95rem;
            font-weight: bold;
            margin: 0.6rem 0;
            word-break: break-all;
        }
        .alert-modal {
            display: none;
            position: fixed; inset: 0;
            background: rgba(0,0,0,0.6);
            align-items: center; justify-content: center;
            z-index: 999; padding: 1rem;
        }
        .alert-content {
            background: white; max-width: 480px; width: 100%;
            padding: 1.8rem; border-radius: 12px; text-align: center;
            border-top: 6px solid var(--success);
        }
        footer {
            background: #0f172a; color: #cbd5e1;
            text-align: center; padding: 2rem 1rem;
            margin-top: 3rem; font-size: 0.9rem;
        }
        /* Stampa solo il modulo ufficiale */
        @media print {
            body * { visibility: hidden; }
            #printableArea, #printableArea * { visibility: visible; }
            #printableArea {
                position: absolute; left: 0; top: 0; width: 100%;
                border: none; padding: 0; margin: 0;
            }
        }
    </style>
</head>
<body>

<header>
    <h1>🇺🇦 Портал Італія — Assistenza Ucraini in Italia 🇮🇹</h1>
    <p>Генератор офіційних документів, допомога з бюрократією та автострахуванням в Італії<br>
    Generatore di moduli ufficiali, supporto burocratico e assistenza per la comunità ucraina</p>
</header>

<!-- Barra Contatori Automatici -->
<div class="stats-bar">
    <span>📊 <strong>Модулів заповнено / Moduli compilati:</strong> <span id="cnt-compile">142</span></span>
    <span>📥 <strong>Завантажено / Scaricati:</strong> <span id="cnt-download">89</span></span>
    <span>🖨️ <strong>Роздруковано / Stampati:</strong> <span id="cnt-print">64</span></span>
</div>

<div class="container">

    <!-- 1. SEZIONE GENERATORI -->
    <h2 class="section-title">1. Оберіть документ / Scegli il Documento da Generare</h2>
    <p class="section-sub">Заповніть поля українською або італійською мовою (латиницею як у закордонному паспорті). Документ формується автоматично італійською мовою для офіційних органів.<br>
    Compila i campi qui sotto: il documento ufficiale in italiano si genera in tempo reale pronto da stampare o scaricare.</p>

    <div class="tabs">
        <button class="tab-btn active" onclick="switchDoc('cf', this)">1. Codice Fiscale<br><small>Податковий код</small></button>
        <button class="tab-btn" onclick="switchDoc('ts', this)">2. Tessera Sanitaria<br><small>Медична картка ASL</small></button>
        <button class="tab-btn" onclick="switchDoc('scuola', this)">3. Scuola e Mensa<br><small>Школа та їдальня</small></button>
        <button class="tab-btn" onclick="switchDoc('osp', this)">4. Ospitalità (Art. 7)<br><small>Декларація житла</small></button>
        <button class="tab-btn" onclick="switchDoc('patente', this)">5. Patente TT2112<br><small>Конвертація прав</small></button>
        <button class="tab-btn" onclick="switchDoc('kit209', this)">6. Kit Postale 209<br><small>Дозвіл на проживання</small></button>
    </div>

    <div class="workspace">
        <!-- Colonna Input -->
        <div class="form-box">
            <h3 id="formTitle">Richiesta Codice Fiscale (Mod. AA4/8) / Запит на Податковий код</h3>
            
            <div class="field">
                <label>Прізвище (як у паспорті) / Cognome:</label>
                <input type="text" id="in_cognome" placeholder="Es. SHEVCHENKO" oninput="renderDoc()">
            </div>
            <div class="field">
                <label>Ім'я (як у паспорті) / Nome:</label>
                <input type="text" id="in_nome" placeholder="Es. OLENA" oninput="renderDoc()">
            </div>
            <div class="field">
                <label>Дата народження / Data di nascita:</label>
                <input type="date" id="in_nascita" oninput="renderDoc()">
            </div>
            <div class="field">
                <label>Місце та країна народження / Luogo e Stato di nascita:</label>
                <input type="text" id="in_luogo" placeholder="Es. KYIV (UCRAINA)" value="UCRAINA (EE)" oninput="renderDoc()">
            </div>
            <div class="field">
                <label>Податковий код (якщо вже є) / Codice Fiscale (se già presente):</label>
                <input type="text" id="in_cf" placeholder="Es. SHVLNE85A41Z138X" oninput="renderDoc()">
            </div>
            <div class="field">
                <label>Місто проживання в Італії (Провінція) / Comune e Provincia in Italia:</label>
                <input type="text" id="in_comune" placeholder="Es. SARONNO (VA)" oninput="renderDoc()">
            </div>
            <div class="field">
                <label>Адреса в Італії (Вулиця, номер) / Indirizzo di domicilio in Italia:</label>
                <input type="text" id="in_indirizzo" placeholder="Es. Via Roma 10" oninput="renderDoc()">
            </div>
            <div class="field">
                <label>Номер закордонного паспорта / Numero Passaporto o Documento:</label>
                <input type="text" id="in_doc" placeholder="Es. FE123456" oninput="renderDoc()">
            </div>
            <div class="field">
                <label id="lbl_extra">Додаткові дані (Телефон / Email) / Dati aggiuntivi:</label>
                <input type="text" id="in_extra" placeholder="Es. +39 333 1234567" oninput="renderDoc()">
            </div>

            <div class="btn-row">
                <button class="btn btn-primary" onclick="actionPrint()">🖨️ Роздрукувати / Stampa PDF</button>
                <button class="btn btn-success" onclick="actionDownload()">📥 Завантажити / Scarica File</button>
                <button class="btn btn-wa" onclick="actionSendCheck('WhatsApp')">💬 Перевірити у WhatsApp / Invia per Controllo</button>
            </div>
        </div>

        <!-- Colonna Anteprima Ufficiale -->
        <div class="preview-wrapper">
            <div style="font-size:0.82rem; color:#475569; margin-bottom:0.5rem; text-align:center;">
                📄 <strong>ПОПЕРЕДНІЙ ПЕРЕГЛЯД / ANTEPRIMA DOCUMENTO UFFICIALE</strong>
            </div>
            <div class="official-doc" id="printableArea">
                <!-- Generato via JS -->
            </div>
        </div>
    </div>

    <!-- 2. SEZIONE ASSICURAZIONE AUTO -->
    <div class="insurance-banner">
        <h3>🚗 Автострахування та Українські Номери / Assicurazione Auto e Targhe Ucraine</h3>
        <p>Маєте автомобіль на українських номерах або вже отримали італійські номерні знаки і шукаєте вигідну страховку RC Auto? Допомагаємо оформити поліс без переплат, перевірити документи для реєстрації REVE або розмитнення.<br>
        Hai un'auto con targa ucraina da regolarizzare (REVE / immatricolazione) o cerchi una polizza RC Auto conveniente in Italia? Ti assistiamo passo dopo passo con preventivo rapido.</p>
        <div class="btn-row">
            <a href="https://wa.me/393931951395?text=Доброго%20дня!%20Мені%20потрібна%20допомога%20з%20автострахуванням%20/%20Salve,%20vorrei%20assistenza%20per%20l'assicurazione%20auto." target="_blank" class="btn btn-wa" onclick="bumpStat('compile')">📲 Запит у WhatsApp / Preventivo WhatsApp</a>
            <a href="viber://chat?number=%2B393931951395" class="btn btn-vb" onclick="bumpStat('compile')">💜 Написати у Viber / Scrivici su Viber</a>
            <a href="https://t.me/+393931951395" target="_blank" class="btn btn-tg" onclick="bumpStat('compile')">✈️ Написати у Telegram / Scrivici su Telegram</a>
        </div>
    </div>

    <!-- 3. TABELLA PREZZI E PACCHETTI -->
    <h2 class="section-title">2. Тарифи та Пакети Допомоги / Tariffe e Pacchetti di Assistenza</h2>
    <p class="section-sub">Оберіть рівень підтримки: від безкоштовного самостійного заповнення до повного супроводу «Без турбот».<br>
    Scegli se fare tutto in autonomia gratuitamente o affidarti al nostro controllo professionale.</p>

    <div class="grid-3">
        <div class="card">
            <div>
                <span class="badge" style="background:#e2e8f0;">Самостійно / Fai da te</span>
                <h3>Базовий / Pacchetto Base</h3>
                <div class="price">0,00 €</div>
                <p>✅ Заповнення модулів онлайн на сайті<br>Compilazione moduli online sul portale</p>
                <p>✅ Миттєвий друк та завантаження PDF<br>Stampa immediata e scaricamento gratuito</p>
            </div>
            <button class="btn btn-dark" onclick="window.scrollTo({top:200, behavior:'smooth'})">Почати безкоштовно / Inizia Gratis</button>
        </div>

        <div class="card">
            <div>
                <span class="badge">Швидка перевірка / Rapido</span>
                <h3>Експрес-перевірка / Controllo Express</h3>
                <div class="price">9,90 €</div>
                <p>✅ Перевірка вашого документа фахівцем перед подачею у Квестуру, Пошту чи ASL<br>Verifica professionale del tuo modulo prima della consegna</p>
                <p>✅ Виправлення помилок та відправка готового файлу у WhatsApp/Viber<br>Correzione errori e invio file pronto su WhatsApp/Viber</p>
            </div>
            <a href="#pagamenti" class="btn btn-primary">Обрати 9,90 € / Scegli Controllo Express</a>
        </div>

        <div class="card featured">
            <div>
                <span class="badge">Хіт вибору / Più scelto</span>
                <h3>Повний пакет «Без турбот» / Pacchetto «Zero Pensieri»</h3>
                <div class="price">19,90 €</div>
                <p>✅ Повне заповнення всіх документів замість вас (ви лише надсилаєте фото паспорта)<br>Compilazione completa da parte nostra (invii solo foto documento)</p>
                <p>✅ Пріоритетна підтримка у WhatsApp, Viber та Telegram до вирішення питання<br>Supporto prioritario diretto passo-passo fino alla consegna</p>
            </div>
            <a href="https://buy.stripe.com/6oUdR2gpC3UJ3OO5fX28801" target="_blank" class="btn btn-success">Оплатити 19,90 € / Attiva Zero Pensieri</a>
        </div>
    </div>

    <!-- 4. GRIGLIA PAGAMENTI A 3 COLONNE -->
    <h2 class="section-title" id="pagamenti">3. Зручна Оплата / Metodi di Pagamento Sicuri</h2>
    <p class="section-sub">Оплачуйте зручним способом: через українські додатки Приват24 / Монобанк за реквізитами IBAN Wise, через PayPal або карткою через Stripe.<br>
    Paga comodamente da app bancarie ucraine (Privat24 / Monobank), PayPal oppure con qualsiasi carta su Stripe.</p>

    <div class="grid-3">
        <!-- Colonna 1: Wise / Privat24 / Monobank -->
        <div class="card">
            <div>
                <h3>🏦 Wise / Приват24 / Монобанк</h3>
                <p>Переказ за європейським IBAN (ідеально для оплати з карток <strong>Privat24</strong> та <strong>Monobank</strong> у євро або гривні):<br>
                <small>Bonifico SEPA istantaneo (perfetto da Privat24 e Monobank):</small></p>
                <p style="margin:0.3rem 0;"><strong>Отримувач / Intestatario:</strong> Antonio Morabito</p>
                <div class="iban-box" id="ibanText">BE27 9670 8684 5173</div>
                <p style="font-size:0.85rem; color:#475569;">Після оплати надішліть квитанцію у WhatsApp або Viber.<br>Dopo il bonifico invia la ricevuta su WhatsApp o Viber.</p>
            </div>
            <button class="btn btn-primary" onclick="copyIban()">📋 Скопіювати IBAN / Copia IBAN</button>
        </div>

        <!-- Colonna 2: PayPal -->
        <div class="card">
            <div>
                <h3>💳 PayPal</h3>
                <p>Швидка та захищена оплата через ваш акаунт PayPal (вкажіть суму 9,90 € або 19,90 €):<br>
                <small>Pagamento immediato e sicuro tramite PayPal:</small></p>
                <p style="font-weight:bold; color:var(--ua-blue); margin: 1rem 0;">paypal.me/Antonio463</p>
            </div>
            <a href="https://www.paypal.me/Antonio463" target="_blank" class="btn btn-primary" onclick="bumpStat('compile')">Оплатити через PayPal / Paga con PayPal</a>
        </div>

        <!-- Colonna 3: Stripe -->
        <div class="card">
            <div>
                <h3>🔒 Stripe (Visa / Mastercard / Apple & Google Pay)</h3>
                <p>Офіційна захищена оплата будь-якою банківською карткою в один клік без реєстрації:<br>
                <small>Pagamento diretto con carta di credito, debito, Apple Pay o Google Pay:</small></p>
                <p style="font-weight:bold; color:var(--success); margin: 1rem 0;">✅ Автоматичне підтвердження / Conferma immediata</p>
            </div>
            <a href="https://buy.stripe.com/6oUdR2gpC3UJ3OO5fX28801" target="_blank" class="btn btn-success" onclick="bumpStat('compile')">Оплатити карткою (Stripe) / Paga con Stripe</a>
        </div>
    </div>

    <!-- 5. CONTATTI DIRETTI -->
    <h2 class="section-title">4. Прямий Зв'язок / Contatto Diretto Rapido</h2>
    <p class="section-sub">Маєте запитання або вже оплатили послугу? Напишіть нам напряму за номером <strong>+39 393 195 1395</strong>:<br>
    Hai domande o hai effettuato il pagamento? Scrivici subito su WhatsApp, Viber o Telegram:</p>
    <div class="btn-row" style="justify-content:center; margin-bottom:2rem;">
        <a href="https://wa.me/393931951395?text=Доброго%20дня!%20Пишу%20з%20сайту%20assistenzaucraini.it" target="_blank" class="btn btn-wa">💬 WhatsApp (+39 393 1951395)</a>
        <a href="viber://chat?number=%2B393931951395" class="btn btn-vb">💜 Viber (+39 393 1951395)</a>
        <a href="https://t.me/+393931951395" target="_blank" class="btn btn-tg">✈️ Telegram (+39 393 1951395)</a>
    </div>

</div>

<!-- Finestra di conferma e rassicurazione utente -->
<div class="alert-modal" id="confirmModal">
    <div class="alert-content">
        <h3 style="color:var(--success); margin-top:0;">✅ Дякуємо за звернення! / Grazie per la tua richiesta!</h3>
        <p id="modalMsg">Ваш документ підготовлено. Зараз відкриється чат, щоб ви могли надіслати дані нашому спеціалісту. Не хвилюйтеся, ми відповімо вам якнайшвидше!<br><br>
        Il tuo modulo è pronto. Tra un istante si aprirà la chat per inviare i dati: ti risponderemo al più presto!</p>
        <button class="btn btn-primary" onclick="closeModal()">Зрозуміло / Ho capito</button>
    </div>
</div>

<footer>
    <p><strong>Портал Італія — assistenzaucraini.it</strong> | Supporto Documentale e Assistenza per la Comunità Ucraina in Italia</p>
    <p>Contatto diretto WhatsApp / Viber / Telegram: +39 393 195 1395 | Pagamenti sicuri verificati Stripe, PayPal, Wise</p>
    <p style="font-size:0.8rem; opacity:0.75;">&copy; 2026 assistenzaucraini.it - Tutti i diritti riservati. Conformità GDPR e Cookie Policy (LegalBlink).</p>
</footer>

<script>
    let currentType = 'cf';

    // Configurazione titoli ed etichette extra per i 6 generatori
    const docConfig = {
        cf: {
            title: "1. Richiesta Codice Fiscale (Mod. AA4/8) / Запит на Податковий код",
            extraLabel: "Телефон або Email / Telefono o Email di contatto:",
            extraPlaceholder: "Es. +39 333 1234567"
        },
        ts: {
            title: "2. Iscrizione Servizio Sanitario (Tessera Sanitaria ASL) / Медична картка",
            extraLabel: "Тип дозволу на проживання (напр. Protezione Temporanea) / Tipo Permesso:",
            extraPlaceholder: "Es. Permesso per Protezione Temporanea / Richiesta Medico di Base"
        },
        scuola: {
            title: "3. Domanda Iscrizione Scolastica e Agevolazione Mensa / Запис до школи та їдальні",
            extraLabel: "Ім'я дитини та назва школи/класу / Nome Alunno, Scuola e Classe:",
            extraPlaceholder: "Es. Alunno: Taras Shevchenko - Scuola Primaria di Saronno, Classe 3A"
        },
        osp: {
            title: "4. Dichiarazione di Ospitalità (Art. 7 D.Lgs. 286/98) / Декларація про надання житла",
            extraLabel: "Прізвище та Ім'я власника житла (Хто приймає) / Nome e Cognome Ospitante:",
            extraPlaceholder: "Es. Ospitante: Mario Rossi - Cede in ospitalità dal 20/10/2026"
        },
        patente: {
            title: "5. Domanda Conversione Patente Ucraina (Mod. TT2112) / Конвертація посвідчення водія",
            extraLabel: "Номер та категорія українських прав / Numero e Categoria Patente Ucraina:",
            extraPlaceholder: "Es. Patente UA n. BXT123456 - Categoria B"
        },
        kit209: {
            title: "6. Guida Operativa a Caselle Kit Postale (Mod. 209 - Modulo 1) / Інструкція для Пошти",
            extraLabel: "Підстава дозволу (напр. Lavoro / Famiglia / Conversione) / Motivo soggiorno:",
            extraPlaceholder: "Es. Rinnovo / Conversione Permesso di Soggiorno"
        }
    };

    function switchDoc(type, btnEl) {
        currentType = type;
        document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
        btnEl.classList.add('active');
        document.getElementById('formTitle').innerText = docConfig[type].title;
        document.getElementById('lbl_extra').innerText = docConfig[type].extraLabel;
        document.getElementById('in_extra').placeholder = docConfig[type].extraPlaceholder;
        renderDoc();
    }

    function val(id, fallback) {
        const v = document.getElementById(id).value.trim();
        return v ? v.toUpperCase() : fallback;
    }

    function renderDoc() {
        const cognome = val('in_cognome', '____________________');
        const nome = val('in_nome', '____________________');
        const nascitaRaw = document.getElementById('in_nascita').value;
        const nascita = nascitaRaw ? nascitaRaw.split('-').reverse().join('/') : '__/__/____';
        const luogo = val('in_luogo', 'UCRAINA (EE)');
        const cf = val('in_cf', '____________________');
        const comune = val('in_comune', '____________________');
        const indirizzo = val('in_indirizzo', '____________________');
        const doc = val('in_doc', '____________________');
        const extra = val('in_extra', '____________________');
        const oggi = new Date().toLocaleDateString('it-IT');

        let html = '';

        if (currentType === 'cf') {
            html = `
                <h2>AGENZIA DELLE ENTRATE</h2>
                <h4>DOMANDA DI ATTRIBUZIONE CODICE FISCALE (SCHEMA MOD. AA4/8)</h4>
                <div class="doc-line"><strong>QUADRO A - Tipologia richiesta:</strong> Attribuzione Codice Fiscale / Richiesta tesserino</div>
                <div class="doc-line"><strong>QUADRO B - Dati Anagrafici del Richiedente:</strong></div>
                <div class="doc-line">Cognome: <strong>${cognome}</strong></div>
                <div class="doc-line">Nome: <strong>${nome}</strong></div>
                <div class="doc-line">Data di nascita: <strong>${nascita}</strong> — Stato/Luogo di nascita: <strong>${luogo}</strong></div>
                <div class="doc-line"><strong>QUADRO D - Domicilio in Italia:</strong></div>
                <div class="doc-line">Comune: <strong>${comune}</strong></div>
                <div class="doc-line">Indirizzo: <strong>${indirizzo}</strong></div>
                <div class="doc-line"><strong>Documento di riconoscimento (Passaporto):</strong> <strong>${doc}</strong></div>
                <div class="doc-line">Recapito Telefonico / Email: <strong>${extra}</strong></div>
                <p style="margin-top:1.2rem; font-size:0.9rem;">Il/La sottoscritto/a richiede l'attribuzione del Codice Fiscale ai sensi della normativa vigente per cittadini ucraini presenti sul territorio nazionale.</p>
                <div class="doc-sign">
                    <span>Luogo e Data: ${comune}, ${oggi}</span>
                    <span>Firma del Richiedente: ______________________</span>
                </div>
            `;
        } else if (currentType === 'ts') {
            html = `
                <h2>AZIENDA SANITARIA LOCALE (ASL / ATS)</h2>
                <h4>DOMANDA DI ISCRIZIONE AL SERVIZIO SANITARIO NAZIONALE E RILASCIO TESSERA SANITARIA</h4>
                <div class="doc-line">Il/La sottoscritto/a: <strong>${cognome} ${nome}</strong></div>
                <div class="doc-line">Nato/a il: <strong>${nascita}</strong> in <strong>${luogo}</strong></div>
                <div class="doc-line">Codice Fiscale: <strong>${cf}</strong></div>
                <div class="doc-line">Domiciliato/a in: <strong>${comune}</strong> — Via/Piazza: <strong>${indirizzo}</strong></div>
                <div class="doc-line">Documento / Passaporto n.: <strong>${doc}</strong></div>
                <div class="doc-line">Titolo di soggiorno / Note: <strong>${extra}</strong></div>
                <p style="margin-top:1rem;"><strong>CHIEDE</strong> l'iscrizione al Servizio Sanitario Nazionale (SSN), l'assegnazione del Medico di Medicina Generale / Pediatra di Libera Scelta e l'emissione della Tessera Sanitaria.</p>
                <div class="doc-sign">
                    <span>Luogo e Data: ${comune}, ${oggi}</span>
                    <span>Firma: ______________________</span>
                </div>
            `;
        } else if (currentType === 'scuola') {
            html = `
                <h2>AL DIRIGENTE SCOLASTICO / ALL'UFFICIO SCUOLA DEL COMUNE DI ${comune}</h2>
                <h4>DOMANDA DI ISCRIZIONE SCOLASTICA E RICHIESTA AGEVOLAZIONE MENSA / TRASPORTO</h4>
                <div class="doc-line">Il/La sottoscritto/a genitore/tutore: <strong>${cognome} ${nome}</strong></div>
                <div class="doc-line">Nato/a il: <strong>${nascita}</strong> in <strong>${luogo}</strong> — C.F.: <strong>${cf}</strong></div>
                <div class="doc-line">Domiciliato/a a: <strong>${comune}</strong> in <strong>${indirizzo}</strong> (Doc.: <strong>${doc}</strong>)</div>
                <div class="doc-line"><strong>Dati Alunno/a, Scuola e Classe richiesta:</strong> <strong>${extra}</strong></div>
                <p style="margin-top:1rem;"><strong>CHIEDE</strong> l'inserimento scolastico del/la minore sopraindicato/a ai sensi delle disposizioni per l'accoglienza degli alunni provenienti dall'Ucraina, nonché l'accesso ai servizi di refezione scolastica (mensa) e trasporto con applicazione delle agevolazioni previste.</p>
                <div class="doc-sign">
                    <span>Luogo e Data: ${comune}, ${oggi}</span>
                    <span>Firma del Genitore: ______________________</span>
                </div>
            `;
        } else if (currentType === 'osp') {
            html = `
                <h2>ALL'AUTORITÀ LOCALE DI PUBBLICA SICUREZZA (QUESTURA / COMUNE DI ${comune})</h2>
                <h4>DICHIARAZIONE DI OSPITALITÀ / CESSIONE DI FABBRICATO (ART. 7 D.LGS. 286/98)</h4>
                <div class="doc-line"><strong>Dati Soggetto Ospitante (Dichiarante):</strong> <strong>${extra}</strong></div>
                <div class="doc-line">DICHIARA di aver fornito alloggio / ospitalità presso l'immobile sito in:</div>
                <div class="doc-line">Comune di: <strong>${comune}</strong> — Indirizzo: <strong>${indirizzo}</strong></div>
                <div class="doc-line"><strong>In favore del cittadino/a ucraino/a (Ospite):</strong></div>
                <div class="doc-line">Cognome: <strong>${cognome}</strong> — Nome: <strong>${nome}</strong></div>
                <div class="doc-line">Data di nascita: <strong>${nascita}</strong> — Luogo di nascita: <strong>${luogo}</strong></div>
                <div class="doc-line">Codice Fiscale: <strong>${cf}</strong> — Passaporto n.: <strong>${doc}</strong></div>
                <p style="margin-top:1rem; font-size:0.88rem;">Si allegano copia del documento d'identità del dichiarante, copia del passaporto dell'ospite e titolo di disponibilità dell'immobile.</p>
                <div class="doc-sign">
                    <span>Luogo e Data: ${comune}, ${oggi}</span>
                    <span>Firma dell'Ospitante: ______________________</span>
                </div>
            `;
        } else if (currentType === 'patente') {
            html = `
                <h2>UFFICIO MOTORIZZAZIONE CIVILE (UMC)</h2>
                <h4>DOMANDA DI CONVERSIONE PATENTE DI GUIDA UCRAINA (SCHEMA MOD. TT2112)</h4>
                <div class="doc-line">Il/La sottoscritto/a: <strong>${cognome} ${nome}</strong></div>
                <div class="doc-line">Nato/a il: <strong>${nascita}</strong> in <strong>${luogo}</strong></div>
                <div class="doc-line">Codice Fiscale: <strong>${cf}</strong></div>
                <div class="doc-line">Residente/Domiciliato in: <strong>${comune}</strong> — Indirizzo: <strong>${indirizzo}</strong></div>
                <div class="doc-line">Documento di identità / Passaporto: <strong>${doc}</strong></div>
                <div class="doc-line"><strong>Estremi Patente Ucraina da convertire:</strong> <strong>${extra}</strong></div>
                <p style="margin-top:1rem;"><strong>CHIEDE</strong> la conversione senza esami della propria patente di guida rilasciata in Ucraina in patente di guida italiana ai sensi dell'Accordo Italia-Ucraina vigente.</p>
                <div class="doc-sign">
                    <span>Luogo e Data: ${comune}, ${oggi}</span>
                    <span>Firma del Richiedente: ______________________</span>
                </div>
            `;
        } else if (currentType === 'kit209') {
            html = `
                <h2>GUIDA ALLA COMPILAZIONE A CASELLE - KIT POSTALE MOD. 209 (MODULO 1)</h2>
                <h4>SCHEMA DI CONTROLLO CASELLE PER QUESTURA / SPORTELLO AMICO POSTE</h4>
                <div class="kit-box">[Sez. 1 - Dati Richiedente] Casella Cognome: <strong>${cognome}</strong> | Casella Nome: <strong>${nome}</strong></div>
                <div class="kit-box">[Sez. 2 - Codice Fiscale (16 caselle)] <strong>${cf}</strong></div>
                <div class="kit-box">[Sez. 3 - Nascita] Data (GG/MM/AAAA): <strong>${nascita}</strong> | Codice Stato: <strong>UKR (Ucraina)</strong></div>
                <div class="kit-box">[Sez. 4 - Passaporto] Numero: <strong>${doc}</strong> | Autorità rilascio: <strong>01 (Governo)</strong></div>
                <div class="kit-box">[Sez. 5 - Recapito in Italia] Comune: <strong>${comune}</strong> | Indirizzo: <strong>${indirizzo}</strong></div>
                <div class="kit-box">[Sez. 6 - Tipologia Richiesta] Motivo indicato: <strong>${extra}</strong></div>
                <p style="font-size:0.88rem; margin-top:0.8rem;">⚠️ <strong>Regola d'oro per le Poste:</strong> Compila il modulo cartaceo con penna NERA in stampatello maiuscolo, una lettera per ogni casella, e NON firmare prima di essere davanti all'operatore dello Sportello Amico.</p>
            `;
        }

        document.getElementById('printableArea').innerHTML = html;
    }

    // Gestione Contatori Automatici
    function initStats() {
        ['compile', 'download', 'print'].forEach(k => {
            const saved = localStorage.getItem('ua_stat_' + k);
            if (saved) document.getElementById('cnt-' + k).innerText = saved;
        });
    }

    function bumpStat(type) {
        const el = document.getElementById('cnt-' + type);
        let current = parseInt(el.innerText, 10) || 0;
        current += 1;
        el.innerText = current;
        localStorage.setItem('ua_stat_' + type, current);
    }

    function actionPrint() {
        bumpStat('compile');
        bumpStat('print');
        window.print();
    }

    function actionDownload() {
        bumpStat('compile');
        bumpStat('download');
        const content = document.getElementById('printableArea').innerHTML;
        const fullHtml = `<!DOCTYPE html><html lang="it"><head><meta charset="UTF-8"><title>Modulo_Ufficiale_${currentType}</title><style>body{font-family:'Times New Roman',serif;padding:40px;line-height:1.5;max-width:800px;margin:auto;}h2,h4{text-align:center;}.doc-line{margin-bottom:10px;}.doc-sign{margin-top:45px;display:flex;justify-content:space-between;}</style></head><body>${content}</body></html>`;
        const blob = new Blob([fullHtml], { type: 'text/html;charset=utf-8' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `Modulo_${currentType.toUpperCase()}_assistenzaucraini.html`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    function actionSendCheck(channel) {
        bumpStat('compile');
        const cognome = val('in_cognome', '-');
        const nome = val('in_nome', '-');
        const comune = val('in_comune', '-');
        const msg = encodeURIComponent(`Доброго дня! Хочу перевірити модуль (${currentType.toUpperCase()}): ${cognome} ${nome}, Comune: ${comune}. / Salve, vorrei il controllo del modulo ${currentType.toUpperCase()}.`);
        document.getElementById('confirmModal').style.display = 'flex';
        setTimeout(() => {
            window.open(`https://wa.me/393931951395?text=${msg}`, '_blank');
        }, 1200);
    }

    function closeModal() {
        document.getElementById('confirmModal').style.display = 'none';
    }

    function copyIban() {
        const iban = "BE27967086845173";
        navigator.clipboard.writeText(iban).then(() => {
            alert("✅ IBAN скопійовано: BE27 9670 8684 5173\nIBAN copiato negli appunti!");
        });
    }

    window.onload = function() {
        initStats();
        renderDoc();
    };
</script>

</body>
</html>