jQuery(document).ready(function($) {
    $('#imdb-form').on('submit', function(e) {
        e.preventDefault(); // This stops page reload

        const imdbID = $('#imdb-id').val().trim();
        const $result = $('#imdb-result');
        const $loading = $('#imdb-loading');

        if (!imdbID) {
            alert('Please enter IMDb ID (e.g. tt0111161)');
            return;
        }

        $loading.show();
        $result.html('');

        $.ajax({
            url: imdbAjax.url,
            method: 'POST',
            data: {
                action: 'fetch_imdb_movie',
                imdb_id: imdbID,
                nonce: imdbAjax.nonce
            },
            success: function(res) {
                $loading.hide();

                if (res.success) {
                    const m = res.data;
                    $result.html(`
                        <div class="imdb-movie-card" style="display:flex;gap:20px;margin-top:20px;">
                            ${m.Poster !== 'N/A' ? `<img src="${m.Poster}" style="max-width:300px;border-radius:8px;">` : ''}
                            <div>
                                <h2>${m.Title} <small>(${m.Year})</small></h2>
                                <p><strong>Rated:</strong> ${m.Rated} | <strong>Runtime:</strong> ${m.Runtime}</p>
                                <p><strong>Genre:</strong> ${m.Genre}</p>
                                <p><strong>Director:</strong> ${m.Director}</p>
                                <p><strong>Cast:</strong> ${m.Actors}</p>
                                <p><strong>IMDb Rating:</strong> ⭐ ${m.imdbRating}/10 (${m.imdbVotes} votes)</p>
                                <p><em>${m.Plot}</em></p>
                                <p><a href="https://imdb.com/title/${m.imdbID}" target="_blank">View on IMDb.com</a></p>
                            </div>
                        </div>
                    `);
                } else {
                    $result.html(`<p style="color:red;">${res.data.message}</p>`);
                }
            },
            error: function() {
                $loading.hide();
                $result.html('<p style="color:red;">Server error. Try again later.</p>');
            }
        });
    });
});