{{--
    Ported from the design bundle (ai-marketing-platform-assets, 8 Sep 2026):
    includes/components/new-creative.php + assets/js/new-creative.js.
    Markup/classes (mb-wizard, mb-steps, mb-option, mb-field-card, mb-ratios,
    mb-segment, mb-review, mb-wizard-foot, ...) are kept as shipped; only the
    data and behavior are ours (real Livewire actions instead of client JS).

    Deviations from the design:
    - The design's flow is 6 fixed steps (Type, Starting point, Details,
      Style, Format, Review). This component's flow additionally has extra
      steps only for video creatives (Duration, Script, Avatar, Voice,
      Storyboard) — ChatWizard::stepOrder()/tabs() insert those between
      Format and Review. There's no shipped design for those, so they reuse
      the same mb-field-card/mb-option/mb-segment classes for visual
      consistency with the rest of the wizard.
    - "Style" now ports the design's example-ad image gallery (mb-style-grid/
      mb-style-card, size filter chips, zoom preview) using the real preview
      images shipped in the design bundle. "Auto" is a purely client-side
      choice (empty $style, no AI call at pick time) — a suggestion, or no
      preference, is decided later at generate time.
    - Clicking an option/preset both selects and advances (as the previous
      chat-based version did) rather than select-then-press-Continue, to
      avoid reworking the underlying state machine; Back/Edit still work via
      goBack()/goToStep(). The Style and Format steps are the exceptions —
      Format bundles ratio + duration + variations onto one screen and Style's
      gallery needs browsing/filtering before committing, so both select on
      click and require the footer's Continue button to advance, like the
      design.
--}}
@push('styles')
    <link href="{{ asset('assets/mb/css/creatives.css') }}?v={{ filemtime(public_path('assets/mb/css/creatives.css')) }}" rel="stylesheet">
@endpush

@php
    $order = $this->stepOrder();
    $currentIndex = array_search($step, $order, true) ?: 0;
    $tabs = $this->tabs();
@endphp

