// app/beach/actions.ts

'use server';

import nodemailer from 'nodemailer';

export async function submitRegistration(prevState: unknown, formData: FormData) {
    // 1. Spara all rådata direkt för att kunna skicka tillbaka den vid fel
    const rawData = {
        name: formData.get('name') as string,
        email: formData.get('email') as string,
        tel: formData.get('tel') as string,
        team: formData.get('team') as string,
        count: formData.get('count') as string,
        level: formData.get('level') as string,
        message: formData.get('message') as string,
    };

    const honeypot = formData.get('website');
    if (honeypot) {
        return { success: false, message: 'Spam detekterat.', values: rawData };
    }

    // 2. Hämta Turnstile Token och Secret (MATCHING .env NAME)
    const turnstileToken = formData.get('cf-turnstile-response');
    const secretKey = process.env.TURNSTILE_SECRET; // Matchar din .env exakt

    if (!secretKey) {
        console.error("Saknar TURNSTILE_SECRET i miljön.");
        return {
            success: false,
            message: 'Serverkonfiguration saknas. Kontakta administratör.',
            values: rawData
        };
    }

    // 3. Verifiera mot Cloudflare
    try {
        const turnstileRes = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                secret: secretKey,
                response: String(turnstileToken || ''),
            }),
        });

        const turnstileData = await turnstileRes.json();

        if (!turnstileData.success) {
            console.error("Turnstile failed:", turnstileData);
            return {
                success: false,
                message: 'Säkerhetsverifieringen misslyckades. Ladda om sidan och försök igen.',
                values: rawData
            };
        }
    } catch (error) {
        console.error("Turnstile fetch error:", error);
        return {
            success: false,
            message: 'Kunde inte nå verifieringsservern.',
            values: rawData
        };
    }

    // 4. Formatera telefonnummer
    let cleanTel = rawData.tel.replace(/\D/g, '');
    if (cleanTel.startsWith('46')) cleanTel = cleanTel.substring(2);
    else if (cleanTel.startsWith('0')) cleanTel = cleanTel.substring(1);

    const formattedTel = cleanTel.length === 9
        ? `+46 (0)${cleanTel.substring(0, 2)}-${cleanTel.substring(2, 5)} ${cleanTel.substring(5, 7)} ${cleanTel.substring(7, 9)}`
        : rawData.tel;

    // 5. Nodemailer setup
    const transporter = nodemailer.createTransport({
        host: process.env.SMTP_HOST,
        port: 587,
        secure: false,
        auth: {
            user: process.env.SMTP_USER,
            pass: process.env.SMTP_PASS,
        },
        tls: {
            rejectUnauthorized: false
        }
    });

    try {
        const dateStr = new Date().toLocaleString('sv-SE', {
            timeZone: 'Europe/Stockholm',
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
        const cleanMessage = rawData.message ? rawData.message.replace(/[\r\n;]/g, " ") : "";

        // Mail till klubben
        await transporter.sendMail({
            from: `"Beach-anmälan: ${rawData.name}" <${process.env.SMTP_USER}>`,
            to: 'beach@lerbergetsvolleyboll.se',
            replyTo: rawData.email,
            subject: `Anmälan: ${rawData.team}`,
            html: `
            <html>
            <body style='font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 800px; padding: 20px;'>
                <h2 style='color: #39979f;'>Beach-anmälan</h2>
                
                <table style='width: 100%; max-width: 600px; border-collapse: collapse;'>
                    <tr><td style='padding: 5px; font-weight: bold; width: 150px;'>Lagnamn:</td><td>${rawData.team}</td></tr>
                    <tr><td style='padding: 5px; font-weight: bold;'>Kontakt:</td><td>${rawData.name}</td></tr>
                    <tr><td style='padding: 5px; font-weight: bold;'>E-post:</td><td>${rawData.email}</td></tr>
                    <tr><td style='padding: 5px; font-weight: bold;'>Telefon:</td><td>${formattedTel}</td></tr>
                    <tr><td style='padding: 5px; font-weight: bold;'>Spelare:</td><td>${rawData.count}</td></tr>
                    <tr><td style='padding: 5px; font-weight: bold;'>Nivå:</td><td>${rawData.level}</td></tr>
                </table>
                <p><strong>Meddelande:</strong><br>${rawData.message ? rawData.message.replace(/\n/g, '<br>') : '<em>Inget meddelande</em>'}</p>
                
                <hr style='border: none; border-top: 1px solid #ddd; margin: 30px 0;'>
                
                <details style="margin-top: 20px;">
                    <summary style="background-color: #fdb84b; color: #fff; padding: 12px 20px; border-radius: 8px; font-weight: bold; cursor: pointer; display: inline-block; font-size: 14px; text-transform: uppercase; letter-spacing: 1px;">
                        Visa kopierbar tabell för Excel
                    </summary>
                    
                    <div style="margin-top: 15px; overflow-x: auto;">
                        <table border='1' style='border-collapse: collapse; font-family: Calibri, sans-serif; font-size: 11pt; width: 100%; text-align: left;'>
                            <tr style="background-color: #f9f9f9;">
                                <td style='padding: 8px; border: 1px solid #ccc;'>${rawData.team}</td>
                                <td style='padding: 8px; border: 1px solid #ccc;'>${rawData.count}</td>
                                <td style='padding: 8px; border: 1px solid #ccc;'>${rawData.level}</td>
                                <td style='padding: 8px; border: 1px solid #ccc;'>${rawData.name}</td>
                                <td style='padding: 8px; border: 1px solid #ccc;'>${formattedTel}</td>
                                <td style='padding: 8px; border: 1px solid #ccc;'>${rawData.email}</td>
                                <td style='padding: 8px; border: 1px solid #ccc;'>${dateStr}</td>
                                <td style='padding: 8px; border: 1px solid #ccc;'>${cleanMessage}</td>
                            </tr>
                        </table>
                    </div>
                </details>
            </body>
            </html>
            `
        });

        // Bekräftelse till användaren
        await transporter.sendMail({
            from: `"LVS" <${process.env.SMTP_USER}>`,
            to: rawData.email,
            replyTo: `"LVS Beach" <beach@lerbergetsvolleyboll.se>`,
            subject: `Vi har tagit emot din anmälan för ${rawData.team}`,
            html: `<div style="font-family: sans-serif; padding: 20px; color: #333;">
                <h2 style="color: #39979f;">Hej ${rawData.name}!</h2>
                <p>Tack för din anmälan till beachturneringen. Vi återkommer så snart vi har granskat era uppgifter.</p>
                <p>Ses på stranden!<br><strong style="color: #fdb84b;">Lerbergets Volleybollsällskap</strong></p>
            </div>`
        });

        // Returnerar INGA värden här, vilket gör att formuläret kan rensas rent
        return { success: true, message: 'Tack! Din anmälan har skickats. Håll utkik i din inkorg efter bekräftelse.' };
    } catch (e) {
        console.error("Nodemailer error:", e);
        return {
            success: false,
            message: 'Kunde inte skicka mail. Kontakta oss manuellt istället.',
            values: rawData
        };
    }
}