@extends('layouts.nova.content-layout')

@php
    $hero_title = $mode === 'create' ? 'Write Story' : 'Edit Story';
    $hero_description = 'A focused writing studio with autosave, embeds, live preview, and a cleaner publish workflow.';
@endphp

@section('page-content')
@php
    $initialContent = $story->content;
    if (is_string($initialContent)) {
        $decodedContent = json_decode($initialContent, true);
        if (json_last_error() !== JSON_ERROR_NONE || ! is_array($decodedContent)) {
            $initialContent = [
                'type' => 'doc',
                'content' => [
                    ['type' => 'paragraph', 'content' => [['type' => 'text', 'text' => strip_tags($initialContent)]],],
                ],
            ];
        } else {
            $initialContent = $decodedContent;
        }
    }

    $storyPayload = [
        'id' => $story->id,
        'title' => old('title', (string) $story->title),
        'excerpt' => old('excerpt', (string) ($story->excerpt ?? '')),
        'cover_image' => old('cover_image', (string) ($story->cover_image ?? '')),
        'story_type' => old('story_type', (string) ($story->story_type ?? 'creator_story')),
        'tags_csv' => old('tags_csv', (string) ($story->tags?->pluck('name')->implode(', ') ?? '')),
        'meta_title' => old('meta_title', (string) ($story->meta_title ?? $story->title ?? '')),
        'meta_description' => old('meta_description', (string) ($story->meta_description ?? $story->excerpt ?? '')),
        'canonical_url' => old('canonical_url', (string) ($story->canonical_url ?? '')),
        'og_image' => old('og_image', (string) ($story->og_image ?? $story->cover_image ?? '')),
        'status' => old('status', (string) ($story->status ?? 'draft')),
        'scheduled_for' => old('scheduled_for', optional($story->scheduled_for)->format('Y-m-d\\TH:i')),
        'content' => $initialContent,
    ];

    $endpointPayload = [
        'create' => url('/api/stories/create'),
        'update' => url('/api/stories/update'),
        'autosave' => url('/api/stories/autosave'),
        'uploadImage' => url('/api/story/upload-image'),
        'artworks' => url('/api/story/artworks'),
        'previewBase' => url('/creator/stories'),
        'analyticsBase' => url('/creator/stories'),
    ];
@endphp

<div class="mx-auto max-w-7xl" id="story-editor-react-root"
    data-mode="{{ $mode }}"
    data-story='@json($storyPayload)'
    data-story-types='@json($storyTypes)'
    data-endpoints='@json($endpointPayload)'>
    <div class="rounded-xl border border-gray-700 bg-gray-800/60 p-6 text-gray-200 shadow-lg">
        Loading editor...
    </div>
</div>
@endsection