<div class="mb-page-flex">
    <div class="mb-wizard" id="new-creative">

        <div class="mb-wizard-head">
            <div class="mb-page-head">
                <div>
                    <a class="mb-back" href="{{ route('creatives.index') }}" wire:navigate><i class="bi bi-arrow-left"></i>All creatives</a>
                    <h1 class="mb-page-title">{{ $type ? 'New '.$type.' creative' : 'New creative' }}</h1>
                </div>
            </div>
            <div class="mb-steps">
                @foreach ($tabs as $label => $tabStep)
                    @php $tabIndex = array_search($tabStep, $order, true); @endphp
                    <div class="mb-step {{ $tabIndex < $currentIndex ? 'is-done' : ($tabIndex === $currentIndex ? 'is-active' : '') }}">
                        <div class="mb-step-bar"><i></i></div>
                        <div class="mb-step-label">{{ $label }}</div>
                    </div>
                @endforeach
            </div>
        </div>

        <div class="mb-wizard-scroll">
            <div>

                @if ($videoNotice)
                    <div class="mb-note is-info mb-3"><i class="bi bi-info-circle"></i><div>{{ $videoNotice }}</div></div>
                @endif

                {{-- Step: Type --}}
                @if ($step === 'type')
                    <div class="mb-step-head">
                        <span class="mb-eyebrow"><i class="bi bi-stars"></i>Step {{ $currentIndex + 1 }} of {{ count($order) - 1 }}</span>
                        <h2 class="mb-step-title">What are you creating?</h2>
                        <p class="mb-step-sub">Pick the format — you can change it later from the creative.</p>
                    </div>

                    <div class="mb-field-card mb-3">
                        <label class="mb-label" for="mb-project-name">Project Name <span class="text-muted fw-normal">(Optional)</span></label>
                        <input class="mb-input" id="mb-project-name" type="text" wire:model.defer="projectName" placeholder="Mention brand or website">
                    </div>

                    <div class="mb-options">
                        <button type="button" class="mb-option" wire:click="selectType('image')">
                            <span class="mb-option-icon"><i class="bi bi-image"></i></span>
                            <span><span class="mb-option-title">Image ad</span>
                            <span class="mb-option-desc d-block">Static creative for display, social and retargeting.</span></span>
                            <span class="mb-option-check"><i class="bi bi-check-lg"></i></span>
                        </button>
                        <button type="button" class="mb-option" wire:click="selectType('video')">
                            <span class="mb-option-icon"><i class="bi bi-play-btn"></i></span>
                            <span><span class="mb-option-title">Video ad</span>
                            <span class="mb-option-desc d-block">Short motion cut built from your product assets.</span></span>
                            <span class="mb-option-check"><i class="bi bi-check-lg"></i></span>
                        </button>
                    </div>

                {{-- Step: Source --}}
                @elseif ($step === 'source')
                    <div class="mb-step-head">
                        <span class="mb-eyebrow"><i class="bi bi-stars"></i>Step {{ $currentIndex + 1 }} of {{ count($order) - 1 }}</span>
                        <h2 class="mb-step-title">How do you want to start?</h2>
                        <p class="mb-step-sub">Give us something to work from — a link, a description, or your own assets.</p>
                    </div>
                    <div class="mb-options">
                        <button type="button" class="mb-option" wire:click="selectSource('product_url')">
                            <span class="mb-option-icon"><i class="bi bi-link-45deg"></i></span>
                            <span><span class="mb-option-title">Product URL</span>
                            <span class="mb-option-desc d-block">We read the page and pull copy, colours and imagery.</span></span>
                            <span class="mb-option-check"><i class="bi bi-check-lg"></i></span>
                        </button>
                        <button type="button" class="mb-option" wire:click="selectSource('prompt')">
                            <span class="mb-option-icon"><i class="bi bi-chat-square-text"></i></span>
                            <span><span class="mb-option-title">Describe it</span>
                            <span class="mb-option-desc d-block">Write what you want and we build it from scratch.</span></span>
                            <span class="mb-option-check"><i class="bi bi-check-lg"></i></span>
                        </button>
                        <button type="button" class="mb-option" wire:click="selectSource('upload')">
                            <span class="mb-option-icon"><i class="bi bi-cloud-arrow-up"></i></span>
                            <span><span class="mb-option-title">Upload images</span>
                            <span class="mb-option-desc d-block">Start from product shots you already have.</span></span>
                            <span class="mb-option-check"><i class="bi bi-check-lg"></i></span>
                        </button>
                        <button type="button" class="mb-option" wire:click="selectSource('existing')">
                            <span class="mb-option-icon"><i class="bi bi-collection"></i></span>
                            <span><span class="mb-option-title">Existing creative</span>
                            <span class="mb-option-desc d-block">Remix something from your library.</span></span>
                            <span class="mb-option-check"><i class="bi bi-check-lg"></i></span>
                        </button>
                        <button type="button" class="mb-option" wire:click="selectSource('competitor')">
                            <span class="mb-option-icon"><i class="bi bi-binoculars"></i></span>
                            <span><span class="mb-option-title">Competitor ad</span>
                            <span class="mb-option-desc d-block">Reference an ad that is already working.</span></span>
                            <span class="mb-option-check"><i class="bi bi-check-lg"></i></span>
                        </button>
                    </div>

                {{-- Step: Details — search Meta's Ad Library for a competitor ad --}}
                @elseif ($step === 'competitor_search')
                    <div class="mb-step-head">
                        <span class="mb-eyebrow"><i class="bi bi-stars"></i>Step {{ $currentIndex + 1 }} of {{ count($order) - 1 }}</span>
                        <h2 class="mb-step-title">Search for a competitor ad</h2>
                        <p class="mb-step-sub">Search Meta's Ad Library by brand or keyword, then pick an ad to use as inspiration.</p>
                    </div>
                    <div class="mb-field-card">
                        <div class="mb-adlib-search">
                            <div class="mb-adlib-search-query">
                                <label class="mb-label" for="mb-competitor-query">Brand or keyword</label>
                                <input class="mb-input @error('competitorQuery') is-invalid @enderror" id="mb-competitor-query" type="text" wire:model="competitorQuery" wire:keydown.enter="searchCompetitorAds" placeholder="e.g. Nike" autofocus>
                            </div>
                            <div class="mb-adlib-search-country">
                                <label class="mb-label" for="mb-competitor-country">Country</label>
                                <select class="mb-input @error('competitorCountry') is-invalid @enderror" id="mb-competitor-country" wire:model="competitorCountry">
                                    @foreach ($this->competitorCountries() as $label => $code)
                                        <option value="{{ $code }}">{{ $label }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <button type="button" class="mb-btn-primary mb-adlib-search-submit" wire:click="searchCompetitorAds" wire:loading.attr="disabled" wire:target="searchCompetitorAds" @disabled($competitorSearchPending)>Search</button>
                        </div>
                        @error('competitorCountry')
                            <div class="mb-error is-on">{{ $message }}</div>
                        @enderror
                        @error('competitorQuery')
                            <div class="mb-error is-on">{{ $message }}</div>
                        @enderror
                        @if ($competitorSearchPending)
                            <div wire:poll.2s="pollCompetitorAds" class="small text-muted mt-2">Searching Meta's Ad Library&hellip; this can take a minute.</div>
                        @else
                            <div wire:loading wire:target="searchCompetitorAds" class="small text-muted mt-2">Searching&hellip;</div>
                        @endif

                        @if (count($competitorResults))
                            <div class="mb-adlib mt-3">
                                @foreach ($competitorResults as $ad)
                                    @php
                                        $snapshotUrl = $ad['snapshot']['ad_snapshot_url'] ?? null;
                                        $snapshotIsHttp = is_string($snapshotUrl) && preg_match('#^https?://#i', $snapshotUrl) === 1;
                                        $thumbUrl = $ad['thumbnail_url'] ?? null;
                                        $linkTitle = $ad['snapshot']['ad_creative_link_titles'][0] ?? null;
                                        $linkCaption = $ad['snapshot']['ad_creative_link_captions'][0] ?? null;
                                        $body = $ad['snapshot']['ad_creative_bodies'][0] ?? null;
                                        $startedAt = $ad['snapshot']['ad_delivery_start_time'] ?? null;
                                        $ageLabel = filled($startedAt)
                                            ? ((int) now()->diffInDays(\Illuminate\Support\Carbon::parse($startedAt), true)).'D'
                                            : null;
                                        $initial = \Illuminate\Support\Str::upper(\Illuminate\Support\Str::substr($ad['advertiser_name'], 0, 1));
                                    @endphp
                                    <article
                                        wire:key="competitor-{{ $ad['external_ad_id'] }}"
                                        class="mb-adlib-card {{ $selectedCompetitorAdId === $ad['external_ad_id'] ? 'is-selected' : '' }}"
                                        wire:click="selectCompetitorAd('{{ $ad['external_ad_id'] }}')"
                                    >
                                        <div class="mb-adlib-head">
                                            <span class="mb-adlib-avatar" aria-hidden="true">{{ $initial }}</span>
                                            <div class="mb-adlib-head-text">
                                                <span class="mb-adlib-name">{{ $ad['advertiser_name'] }}</span>
                                                <!-- <span class="mb-adlib-id">ID {{ $ad['external_ad_id'] }}</span> -->
                                            </div>
                                            @if ($ageLabel)
                                                <span class="mb-adlib-age"><span class="mb-adlib-age-dot"></span>{{ $ageLabel }}</span>
                                            @endif
                                        </div>

                                        @if (filled($body))
                                            <p class="mb-adlib-copy">{{ $body }}</p>
                                        @endif

                                        <div class="mb-adlib-media">
                                            @if ($thumbUrl)
                                                <img src="{{ $thumbUrl }}" alt="{{ $ad['advertiser_name'] }}" loading="lazy" onerror="this.style.display='none';this.parentElement.classList.add('is-fallback');">
                                            @endif
                                            <span class="mb-adlib-fallback{{ $thumbUrl ? '' : ' is-active' }}"><i class="bi bi-meta"></i></span>
                                            @if ($snapshotIsHttp)
                                                <a href="{{ $snapshotUrl }}" target="_blank" rel="noopener noreferrer" onclick="event.stopPropagation();" class="mb-pick-preview-link" title="Open full ad on Meta Ad Library">
                                                    <i class="bi bi-box-arrow-up-right"></i> Ad
                                                </a>
                                            @endif
                                        </div>

                                        @if (filled($linkCaption))
                                            <div class="mb-adlib-domain">{{ $linkCaption }}</div>
                                        @endif
                                        @if (filled($linkTitle))
                                            <div class="mb-adlib-headline">{{ $linkTitle }}</div>
                                        @endif
                                    </article>
                                @endforeach
                            </div>
                        @elseif ($competitorSearched)
                            <p class="small text-muted mt-2 mb-0" wire:loading.remove wire:target="searchCompetitorAds">No ads found</p>
                        @endif
                    </div>

                {{-- Step: Details — remix an existing creative --}}
                @elseif ($step === 'clone_select')
                    <div class="mb-step-head">
                        <span class="mb-eyebrow"><i class="bi bi-stars"></i>Step {{ $currentIndex + 1 }} of {{ count($order) - 1 }}</span>
                        <h2 class="mb-step-title">Pick a creative to remix</h2>
                        <p class="mb-step-sub">We keep the subject and rebuild the layout, copy and format.</p>
                    </div>
                    <div class="mb-field-card">
                        <div class="mb-pick">
                            @forelse ($this->cloneCandidates as $candidate)
                                @php
                                    $mediaUrl = $candidate->asset ? route('assets.preview', $candidate->asset) : ($candidate->asset_path ? asset('storage/'.$candidate->asset_path) : null);
                                    $posterUrl = $candidate->thumbnail_path ? asset('storage/'.$candidate->thumbnail_path) : null;
                                @endphp
                                <button type="button" class="mb-pick-card {{ $cloneFromId === $candidate->id ? 'is-selected' : '' }}" wire:click="selectCloneFrom({{ $candidate->id }})">
                                    <span class="mb-pick-media d-block">
                                        @if ($candidate->type === 'video')
                                            @if ($mediaUrl)
                                                <video src="{{ $mediaUrl }}" @if ($posterUrl) poster="{{ $posterUrl }}" @endif muted loop playsinline preload="metadata" onmouseenter="this.play()" onmouseleave="this.pause();this.currentTime=0;" onerror="this.style.display='none';this.parentElement.classList.add('is-fallback');"></video>
                                                <span class="mb-pick-play-icon"><i class="bi bi-play-fill"></i></span>
                                                <span class="mb-pick-video-badge"><i class="bi bi-camera-reels"></i>{{ $candidate->duration ? $candidate->duration.'s' : 'Video' }}</span>
                                            @elseif ($posterUrl)
                                                <img src="{{ $posterUrl }}" alt="" loading="lazy" onerror="this.style.display='none';this.parentElement.classList.add('is-fallback');">
                                                <span class="mb-pick-video-badge"><i class="bi bi-camera-reels"></i>Video</span>
                                            @else
                                                <span class="mb-pick-fallback is-active"><i class="bi bi-camera-reels"></i></span>
                                            @endif
                                            <span class="mb-pick-fallback"><i class="bi bi-camera-reels"></i></span>
                                        @else
                                            @if ($mediaUrl)
                                                <img src="{{ $mediaUrl }}" alt="" loading="lazy" onerror="this.style.display='none';this.parentElement.classList.add('is-fallback');">
                                            @elseif ($posterUrl)
                                                <img src="{{ $posterUrl }}" alt="" loading="lazy" onerror="this.style.display='none';this.parentElement.classList.add('is-fallback');">
                                            @else
                                                <span class="mb-pick-fallback is-active"><i class="bi bi-image"></i></span>
                                            @endif
                                            <span class="mb-pick-fallback"><i class="bi bi-image"></i></span>
                                        @endif
                                    </span>
                                    <span class="mb-pick-name d-block">#{{ $candidate->id }} — {{ $candidate->title ?? $candidate->prompt ?? $candidate->product_url ?? $candidate->ratio }}</span>
                                    <span class="mb-pick-tick"><i class="bi bi-check-lg"></i></span>
                                </button>
                            @empty
                                <p class="text-muted small mb-0">You don't have any completed creatives to clone yet. Choose another starting point instead.</p>
                            @endforelse
                        </div>
                    </div>

                {{-- Step: Details — url / prompt / upload --}}
                @elseif ($step === 'input')
                    <div class="mb-step-head">
                        <span class="mb-eyebrow"><i class="bi bi-stars"></i>Step {{ $currentIndex + 1 }} of {{ count($order) - 1 }}</span>
                        @if ($source === 'product_url')
                            <h2 class="mb-step-title">Where does the product live?</h2>
                            <p class="mb-step-sub">Paste a product or landing page URL and we will read it for copy and imagery.</p>
                        @elseif ($source === 'upload')
                            <h2 class="mb-step-title">Upload your product images</h2>
                            <p class="mb-step-sub">JPG or PNG, up to 5 files. We use them as the base for the creative.</p>
                        @else
                            <h2 class="mb-step-title">Describe the ad you want</h2>
                            <p class="mb-step-sub">The more specific the scene, mood and message, the closer the first draft lands.</p>
                        @endif
                    </div>
                    <div class="mb-field-card">
                        @if ($source === 'product_url')
                            <label class="mb-label" for="mb-url">Product or landing page URL</label>
                            <input class="mb-input @error('rawInput') is-invalid @enderror" id="mb-url" type="url" wire:model="rawInput" placeholder="https://example.com/product" autofocus>
                            @error('rawInput')
                                <div class="mb-error is-on">{{ $message }}</div>
                            @enderror
                            <p class="mb-hint">The page needs to be publicly reachable — pages behind a login cannot be read.</p>
                        @elseif ($source === 'upload')
                            <div
                                x-data="{
                                    uploadError: null,
                                    sanitizeFiles(files) {
                                        if (!files || !files.length) return null;
                                        this.uploadError = null;
                                        const dt = new DataTransfer();
                                        Array.from(files).forEach((file, idx) => {
                                            let ext = '';
                                            if (file.name && file.name.includes('.')) {
                                                ext = file.name.split('.').pop().toLowerCase().replace(/[^a-z0-9]/g, '');
                                            }
                                            if (!ext || ext.length > 5) {
                                                const typeExt = file.type ? file.type.split('/').pop().toLowerCase().replace('jpeg', 'jpg') : '';
                                                ext = typeExt || 'jpg';
                                            }
                                            if (!['jpg', 'jpeg', 'png', 'webp', 'gif', 'avif'].includes(ext)) {
                                                ext = 'jpg';
                                            }
                                            const baseName = (file.name || 'image')
                                                .replace(/\.[^/.]+$/, '')
                                                .replace(/[^a-zA-Z0-9]/g, '-')
                                                .replace(/-+/g, '-')
                                                .replace(/^-|-$/g, '')
                                                .substring(0, 45) || ('image-' + (idx + 1));
                                            const safeName = baseName + '.' + ext;
                                            const mimeType = file.type || (ext === 'avif' ? 'image/avif' : ('image/' + (ext === 'jpg' ? 'jpeg' : ext)));
                                            dt.items.add(new File([file], safeName, { type: mimeType }));
                                        });
                                        return dt.files;
                                    },
                                    handleDrop(e) {
                                        const cleanFiles = this.sanitizeFiles(e.dataTransfer.files);
                                        if (cleanFiles) {
                                            const input = document.getElementById('mb-files');
                                            input.files = cleanFiles;
                                            input.dispatchEvent(new Event('change', { bubbles: true }));
                                        }
                                    }
                                }"
                                x-on:livewire-upload-start="uploadError = null"
                                x-on:livewire-upload-finish="uploadError = null"
                                x-on:livewire-upload-error="uploadError = 'Upload failed: please ensure your image is a valid JPG, PNG, WebP, or AVIF file under 10MB.'">
                                <label class="mb-drop" for="mb-files"
                                    x-on:dragover.prevent="$el.classList.add('is-over')"
                                    x-on:dragleave.prevent="$el.classList.remove('is-over')"
                                    x-on:drop.prevent="$el.classList.remove('is-over'); handleDrop($event)">
                                    <i class="bi bi-cloud-arrow-up"></i>
                                    <span class="mb-drop-title">Click to browse or drag and drop images</span>
                                    <span class="mb-cell-meta">JPG, PNG, WebP, AVIF · up to 5 files (max 10MB each)</span>
                                    <input type="file" id="mb-files" accept="image/jpeg,image/png,image/webp,image/gif,image/avif,image/*" multiple hidden
                                        x-on:change="
                                            if (!$el.dataset.sanitized) {
                                                $event.stopImmediatePropagation();
                                                const clean = sanitizeFiles($el.files);
                                                if (clean) {
                                                    $el.dataset.sanitized = 'true';
                                                    $el.files = clean;
                                                    $el.dispatchEvent(new Event('change', { bubbles: true }));
                                                    setTimeout(() => delete $el.dataset.sanitized, 100);
                                                }
                                            }
                                        "
                                        wire:model="uploadedImages">
                                </label>
                                <div wire:loading wire:target="uploadedImages" class="small text-muted mt-2">Uploading&hellip;</div>
                                <div x-show="uploadError" class="mb-error is-on mt-2" x-text="uploadError" style="display:none"></div>
                                @if (count($uploadedImages))
                                    <div class="mb-thumbs">
                                        @foreach ($uploadedImages as $image)
                                            @php
                                                $previewUrl = null;
                                                try {
                                                    if (is_object($image) && method_exists($image, 'isPreviewable') && $image->isPreviewable()) {
                                                        $previewUrl = $image->temporaryUrl();
                                                    }
                                                } catch (\Throwable $e) {
                                                    $previewUrl = null;
                                                }
                                            @endphp
                                            @if ($previewUrl)
                                                <div class="mb-thumb-item"><img src="{{ $previewUrl }}" alt="Upload preview"></div>
                                            @else
                                                <div class="mb-thumb-item mb-thumb-fallback" title="{{ is_object($image) && method_exists($image, 'getClientOriginalName') ? $image->getClientOriginalName() : 'Uploaded file' }}">
                                                    <i class="bi bi-file-earmark-image"></i>
                                                    <span class="small">{{ is_object($image) && method_exists($image, 'getClientOriginalName') ? \Illuminate\Support\Str::limit($image->getClientOriginalName(), 15) : 'Image' }}</span>
                                                </div>
                                            @endif
                                        @endforeach
                                    </div>
                                @endif
                                @if ($errors->has('uploadedImages'))
                                    <div class="mb-error is-on mt-2">{{ $errors->first('uploadedImages') }}</div>
                                @endif
                                @foreach ($errors->get('uploadedImages.*') as $messages)
                                    @foreach ($messages as $msg)
                                        <div class="mb-error is-on mt-2">{{ $msg }}</div>
                                    @endforeach
                                @endforeach
                            </div>
                        @else
                            <label class="mb-label" for="mb-prompt">Prompt</label>
                            <textarea class="mb-textarea @error('rawInput') is-invalid @enderror" id="mb-prompt" wire:model="rawInput" placeholder="e.g. A clean, premium ad for our ad-free browser — dark UI on a desk at night, bold headline, single accent colour." autofocus></textarea>
                            @error('rawInput')
                                <div class="mb-error is-on">{{ $message }}</div>
                            @enderror
                            <div class="mb-chips">
                                <button type="button" class="mb-chip" wire:click="$set('rawInput', 'Clean studio shot on a seamless backdrop, soft shadow, bold headline top-left.')">Studio shot</button>
                                <button type="button" class="mb-chip" wire:click="$set('rawInput', 'Lifestyle scene, golden hour, real people using the product, warm tones.')">Lifestyle</button>
                                <button type="button" class="mb-chip" wire:click="$set('rawInput', 'Bold sale banner, high contrast, big discount number, clear call to action.')">Sale banner</button>
                                <button type="button" class="mb-chip" wire:click="$set('rawInput', 'Minimal editorial layout, generous white space, single accent colour.')">Minimal</button>
                            </div>
                        @endif
                    </div>

                {{-- Step: Format — ratio, duration (video) and variations, all in one screen --}}
                @elseif ($step === 'ratio')
                    <div class="mb-step-head">
                        <span class="mb-eyebrow"><i class="bi bi-stars"></i>Step {{ $currentIndex + 1 }} of {{ count($order) - 1 }}</span>
                        <h2 class="mb-step-title">Format and variations</h2>
                        <p class="mb-step-sub">Choose the aspect ratio{{ $type === 'video' ? ', duration' : '' }} and how many versions to generate.</p>
                    </div>
                    <div class="mb-field-card" x-data="{ showCustomRatio: {{ \App\Livewire\Creatives\ChatWizard::isCustomRatio($ratio) ? 'true' : 'false' }} }">
                        <div class="d-flex align-items-center justify-content-between flex-wrap gap-2">
                            <label class="mb-label mb-0">Aspect ratio</label>
                            @if ($type === 'image')
                                <button type="button" class="mb-chip {{ $selectedRatios === \App\Livewire\Creatives\ChatWizard::ALL_IMAGE_RATIOS ? 'is-on' : '' }}" wire:click="selectAllSizes">
                                    <i class="bi bi-grid-3x3-gap"></i>Select all sizes
                                </button>
                            @endif
                        </div>
                        <div class="mb-ratios">
                            @foreach (($type === 'video' ? $videoRatios : $ratios) as $option)
                                @php
                                    $isSelected = $type === 'image' && ($quantity ?? 1) > 1
                                        ? in_array($option, $selectedRatios, true)
                                        : $ratio === $option;
                                @endphp
                                <button type="button" class="mb-ratio {{ $isSelected ? 'is-selected' : '' }}" wire:click="selectRatio('{{ $option }}'); showCustomRatio = false" @click="showCustomRatio = false">
                                    <span class="mb-ratio-box" style="width: {{ match($option) { '1:1' => 34, '4:5' => 28, '4:3' => 36, '9:16' => 20, '16:9', '1.91:1' => 40, default => 30 } }}px; height: {{ match($option) { '1:1' => 34, '4:5' => 35, '4:3' => 27, '9:16' => 36, '16:9' => 23, '1.91:1' => 21, default => 30 } }}px"></span>
                                    <span class="mb-ratio-name">{{ $option }}</span>
                                    @if ($type === 'image')
                                        <span class="mb-ratio-dimensions">{{ match($option) {
                                            '1:1' => '1200×1200',
                                            '4:5' => '960×1200',
                                            '9:16' => '900×1600',
                                            '16:9' => '1600×900',
                                            '1.91:1' => '1200×628',
                                            default => '',
                                        } }}</span>
                                    @endif
                                    <span class="mb-ratio-use">{{ match($option) {
                                        '1:1' => 'Feed',
                                        '4:5' => 'Portrait',
                                        '4:3' => 'Classic',
                                        '9:16' => 'Story',
                                        '16:9' => 'Display',
                                        '1.91:1' => 'Google Ads',
                                        default => '',
                                    } }}</span>
                                </button>
                            @endforeach
                            @if ($type !== 'video')
                                <button type="button" class="mb-ratio {{ \App\Livewire\Creatives\ChatWizard::isCustomRatio($ratio) ? 'is-selected' : '' }}" @click="showCustomRatio = true">
                                    <span class="mb-ratio-box" style="width: 30px; height: 30px; border-style: dashed;"></span>
                                    <span class="mb-ratio-name">Custom</span>
                                    <span class="mb-ratio-use">{{ \App\Livewire\Creatives\ChatWizard::isCustomRatio($ratio) ? $ratio.'px' : 'Pixels' }}</span>
                                </button>
                            @endif
                        </div>
                        @if ($type === 'image' && ($quantity ?? 1) > 1)
                            <p class="mb-cell-meta mt-1">Selected {{ count($selectedRatios) }}/{{ $quantity }} — pick up to {{ $quantity }} sizes, one variation is rendered per size.</p>
                        @endif
                        @if ($type !== 'video')
                            <div class="mt-2" x-show="showCustomRatio" x-cloak>
                                <div class="d-flex align-items-end gap-2 flex-wrap">
                                    <div>
                                        <label class="mb-label" for="mb-custom-ratio-w">Width (px)</label>
                                        <input type="number" id="mb-custom-ratio-w" min="1" max="8000" placeholder="1080" wire:model="customRatioWidth" class="mb-input @error('customRatioWidth') is-invalid @enderror" style="width: 7rem;">
                                    </div>
                                    <div>
                                        <label class="mb-label" for="mb-custom-ratio-h">Height (px)</label>
                                        <input type="number" id="mb-custom-ratio-h" min="1" max="8000" placeholder="1080" wire:model="customRatioHeight" class="mb-input @error('customRatioHeight') is-invalid @enderror" style="width: 7rem;">
                                    </div>
                                    <button type="button" class="mb-btn-primary" wire:click="submitCustomRatio">Use</button>
                                </div>
                                <p class="mb-cell-meta mt-1">Enter pixel dimensions (e.g. 1080 × 1080, 1200 × 628) or aspect ratio (e.g. 16 × 9). Small ratios are auto-scaled to high-res.</p>
                                @error('customRatioWidth')
                                    <div class="mb-error is-on">{{ $message }}</div>
                                @enderror
                                @error('customRatioHeight')
                                    <div class="mb-error is-on">{{ $message }}</div>
                                @enderror
                            </div>
                        @endif
                        @error('ratio')
                            <div class="mb-error is-on">{{ $message }}</div>
                        @enderror

                        @if ($type === 'video')
                            <div class="mb-format-grid mt-3">
                                <div>
                                    <label class="mb-label">Duration</label>
                                    <div class="mb-segment">
                                        @foreach ($durationPresets as $preset)
                                            <button type="button" class="{{ $duration === $preset ? 'is-selected' : '' }}" wire:click="selectDuration({{ $preset }})">{{ $preset }}s</button>
                                        @endforeach
                                    </div>
                                    @error('duration')
                                        <div class="mb-error is-on">{{ $message }}</div>
                                    @enderror
                                </div>
                                <div>
                                    <label class="mb-label">Variations</label>
                                    <div class="mb-segment">
                                        @foreach ($videoQuantityPresets as $preset)
                                            <button type="button" class="{{ $quantity === $preset ? 'is-selected' : '' }}" wire:click="selectQuantity({{ $preset }})">{{ $preset }}</button>
                                        @endforeach
                                    </div>
                                    @error('quantity')
                                        <div class="mb-error is-on">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        @else
                            <div class="mb-format-grid mt-3">
                                <div>
                                    <label class="mb-label">Variations</label>
                                    <div class="mb-segment">
                                        @foreach ($quantityPresets as $preset)
                                            <button type="button" class="{{ $quantity === $preset ? 'is-selected' : '' }}" wire:click="selectQuantity({{ $preset }})">{{ $preset }}</button>
                                        @endforeach
                                    </div>
                                    @error('quantity')
                                        <div class="mb-error is-on">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        @endif

                        <div class="mt-3">
                            <label class="mb-label" for="mb-format-notes">Notes <span class="text-muted fw-normal">(optional)</span></label>
                            <textarea class="mb-textarea @error('formatNotes') is-invalid @enderror" id="mb-format-notes"  wire:model="formatNotes" placeholder="Adding notes helps us tailor the result to what you actually want, e.g. tone of voice, colours to keep, call to action, or things to avoid. Example: &quot;Keep it upbeat and playful, use our teal/orange palette, end with 'Shop the sale', avoid stock-photo people.&quot;"></textarea>
                            @error('formatNotes')
                                <div class="mb-error is-on">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>

                {{-- Step: Style --}}
                @elseif ($step === 'style')
                    @php
                        $activeSizeId = $styleSizeFilter === 'all' ? '1:1' : $styleSizeFilter;
                        $activeSize = collect($styleSizeOptions)->firstWhere('id', $activeSizeId);
                        $galleryAspect = $activeSize['w'].' / '.$activeSize['h'];
                        $imgUrl = fn (string $dir) => asset('assets/mb/img/ad-style/'.$dir.'/'.$activeSize['file'].'.jpg');
                        $visibleStyleCatalogue = collect($styleCatalogue)
                            ->filter(fn (array $card) => $type === 'video' || ! ($card['video_only'] ?? false));
                    @endphp
                    <div class="mb-step-head">
                        <span class="mb-eyebrow"><i class="bi bi-stars"></i>Step {{ $currentIndex + 1 }} of {{ count($order) - 1 }}</span>
                        <h2 class="mb-step-title">Pick a look</h2>
                        <p class="mb-step-sub">
                            @if (($quantity ?? 1) > 1)
                                Pick up to {{ $quantity }} styles — one per variation (picking fewer repeats them across the batch).
                            @else
                                Browse example ads and pick the direction. Filter by placement to see how each style crops.
                            @endif
                        </p>
                    </div>
                    <div class="mb-style-bar">
                        <div class="mb-size-chips" role="group" aria-label="Filter by size">
                            <button type="button" class="mb-size-chip {{ $styleSizeFilter === 'all' ? 'is-on' : '' }}" wire:click="setStyleSizeFilter('all')">All sizes</button>
                            @foreach ($styleSizeOptions as $sz)
                                <button type="button" class="mb-size-chip {{ $styleSizeFilter === $sz['id'] ? 'is-on' : '' }}" wire:click="setStyleSizeFilter('{{ $sz['id'] }}')">
                                    <span class="mb-size-box" style="aspect-ratio: {{ $sz['w'] }} / {{ $sz['h'] }}"></span>{{ $sz['id'] }}<span class="mb-size-use">{{ $sz['use'] }}</span>
                                </button>
                            @endforeach
                        </div>
                        <span class="mb-style-count">{{ $visibleStyleCatalogue->count() + 1 }} styles</span>
                    </div>
                    <div x-data="{ zoomDir: null }">
                        <div class="mb-style-grid {{ $styleSizeFilter === 'all' ? '' : 'is-'.str_replace(':', '-', $styleSizeFilter) }}">
                            @php
                                // Multi-select mode (quantity > 1) tracks selection purely via $selectedStyles —
                                // falling back to $style === '' here would show Auto as selected (and undeletable/
                                // uncounted in the "Selected X/N" indicator) before the user has picked anything.
                                $autoSelected = ($quantity ?? 1) > 1 ? in_array('', $selectedStyles, true) : $style === '';
                            @endphp
                            <button type="button" class="mb-style-card mb-style-auto {{ $autoSelected ? 'is-selected' : '' }}" wire:click="selectAutoStyle">
                                <div class="mb-style-media" style="aspect-ratio: {{ $galleryAspect }}">
                                    <span class="mb-style-auto-inner">
                                        <i class="bi bi-stars"></i>
                                        <span class="mb-style-auto-title">Auto</span>
                                        <span class="mb-style-auto-sub">We pick the look that fits your brief</span>
                                    </span>
                                </div>
                                <span class="mb-style-tick"><i class="bi bi-check-lg"></i></span>
                            </button>
                            @foreach ($visibleStyleCatalogue as $card)
                                <div class="mb-style-card {{ in_array($card['name'], $selectedStyles, true) ? 'is-selected' : '' }}" role="button" tabindex="0" wire:click="selectStyle('{{ $card['name'] }}')">
                                    <div class="mb-style-media" style="aspect-ratio: {{ $galleryAspect }}">
                                        <img src="{{ $imgUrl($card['dir']) }}" alt="{{ $card['name'] }} example ad" decoding="async">
                                        <span class="mb-style-scrim"></span>
                                        <span class="mb-style-tag">{{ $card['tag'] }}</span>
                                        <span class="mb-style-name">{{ $card['label'] ?? $card['name'] }}</span>
                                    </div>
                                    <span class="mb-style-tick"><i class="bi bi-check-lg"></i></span>
                                    <button type="button" class="mb-style-zoom" @click.stop="zoomDir = '{{ $card['dir'] }}'" aria-label="Preview {{ $card['name'] }} in all sizes"><i class="bi bi-arrows-angle-expand"></i></button>
                                </div>
                            @endforeach
                        </div>

                        @foreach ($visibleStyleCatalogue as $card)
                            <div class="mb-style-preview" x-show="zoomDir === '{{ $card['dir'] }}'" x-cloak @click.self="zoomDir = null" style="display:none">
                                <div class="mb-style-sheet" role="dialog" aria-modal="true" aria-label="{{ $card['name'] }}">
                                    <div class="mb-style-sheet-head">
                                        <div><h3>{{ $card['name'] }}</h3><p>{{ $card['desc'] }}</p></div>
                                        <button type="button" class="mb-icon-btn" @click="zoomDir = null" aria-label="Close"><i class="bi bi-x-lg"></i></button>
                                    </div>
                                    <div class="mb-style-sizes">
                                        @foreach ($styleSizeOptions as $sz)
                                            <figure class="mb-style-size">
                                                <div class="mb-style-size-media" style="aspect-ratio: {{ $sz['w'] }} / {{ $sz['h'] }}">
                                                    <img src="{{ asset('assets/mb/img/ad-style/'.$card['dir'].'/'.$sz['file'].'.jpg') }}" alt="{{ $card['name'] }} at {{ $sz['id'] }}">
                                                </div>
                                                <figcaption>{{ $sz['id'] }}<span>{{ $sz['use'] }}</span></figcaption>
                                            </figure>
                                        @endforeach
                                    </div>
                                    <div class="mb-style-sheet-foot">
                                        <button type="button" class="mb-btn-ghost" @click="zoomDir = null">Close</button>
                                        <button type="button" class="mb-btn-primary" wire:click="selectStyle('{{ $card['name'] }}')" @click="zoomDir = null"><i class="bi bi-check-lg"></i>Use this style</button>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                    @error('style')
                        <div class="mb-error is-on">{{ $message }}</div>
                    @enderror

                {{-- Step: Script (video only) --}}
                @elseif ($step === 'script')
                    <div class="mb-step-head">
                        <span class="mb-eyebrow"><i class="bi bi-stars"></i>Step {{ $currentIndex + 1 }} of {{ count($order) - 1 }}</span>
                        <h2 class="mb-step-title">Let's write your script</h2>
                        <p class="mb-step-sub">
                            @if ($quantity > 1)
                                Generate a few variations and pick up to {{ $quantity }} — one per video (picking fewer repeats them across the batch).
                            @else
                                Generate a few variations and pick your favorite.
                            @endif
                        </p>
                    </div>
                    <div class="mb-field-card" @if (empty($scriptVariations) && ! $errors->has('scriptVariations')) wire:init="generateScripts" @endif>
                        @error('scriptVariations')
                            <div class="mb-error is-on">{{ $message }}</div>
                            <button type="button" class="mb-btn-ghost" wire:click="generateScripts">Try generating scripts again</button>
                        @enderror
                        @if (empty($scriptVariations) && ! $errors->has('scriptVariations'))
                            <div class="d-flex align-items-center gap-2 text-muted py-3">
                                <span class="spinner-border spinner-border-sm"></span>
                                <span>Doing some magic, generating the perfect script for your {{ $type }} ad campaign&hellip;</span>
                            </div>
                        @elseif (! empty($scriptVariations))
                            <div class="d-flex justify-content-end mb-2">
                                <button type="button" class="mb-btn-ghost" wire:click="generateScripts" wire:loading.attr="disabled" wire:target="generateScripts">
                                    <span wire:loading.remove wire:target="generateScripts"><i class="bi bi-arrow-repeat"></i> Regenerate scripts</span>
                                    <span wire:loading wire:target="generateScripts"><span class="spinner-border spinner-border-sm me-1"></span> Writing scripts&hellip;</span>
                                </button>
                            </div>
                            <div class="mb-options mb-options-script">
                                @foreach ($scriptVariations as $index => $variation)
                                    <button type="button" class="mb-option mb-option-script {{ in_array($index, $selectedScriptIndices, true) ? 'is-selected' : '' }}" wire:click="toggleScript({{ $index }})">
                                        <span class="mb-script-body">
                                            <span class="mb-option-title">Variation {{ $index + 1 }}</span>
                                            <span class="mb-script-line"><strong>Hook:</strong> {{ $variation['hook'] }}</span>
                                            <span class="mb-script-line"><strong>Problem:</strong> {{ $variation['problem'] }}</span>
                                            <span class="mb-script-line"><strong>Product:</strong> {{ $variation['product'] }}</span>
                                            <span class="mb-script-line"><strong>Benefits:</strong> {{ $variation['benefits'] }}</span>
                                            <span class="mb-script-line"><strong>CTA:</strong> {{ $variation['cta'] }}</span>
                                        </span>
                                        <span class="mb-option-check"><i class="bi bi-check-lg"></i></span>
                                    </button>
                                @endforeach
                            </div>
                        @endif
                    </div>

                {{-- Step: Avatar & Voice (video only) --}}
                @elseif ($step === 'avatar')
                    <div class="mb-step-head">
                        <span class="mb-eyebrow"><i class="bi bi-stars"></i>Step {{ $currentIndex + 1 }} of {{ count($order) - 1 }}</span>
                        <h2 class="mb-step-title">Choose an avatar and voice</h2>
                        <p class="mb-step-sub">{{ $videoEngine === 'higgsfield-seedance' ? 'Choose a presenter and voice style for the script. '.$this->higgsfieldModelLabel().' generates the video from the script and does not use the presenter photo.' : 'Choose a Gemini-generated presenter and Gemini voice style. Veo may not reproduce the avatar photo exactly.' }}</p>
                    </div>
                    <div class="mb-field-card">
                        <label class="mb-label">Avatar</label>
                        <div class="mb-options">
                            @forelse ($this->avatars as $avatar)
                                @php
                                    $initials = collect(explode(' ', $avatar->name))->map(fn ($part) => mb_substr($part, 0, 1))->join('');
                                    $palette = ['#6366f1', '#0ea5e9', '#f59e0b', '#ef4444', '#10b981', '#8b5cf6'];
                                    $avatarColor = $palette[$avatar->id % count($palette)];
                                @endphp
                                <button type="button" class="mb-option mb-option-avatar {{ $avatarId === $avatar->id ? 'is-selected' : '' }}" wire:click="selectAvatar({{ $avatar->id }})" wire:loading.attr="disabled" wire:target="selectAvatar">
                                    @if ($avatar->source_path)
                                        <img class="mb-avatar-thumb" src="{{ asset($avatar->source_path) }}" alt="{{ $avatar->name }}">
                                    @else
                                        <span class="mb-avatar-thumb" style="background: {{ $avatarColor }};">{{ $initials }}</span>
                                    @endif
                                    <span><span class="mb-option-title">{{ $avatar->name }}</span>
                                    <span class="mb-option-desc d-block">{{ $avatar->gender }}, {{ $avatar->accent }}</span></span>
                                    <span class="mb-option-check"><i class="bi bi-check-lg"></i></span>
                                </button>
                            @empty
                                <p class="text-muted small">No avatars available yet.</p>
                            @endforelse
                        </div>
                    </div>

                    <div wire:loading wire:target="selectAvatar" class="mb-field-card mt-3">
                        <label class="mb-label">Voice</label>
                        <p class="small text-muted mb-0">
                            <span class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
                            Loading voices&hellip;
                        </p>
                    </div>

                    @if ($avatarId)
                        <div class="mb-field-card mt-3" id="mb-voice-section" wire:loading.remove wire:target="selectAvatar" x-data x-on:avatar-selected.window="$nextTick(() => $el.scrollIntoView({ behavior: 'smooth', block: 'start' }))">
                            <label class="mb-label">Voice</label>
                            <p class="mb-step-sub">{{ $videoEngine === 'higgsfield-seedance' ? 'Preview plays a Gemini-generated sample of the selected voice. '.$this->higgsfieldModelLabel().' generates the final video speech separately, so its sound may differ.' : 'Preview plays a Gemini-generated sample of the selected voice. Veo generates the final video speech separately, so its sound may differ.' }}</p>
                            <div class="d-flex flex-column gap-2">
                                @forelse ($this->voices as $voice)
                                    <div class="d-flex align-items-center gap-2 {{ $voiceId === $voice->id ? 'is-selected' : '' }}">
                                        <button type="button" class="mb-btn-ghost" wire:click="previewVoice({{ $voice->id }})" wire:loading.attr="disabled" wire:target="previewVoice({{ $voice->id }})">Preview</button>
                                        <span class="small">{{ $voice->name }} <span class="text-muted">({{ $voice->gender }}, {{ $voice->accent }}, {{ $voice->tone }})</span></span>
                                        @if (isset($voicePreviewPaths[$voice->id]))
                                            <audio controls src="{{ asset('storage/'.$voicePreviewPaths[$voice->id]) }}" style="height: 32px;"></audio>
                                        @endif
                                        <button type="button" class="mb-btn-primary ms-auto" wire:click="selectVoice({{ $voice->id }})">Choose</button>
                                    </div>
                                @empty
                                    <p class="text-muted small mb-0">No voices available for this avatar's gender yet.</p>
                                @endforelse
                                @error('voicePreview')
                                    <div class="mb-error is-on">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                    @endif

                {{-- Step: Storyboard (video only) --}}
                @elseif ($step === 'storyboard')
                    <div class="mb-step-head">
                        <span class="mb-eyebrow"><i class="bi bi-stars"></i>Step {{ $currentIndex + 1 }} of {{ count($order) - 1 }}</span>
                        <h2 class="mb-step-title">Review your storyboard</h2>
                        <p class="mb-step-sub">Edit any scene before we render. Each variation below renders independently with its own script.</p>
                    </div>
                    @foreach ($storyboards as $variationIndex => $scenes)
                        <div class="mb-field-card {{ !$loop->first ? 'mt-3' : '' }}">
                            @if (count($storyboards) > 1)
                                <label class="mb-label">Variation {{ $variationIndex + 1 }}</label>
                            @endif
                            <div class="d-flex flex-column gap-2">
                                @foreach ($scenes as $sceneIndex => $scene)
                                    <textarea rows="2" class="mb-textarea mb-textarea-sm" wire:blur="updateStoryboardScene({{ $variationIndex }}, {{ $sceneIndex }}, $event.target.value)">{{ $scene['scene'] }}</textarea>
                                @endforeach
                            </div>
                        </div>
                    @endforeach

                {{-- Step: Format — variations --}}
                @elseif ($step === 'quantity')
                    <div class="mb-step-head">
                        <span class="mb-eyebrow"><i class="bi bi-stars"></i>Step {{ $currentIndex + 1 }} of {{ count($order) - 1 }}</span>
                        <h2 class="mb-step-title">How many creatives would you like?</h2>
                        <p class="mb-step-sub">Each variation costs 1 credit.</p>
                    </div>
                    <div class="mb-field-card">
                        <div class="mb-format-grid">
                            <div>
                                <label class="mb-label">Variations</label>
                                <div class="mb-segment">
                                    @foreach (($type === 'video' ? $videoQuantityPresets : $quantityPresets) as $preset)
                                        <button type="button" class="{{ $quantity === $preset ? 'is-selected' : '' }}" wire:click="selectQuantity({{ $preset }})">{{ $preset }}</button>
                                    @endforeach
                                </div>
                            </div>
                            <div>
                                <label class="mb-label" for="mb-custom-qty">Custom</label>
                                <div class="d-flex gap-2">
                                    <input type="number" id="mb-custom-qty" min="1" max="{{ $type === 'video' ? 3 : 20 }}" wire:model="customQuantity" class="mb-input @error('customQuantity') is-invalid @enderror" style="width: 6rem;">
                                    <button type="button" class="mb-btn-primary" wire:click="submitCustomQuantity">Use</button>
                                </div>
                                @error('customQuantity')
                                    <div class="mb-error is-on">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                    </div>

                {{-- Step: Review --}}
                @elseif ($step === 'summary')
                    <div class="mb-step-head">
                        <span class="mb-eyebrow"><i class="bi bi-stars"></i>Step {{ $currentIndex + 1 }} of {{ count($order) - 1 }}</span>
                        <h2 class="mb-step-title">Ready to generate</h2>
                        <p class="mb-step-sub">Check the brief — you can jump back to any step.</p>
                    </div>
                    <div class="mb-review">
                        <div class="mb-review-row">
                            <div class="mb-review-key">Type</div>
                            <div class="mb-review-val">{{ ucfirst($type) }}</div>
                            <button type="button" class="mb-review-edit" wire:click="goToStep('type')">Edit</button>
                        </div>
                        <div class="mb-review-row">
                            <div class="mb-review-key">Starting point</div>
                            <div class="mb-review-val">{{ match($source) {
                                'product_url' => 'Product URL',
                                'upload' => 'Uploaded images',
                                'existing' => 'Clone / variation',
                                default => 'Text prompt',
                            } }}</div>
                            <button type="button" class="mb-review-edit" wire:click="goToStep('source')">Edit</button>
                        </div>
                        <div class="mb-review-row">
                            <div class="mb-review-key">Details</div>
                            <div class="mb-review-val">
                                @if ($source === 'product_url') {{ $rawInput }}
                                @elseif ($source === 'upload') {{ count($uploadedImagePaths) }} image(s)
                                @elseif ($source === 'existing') Creative #{{ $cloneFromId }}
                                @elseif ($source === 'competitor') Competitor ad ({{ $competitorQuery }})
                                @else {{ $rawInput }}
                                @endif
                            </div>
                            <button type="button" class="mb-review-edit" wire:click="goToStep('{{ $source === 'existing' ? 'clone_select' : ($source === 'competitor' ? 'competitor_search' : 'input') }}')">Edit</button>
                        </div>
                        <div class="mb-review-row">
                            <div class="mb-review-key">Format</div>
                            <div class="mb-review-val">{{ $ratio }}</div>
                            <button type="button" class="mb-review-edit" wire:click="goToStep('ratio')">Edit</button>
                        </div>
                        @if ($handlingLabel = \App\DTOs\CreativeBrief::handlingLabel($brief['handling'] ?? null))
                            <div class="mb-review-row">
                                <div class="mb-review-key">Handling</div>
                                <div class="mb-review-val">{{ $handlingLabel }}</div>
                            </div>
                        @endif
                        @if ($type === 'video')
                            <div class="mb-review-row">
                                <div class="mb-review-key">Video model</div>
                                <div class="mb-review-val">{{ $videoEngine === 'higgsfield-seedance' ? $this->higgsfieldModelLabel() : 'Veo' }}</div>
                            </div>
                            <div class="mb-review-row">
                                <div class="mb-review-key">Duration</div>
                                <div class="mb-review-val">{{ $duration }}s</div>
                                <button type="button" class="mb-review-edit" wire:click="goToStep('ratio')">Edit</button>
                            </div>
                        @endif
                        <div class="mb-review-row">
                            <div class="mb-review-key">Style</div>
                            <div class="mb-review-val">
                                {{ count($selectedStyles) > 1 ? collect($selectedStyles)->map(fn ($s) => $s ?: 'Auto')->implode(', ') : ($style ?: 'No preference') }}
                            </div>
                            <button type="button" class="mb-review-edit" wire:click="goToStep('style')">Edit</button>
                        </div>
                        @if ($type === 'video' && count($selectedScriptIndices) > 1)
                            <div class="mb-review-row">
                                <div class="mb-review-key">Scripts</div>
                                <div class="mb-review-val">{{ count($selectedScriptIndices) }} selected, cycled across {{ $quantity }} variations</div>
                                <button type="button" class="mb-review-edit" wire:click="goToStep('script')">Edit</button>
                            </div>
                        @endif
                        @if ($type === 'video')
                            <div class="mb-review-row">
                                <div class="mb-review-key">Avatar</div>
                                <div class="mb-review-val">{{ $this->avatars->firstWhere('id', $avatarId)?->name }}</div>
                                <button type="button" class="mb-review-edit" wire:click="goToStep('avatar')">Edit</button>
                            </div>
                            <div class="mb-review-row">
                                <div class="mb-review-key">Voice</div>
                                <div class="mb-review-val">{{ $this->voices->firstWhere('id', $voiceId)?->name }}</div>
                                <button type="button" class="mb-review-edit" wire:click="goToStep('avatar')">Edit</button>
                            </div>
                        @endif
                        <div class="mb-review-row">
                            <div class="mb-review-key">Variations</div>
                            <div class="mb-review-val">{{ $quantity }}</div>
                            <button type="button" class="mb-review-edit" wire:click="goToStep('ratio')">Edit</button>
                        </div>
                        <div class="mb-cost"><i class="bi bi-lightning-charge-fill"></i>Generation cost<strong>{{ $quantity }} {{ $quantity === 1 ? 'credit' : 'credits' }}</strong></div>
                    </div>

                {{-- Step: Done --}}
                @elseif ($step === 'done')
                    <div @if ($this->hasPendingResults()) wire:poll.3s="refreshResults" @endif>
                        @php
                            $completedCount = collect($results)->where('status', 'completed')->count();
                            $pendingCount = collect($results)->reject(fn (array $result) => in_array($result['status'], ['completed', 'failed'], true))->count();
                            $averageProgress = count($results) > 0
                                ? (int) round(collect($results)->avg(fn (array $result) => $result['status'] === 'completed' ? 100 : ($result['render_progress'] ?? 0)))
                                : 0;
                        @endphp
                        <div class="mb-step-head">
                            <span class="mb-eyebrow"><i class="bi {{ $pendingCount > 0 ? 'bi-camera-reels' : 'bi-stars' }}"></i>{{ $pendingCount > 0 ? 'Creating' : 'Done' }}</span>
                            <h2 class="mb-step-title">{{ $pendingCount > 0 ? 'Your creative is taking shape' : $completedCount.' of '.count($results).' creative(s) generated' }}</h2>
                            @if ($pendingCount > 0)
                                <p class="mb-step-sub">{{ $completedCount }} of {{ count($results) }} ready · {{ $type === 'video' ? 'Longer videos are built in multiple scenes.' : 'Generating your final artwork.' }}</p>
                            @endif
                        </div>
                        <div class="mb-render-grid">
                            @foreach ($results as $result)
                                <div class="mb-render-card {{ $result['status'] === 'completed' ? 'is-complete' : '' }} {{ $result['status'] === 'failed' ? 'is-failed' : '' }}">
                                    @if ($result['status'] === 'completed')
                                        @if ($type === 'video')
                                            <video src="{{ asset('storage/'.$result['asset_path']) }}" class="mb-render-media" controls></video>
                                        @else
                                            <img src="{{ asset('storage/'.$result['asset_path']) }}" class="mb-render-media" alt="Generated creative">
                                        @endif
                                        <div class="p-3 d-flex align-items-center justify-content-end border-top">
                                            <a href="{{ route('creatives.show', $result['id']) }}" class="mb-btn-primary mb-btn-sm" wire:navigate>
                                                <i class="bi bi-eye"></i>View Detail
                                            </a>
                                        </div>
                                    @elseif ($result['status'] === 'failed')
                                        <div class="mb-render-error"><i class="bi bi-exclamation-triangle"></i><div><strong>Generation stopped</strong><span>{{ $result['failure_reason'] ?? 'Generation failed.' }}</span></div></div>
                                        <div class="p-3 d-flex align-items-center justify-content-end border-top">
                                            <a href="{{ route('creatives.show', $result['id']) }}" class="mb-btn-secondary mb-btn-sm" wire:navigate>
                                                <i class="bi bi-eye"></i>View Detail
                                            </a>
                                        </div>
                                    @else
                                        @php
                                            $progress = min(99, max(0, (int) ($result['render_progress'] ?? 0)));
                                            $stage = $result['render_stage'] ?? ($type === 'video' ? 'Waiting for renderer' : 'Generating artwork');
                                        @endphp
                                        <div class="mb-render-preview" aria-hidden="true">
                                            <div class="mb-render-film">
                                                <span></span><span></span><span></span>
                                                <i class="bi {{ $type === 'video' ? 'bi-camera-reels-fill' : 'bi-image' }}"></i>
                                            </div>
                                            <div class="mb-render-format"><span>{{ $ratio }}</span>@if ($type === 'video')<span>{{ $duration }}s</span>@endif</div>
                                        </div>
                                        <div class="mb-render-body">
                                            <div class="mb-render-status">
                                                <span><i class="bi bi-stars"></i>{{ $stage }}</span>
                                                <strong>{{ $progress }}%</strong>
                                            </div>
                                            <h3>{{ $type === 'video' ? 'Rendering your video' : 'Designing your creative' }}</h3>
                                            <p>{{ $type === 'video' ? 'We are composing scenes, voice, and motion. You can leave this page and come back anytime.' : 'We are bringing your brief and selected style together.' }}</p>
                                            <div class="mb-render-progress" role="progressbar" aria-label="Estimated render progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ $progress }}">
                                                <span style="width: {{ $progress }}%"></span>
                                            </div>
                                            <div class="mb-render-progress-meta"><span>Estimated progress</span><span>Updates automatically</span></div>
                                            @if ($type === 'video')
                                                <div class="mb-render-milestones">
                                                    <span class="{{ $progress >= 5 ? 'is-done' : '' }}">Prepared</span>
                                                    <span class="{{ $progress >= 12 ? 'is-active' : '' }} {{ $progress >= 90 ? 'is-done' : '' }}">Rendering</span>
                                                    <span class="{{ $progress >= 90 ? 'is-active' : '' }}">Finalizing</span>
                                                </div>
                                            @endif
                                        </div>
                                    @endif
                                    <a href="{{ route('creatives.show', $result['id']) }}" class="mb-render-view" wire:navigate><i class="bi bi-eye"></i>View Detail</a>
                                </div>
                            @endforeach
                        </div>
                    </div>
                @endif

            </div>
        </div>

        <div class="mb-wizard-foot">
            @if ($step !== 'done' && $currentIndex > 0)
                <button type="button" class="mb-btn-ghost" wire:click="goBack" wire:loading.attr="disabled"><i class="bi bi-arrow-left"></i>Back</button>
                <span class="mb-spacer"></span>
            @elseif ($step !== 'done')
                <span class="mb-spacer"></span>
            @endif

            @if ($step === 'input')
                <button type="button" class="mb-btn-primary mb-btn-lg" wire:click="submitInput" wire:loading.attr="disabled" wire:target="submitInput">
                    Continue<i class="bi bi-arrow-right"></i>
                </button>
            @elseif ($step === 'ratio')
                <button type="button" class="mb-btn-primary mb-btn-lg" wire:click="submitFormat" wire:loading.attr="disabled" wire:target="submitFormat">
                    Continue<i class="bi bi-arrow-right"></i>
                </button>
            @elseif ($step === 'style')
                @if (($quantity ?? 1) > 1)
                    <span class="mb-cell-meta">Selected {{ count($selectedStyles) }} / {{ $quantity }} (max {{ $quantity }})</span>
                    <button type="button" class="mb-btn-primary mb-btn-lg" wire:click="confirmStyles" @disabled(empty($selectedStyles))>
                        Continue<i class="bi bi-arrow-right"></i>
                    </button>
                @else
                    <button type="button" class="mb-btn-primary mb-btn-lg" wire:click="submitStyle" wire:loading.attr="disabled" wire:target="submitStyle">
                        Continue<i class="bi bi-arrow-right"></i>
                    </button>
                @endif
            @elseif ($step === 'script')
                @if (count($scriptVariations))
                    <span class="mb-cell-meta">Selected {{ count($selectedScriptIndices) }} / {{ $quantity }} (max {{ $quantity }})</span>
                    <button type="button" class="mb-btn-primary mb-btn-lg" wire:click="confirmScripts" @disabled(empty($selectedScriptIndices))>
                        Continue<i class="bi bi-arrow-right"></i>
                    </button>
                @endif
            @elseif ($step === 'storyboard')
                <button type="button" class="mb-btn-primary mb-btn-lg" wire:click="confirmStoryboard" wire:loading.attr="disabled" wire:target="confirmStoryboard">
                    Looks good, continue<i class="bi bi-arrow-right"></i>
                </button>
            @elseif ($step === 'summary')
                <span class="mb-cell-meta d-none d-sm-inline">{{ $quantity }} {{ $quantity === 1 ? 'credit' : 'credits' }}</span>
                <button type="button" class="mb-btn-primary mb-btn-lg" wire:click="confirmGenerate" wire:loading.attr="disabled" wire:target="confirmGenerate">
                    <span wire:loading.remove wire:target="confirmGenerate"><i class="bi bi-stars"></i>Generate</span>
                    <span wire:loading wire:target="confirmGenerate"><span class="spinner-border spinner-border-sm me-1"></span> Generating&hellip;</span>
                </button>
            @elseif ($step === 'done')
                @if (count($results))
                    <a href="{{ route('creatives.show', $results[0]['id']) }}" class="mb-btn-secondary mb-btn-lg" wire:navigate>
                        <i class="bi bi-eye"></i>View Detail
                    </a>
                @endif
                <a href="{{ route('creatives.create') }}" class="mb-btn-primary mb-btn-lg" wire:navigate>Create Another</a>
            @endif
        </div>

    </div>
</div>


