/// Init command — initialize a new DreamStack project.

use std::fs;
use std::path::PathBuf;

use super::add::get_registry_source;

pub fn cmd_init(name: Option<String>) {
    let project_dir = match &name {
        Some(n) => PathBuf::from(n),
        None => std::env::current_dir().expect("Failed to get current directory"),
    };

    if name.is_some() {
        fs::create_dir_all(&project_dir).expect("Failed to create project directory");
    }

    let components_dir = project_dir.join("components");
    fs::create_dir_all(&components_dir).expect("Failed to create components/ directory");

    // Write starter app.ds
    let app_source = r#"-- My DreamStack App
-- Showcases: imports, components, when/else, match, each, dynamic lists

import { Card } from "./components/card"
import { Badge } from "./components/badge"
import { Button } from "./components/button"

let count = 0
let name = ""
let darkMode = false
let mood = "happy"
let todos = ["Learn DreamStack", "Build something cool"]
let newTodo = ""

view main = column [

  -- Header
  text "🚀 My DreamStack App" { variant: "title" }
  text "Built with DreamStack — edit app.ds and reload" { variant: "subtitle" }

  -- Dashboard cards
  row [
    Card { title: "Counter", subtitle: "reactive state" } [
      text "Count: {count}" { variant: "title" }
      row [
        Button { label: "+1", onClick: count += 1, variant: "primary" }
        Button { label: "-1", onClick: count -= 1, variant: "secondary" }
        Button { label: "Reset", onClick: count = 0, variant: "ghost" }
      ]
    ]

    Card { title: "Greeting", subtitle: "two-way binding" } [
      input { bind: name, placeholder: "Your name..." }
      when name -> text "Hello, {name}! 👋"
      else -> text "Type your name above"
    ]
  ]

  -- Mood selector with match
  Card { title: "Mood", subtitle: "match expressions" } [
    row [
      button "😊 Happy" { click: mood = "happy", variant: "primary" }
      button "😢 Sad" { click: mood = "sad", variant: "secondary" }
      button "🔥 Fired up" { click: mood = "fired", variant: "ghost" }
    ]
    match mood
      "happy" -> Badge { label: "FEELING GREAT 🌟", variant: "success" }
      "sad" -> Badge { label: "HANG IN THERE 💙", variant: "info" }
      "fired" -> Badge { label: "LET'S GO 🔥", variant: "warning" }
      _ -> Badge { label: "HOW ARE YOU?", variant: "info" }
  ]

  -- Todo list with dynamic arrays
  Card { title: "Todos", subtitle: "dynamic lists" } [
    row [
      input { bind: newTodo, placeholder: "New task..." }
      button "Add" { click: todos.push(newTodo), variant: "primary" }
    ]
    each todo in todos ->
      row [
        text "→ {todo}"
        button "×" { click: todos.remove(_idx), variant: "ghost" }
      ]
    button "Clear All" { click: todos = [], variant: "ghost" }
  ]

]
"#;
    fs::write(project_dir.join("app.ds"), app_source).expect("Failed to write app.ds");

    // Write dreamstack.json
    let project_name = name.as_deref().unwrap_or("my-dreamstack-app");
    let config = format!(r#"{{
  "name": "{}",
  "version": "0.1.0",
  "entry": "app.ds"
}}
"#, project_name);
    fs::write(project_dir.join("dreamstack.json"), config).expect("Failed to write dreamstack.json");

    // Add starter components from registry
    let starter_components = ["button", "card", "badge", "input"];
    for comp_name in &starter_components {
        if let Some(source) = get_registry_source(comp_name) {
            let comp_path = components_dir.join(format!("{}.ds", comp_name));
            fs::write(&comp_path, source).expect("Failed to write component");
        }
    }

    let display_name = name.as_deref().unwrap_or(".");
    println!("🚀 DreamStack project initialized in {}/\n", display_name);
    println!("   Created:");
    println!("     app.ds               — your main application");
    println!("     dreamstack.json      — project config");
    println!("     components/button.ds  — button component");
    println!("     components/card.ds    — card component");
    println!("     components/badge.ds   — badge component");
    println!("     components/input.ds   — input component\n");
    println!("   Next steps:");
    if name.is_some() {
        println!("     cd {}", display_name);
    }
    println!("     dreamstack build app.ds -o dist");
    println!("     dreamstack dev app.ds");
    println!("     dreamstack add --list            # see all 11 components");
    println!("     dreamstack add dialog            # add with deps\n");
}
