// widgets/PostFeedWidget.ts
import { Widget } from '../components/Widget';
import { createElement } from '../utils/utils';
import { globalAPI, ApiResponse, ProfileResponseData } from '../api/api'; // Import API and types (now exported)

export class PostFeedWidget extends Widget {
    private posts: { id: number; content: string }[] = [];

    constructor() {
        super();
        this.fetchPosts();
    }

    async fetchPosts() {
        try {
            const response: ApiResponse<ProfileResponseData> = await globalAPI.getProfile('mockUserId');
            if (response.success && response.data && response.data.posts) {
                this.posts = response.data.posts;
                this.render();
            } else {
                console.error("Failed to fetch posts");
            }
        } catch (error) {
            console.error("Error fetching posts:", error);
        }
    }

    render(): HTMLElement {
        this.container.innerHTML = '';

        const header = createElement('div');
        header.classList.add('widget-header');
        header.textContent = 'Post Feed';
        this.container.appendChild(header);

        const widgetBody = createElement('div');
        widgetBody.classList.add('widget-body');

        if (this.posts.length === 0) {
            widgetBody.textContent = 'No posts yet.';
        } else {
            this.posts.forEach(post => {
                const postDiv = createElement('div');
                postDiv.classList.add('mb-2', 'p-2', 'border', 'rounded');
                postDiv.textContent = post.content;
                widgetBody.appendChild(postDiv);
            });
        }

        this.container.appendChild(widgetBody);
        return this.container;
    }
}