import { Component, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule, PopoverController } from '@ionic/angular';
import { Router } from '@angular/router';

interface Story {
  id: string;
  cover: string;
  title: string;
  createTime: Date;
}

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
  standalone: true,
  imports: [IonicModule, CommonModule]
})
export class HomePage {
  stories: Story[] = [];

  constructor(
    private router: Router,
    private popoverController: PopoverController
  ) { }

  navigateTo(path: string) {
    this.router.navigate([path]);
  }

  async presentCreateOptions(ev: any) {
    const popover = await this.popoverController.create({
      component: CreateOptionsComponent,
      event: ev,
      translucent: true,
      size: 'auto'
    });

    await popover.present();

    const { data } = await popover.onDidDismiss();
    if (data) {
      this.createStory(data.type);
    }
  }

  createStory(type: 'long' | 'short') {
    // 使用查询参数传递类型
    this.router.navigate(['/'], {
      queryParams: { generatorType: type, path: type === 'long' ? 'story-generator' : 'short-generator' }
    });
    const targetPath = type === 'long' ? '/story-generator' : '/short-generator';
    this.router.navigate([targetPath]);
  }

  formatDate(date: Date): string {
    return date.toLocaleDateString('zh-CN');
  }
}

@Component({
  template: `
    <ion-list>
      <ion-item button (click)="select('long')">
        <ion-icon name="book-outline" slot="start"></ion-icon>
        <ion-label>创建长篇</ion-label>
      </ion-item>
      <ion-item button (click)="select('short')">
        <ion-icon name="document-text-outline" slot="start"></ion-icon>
        <ion-label>创建短篇</ion-label>
      </ion-item>
    </ion-list>
  `,
  standalone: true,
  imports: [IonicModule]
})
export class CreateOptionsComponent {
  constructor(private popoverController: PopoverController) { }

  select(type: 'long' | 'short') {
    this.popoverController.dismiss({
      type: type
    });
  }
}
