<script lang="ts">
    import { notes } from '$lib';
    import { goto } from '$app/navigation';
    export let data;
    
    let title = data.props.prefilledTitle;
    let content = '';

    async function handleSave() {
        if (!title || !content) return;

        try {
            await notes.add({
                title,
                content
            });
            goto('/');
        } catch (error) {
            console.error('Failed to create note:', error);
        }
    }
</script>

<div class="container">
    <section class="section">
        <h1 class="title">New Note</h1>
        <form on:submit|preventDefault={handleSave}>
            <div class="field">
                <label class="label" for="title">Title</label>
                <div class="control">
                    <input 
                        id="title"
                        class="input" 
                        type="text" 
                        bind:value={title} 
                        required
                    >
                </div>
            </div>

            <div class="field">
                <label class="label" for="content">Content</label>
                <div class="control">
                    <textarea 
                        id="content"
                        class="textarea" 
                        bind:value={content} 
                        rows="10"
                        required
                    ></textarea>
                </div>
            </div>

            <div class="field">
                <div class="control">
                    <button type="submit" class="button is-primary">Create</button>
                    <button type="button" class="button is-light" on:click={() => goto('/')}>Cancel</button>
                </div>
            </div>
        </form>
    </section>
</div>
