<#
Nama Script   : TextToFileGenerator.ps1
Deskripsi     :
Script ini mengubah text input menjadi file dengan format yang dipilih.
User bisa input multiple text content dan generate menjadi file terpisah.

Alur User     :
1. User input dimana generate (output directory).
2. User input text content (comma-separated).
3. User pilih format file (markdown, text, code, etc).
4. Preview hasil generate.
5. User konfirmasi untuk generate.
6. Script create files dengan naming otomatis (tanpa index suffix).

Features:
- No index suffix (Chip.md, Keyboard.md, tidak Chip-1.md)
- Auto deduplication (duplikat dihapus)
- Clean filename (no spaces, hyphens untuk separator)

Supported Formats:
- Markdown: .md, .mdx
- Text: .txt
- Code: .js, .mjs, .cjs, .ts, .tsx, .php, .py, .rb, .rs, .go
- Web: .html, .css, .scss
- Data: .json, .yaml, .yml, .toml
- Shell: .sh, .ps1, .bat
- Data: .csv
Default: .md
#>

# ── Display supported formats ──────────────────────────────────────────────────
function Show-SupportedFormats {
    Write-Host ""
    Write-Host "📋 Supported File Formats:" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "  📝 Markdown & Text:" -ForegroundColor Cyan
    Write-Host "     1.  .md   (Markdown)" -ForegroundColor Gray
    Write-Host "     2.  .mdx  (MDX)" -ForegroundColor Gray
    Write-Host "     3.  .txt  (Plain Text)" -ForegroundColor Gray
    Write-Host ""
    Write-Host "  💻 Code & Scripts:" -ForegroundColor Cyan
    Write-Host "     4.  .js   (JavaScript)" -ForegroundColor Gray
    Write-Host "     5.  .mjs  (ES Module)" -ForegroundColor Gray
    Write-Host "     6.  .cjs  (CommonJS)" -ForegroundColor Gray
    Write-Host "     7.  .ts   (TypeScript)" -ForegroundColor Gray
    Write-Host "     8.  .tsx  (TypeScript React)" -ForegroundColor Gray
    Write-Host "     9.  .php  (PHP)" -ForegroundColor Gray
    Write-Host "    10.  .py   (Python)" -ForegroundColor Gray
    Write-Host "    11.  .rb   (Ruby)" -ForegroundColor Gray
    Write-Host "    12.  .rs   (Rust)" -ForegroundColor Gray
    Write-Host "    13.  .go   (Go)" -ForegroundColor Gray
    Write-Host ""
    Write-Host "  🌐 Web & Style:" -ForegroundColor Cyan
    Write-Host "    14.  .html (HTML)" -ForegroundColor Gray
    Write-Host "    15.  .css  (CSS)" -ForegroundColor Gray
    Write-Host "    16.  .scss (SCSS)" -ForegroundColor Gray
    Write-Host ""
    Write-Host "  📊 Data Formats:" -ForegroundColor Cyan
    Write-Host "    17.  .json (JSON)" -ForegroundColor Gray
    Write-Host "    18.  .yaml (YAML)" -ForegroundColor Gray
    Write-Host "    19.  .yml  (YAML)" -ForegroundColor Gray
    Write-Host "    20.  .toml (TOML)" -ForegroundColor Gray
    Write-Host "    21.  .csv  (CSV)" -ForegroundColor Gray
    Write-Host ""
    Write-Host "  🔧 Shell & Scripts:" -ForegroundColor Cyan
    Write-Host "    22.  .sh   (Bash/Shell)" -ForegroundColor Gray
    Write-Host "    23.  .ps1  (PowerShell)" -ForegroundColor Gray
    Write-Host "    24.  .bat  (Batch)" -ForegroundColor Gray
    Write-Host ""
}

# ── Map format choice to extension ─────────────────────────────────────────────
function Get-FileExtension {
    param ([string]$Choice)

    $extensionMap = @{
        "1"  = "md"
        "2"  = "mdx"
        "3"  = "txt"
        "4"  = "js"
        "5"  = "mjs"
        "6"  = "cjs"
        "7"  = "ts"
        "8"  = "tsx"
        "9"  = "php"
        "10" = "py"
        "11" = "rb"
        "12" = "rs"
        "13" = "go"
        "14" = "html"
        "15" = "css"
        "16" = "scss"
        "17" = "json"
        "18" = "yaml"
        "19" = "yml"
        "20" = "toml"
        "21" = "csv"
        "22" = "sh"
        "23" = "ps1"
        "24" = "bat"
    }

    return $extensionMap[$Choice]
}

# ── Generate safe filename from content ────────────────────────────────────────
function Get-SafeFilename {
    param ([string]$Content, [string]$Extension, [array]$ProcessedNames)

    # Trim leading/trailing spaces, convert spaces to hyphens
    $text = $Content.Trim() -replace '\s+', '-'
    
    # Remove special chars, keep only alphanumeric and hyphens
    $safeName = $text -replace '[^a-zA-Z0-9\-]', ''
    
    # Remove leading/trailing hyphens
    $safeName = $safeName -replace '^-+|-+$', ''
    
    # Remove duplicate hyphens
    $safeName = $safeName -replace '-+', '-'
    
    if ([string]::IsNullOrWhiteSpace($safeName)) {
        return $null
    }
    
    # Check for duplicates in already processed names
    if ($ProcessedNames -contains $safeName) {
        return $null  # Skip duplicate
    }
    
    $filename = "$safeName.$extension"
    return $filename
}

# ── Banner ─────────────────────────────────────────────────────────────────────
Clear-Host
Write-Host "╔═══════════════════════════════════════════════════════════════════╗" -ForegroundColor DarkCyan
Write-Host "║   📝  TEXT TO FILE GENERATOR  v2.0                               ║" -ForegroundColor DarkCyan
Write-Host "║   Convert text input into files with custom formats              ║" -ForegroundColor DarkCyan
Write-Host "║   No index suffix • Auto deduplication • Clean filenames         ║" -ForegroundColor DarkCyan
Write-Host "╚═══════════════════════════════════════════════════════════════════╝" -ForegroundColor DarkCyan
Write-Host ""

# ── MAIN LOOP ──────────────────────────────────────────────────────────────────
do {

    # ── Step 1: Input output directory ─────────────────────────────────────────
    do {
        $outputFolder = Read-Host "📁 Step 1: Input output directory (dimana file akan di-generate)"
        $outputFolder = $outputFolder.Trim('"').Trim("'").Trim()

        if (-not (Test-Path $outputFolder -PathType Container)) {
            Write-Host "`n❌ Folder tidak ditemukan! Periksa path lagi.`n" -ForegroundColor Red
            $validFolder = $false
        } else {
            Write-Host "✅ Output folder: $outputFolder`n" -ForegroundColor Green
            $validFolder = $true
        }
    } while (-not $validFolder)

    # ── Step 2: Input text content (comma-separated) ────────────────────────────
    Write-Host ""
    Write-Host "📝 Step 2: Input text content" -ForegroundColor Yellow
    Write-Host "   Masukkan text yang dipisahkan dengan koma (,)" -ForegroundColor Gray
    Write-Host "   Contoh: Chip, Keyboard, Mouse, Trackpad" -ForegroundColor Gray
    Write-Host ""

    $textInput = Read-Host "Masukkan text (dipisahkan dengan koma)"
    
    if ([string]::IsNullOrWhiteSpace($textInput)) {
        Write-Host "`n❌ Text tidak boleh kosong!`n" -ForegroundColor Red
        continue
    }

    # ── Split by comma and trim each text ──────────────────────────────────────
    $textInputs = $textInput -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_.Length -gt 0 }

    if ($textInputs.Count -eq 0) {
        Write-Host "`n❌ Tidak ada text yang valid setelah split!`n" -ForegroundColor Red
        continue
    }

    Write-Host ""
    Write-Host "✅ Total text diinput: $($textInputs.Count)" -ForegroundColor Green
    Write-Host ""

    # ── Step 3: Choose file format ─────────────────────────────────────────────
    Show-SupportedFormats

    do {
        Write-Host "📋 Step 3: Pilih format file" -ForegroundColor Yellow
        Write-Host "   Opsi 1: Ketik angka 1-24 (pilih dari list)" -ForegroundColor Gray
        Write-Host "   Opsi 2: Ketik custom format (dengan atau tanpa dot)" -ForegroundColor Gray
        Write-Host "   Contoh: md, .ts, json, .tsx" -ForegroundColor Gray
        Write-Host ""
        
        $formatChoice = Read-Host "Masukkan format (default = md)"
        $formatChoice = $formatChoice.Trim()

        if ([string]::IsNullOrWhiteSpace($formatChoice)) {
            $formatChoice = "1"
        }

        # ── Try to get from preset numbers first ────────────────────────────────
        $extension = Get-FileExtension -Choice $formatChoice
        
        if ($extension) {
            # Valid preset number
            Write-Host "`n✅ Format dipilih: .$extension`n" -ForegroundColor Green
            Write-Host "   Quick Note: markdown = .md, .mdx | code = .js, .ts, .py | data = .json, .yaml`n" -ForegroundColor Gray
            $validFormat = $true
        }
        else {
            # Check if it's a custom format
            # Remove leading dot if present
            $customFormat = $formatChoice -replace '^\s*\.', ''
            $customFormat = $customFormat.Trim()

            # Validate: only alphanumeric (allow dots within)
            if ($customFormat -match '^[a-zA-Z0-9\.]+$' -and $customFormat.Length -gt 0) {
                $extension = $customFormat
                Write-Host "`n✅ Custom format dipilih: .$extension`n" -ForegroundColor Green
                $validFormat = $true
            }
            else {
                Write-Host "`n❌ Format tidak valid! Gunakan:" -ForegroundColor Red
                Write-Host "   - Angka 1-24 untuk preset, atau" -ForegroundColor Red
                Write-Host "   - Custom format tanpa spesial char (contoh: md, tsx, myformat)`n" -ForegroundColor Red
                $validFormat = $false
            }
        }
    } while (-not $validFormat)

    # ── Step 4: Preview ────────────────────────────────────────────────────────
    Write-Host ""
    Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -ForegroundColor DarkGray
    Write-Host "👁️  PREVIEW" -ForegroundColor Yellow
    Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -ForegroundColor DarkGray
    Write-Host ""

    $processedNames = @()
    $fileIndex = 0
    $validCount = 0
    
    foreach ($text in $textInputs) {
        $filename = Get-SafeFilename -Content $text -Extension $extension -ProcessedNames $processedNames
        
        # Skip if duplicate or empty
        if ($null -eq $filename) {
            continue
        }
        
        $fileIndex++
        $baseName = $filename -replace "\.$extension$", ""
        $processedNames += $baseName
        
        Write-Host "  [$fileIndex] 📄 $filename" -ForegroundColor Cyan
        Write-Host "      Location: $outputFolder\$filename" -ForegroundColor Gray
        Write-Host "      Content: $text" -ForegroundColor DarkGray
        Write-Host ""
        
        $validCount++
    }

    if ($validCount -eq 0) {
        Write-Host "❌ Tidak ada file yang valid (semua mungkin duplikat)`n" -ForegroundColor Red
        continue
    }

    Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -ForegroundColor DarkGray
    Write-Host "📊 Summary:" -ForegroundColor White
    Write-Host "   Total files to create: $validCount" -ForegroundColor Gray
    Write-Host "   Output folder: $outputFolder" -ForegroundColor Gray
    Write-Host "   Format: .$extension" -ForegroundColor Gray
    Write-Host ""

    # ── Step 5: Confirm generation ─────────────────────────────────────────────
    $confirm = Read-Host "⚠️  Lanjutkan generate? (Y = ya, Enter/N = tidak)"
    $confirm = $confirm.Trim().ToLower()

    if ($confirm -ne 'y') {
        Write-Host "`n❌ Dibatalkan.`n" -ForegroundColor Yellow
        continue
    }

    # ── Step 6: Generate files ─────────────────────────────────────────────────
    Write-Host ""
    Write-Host "🚀 Generating files..." -ForegroundColor Cyan
    Write-Host ""

    $successCount = 0
    $failCount = 0
    $processedNames = @()

    foreach ($text in $textInputs) {
        $filename = Get-SafeFilename -Content $text -Extension $extension -ProcessedNames $processedNames
        
        # Skip if duplicate or empty
        if ($null -eq $filename) {
            continue
        }
        
        $baseName = $filename -replace "\.$extension$", ""
        $processedNames += $baseName
        
        $outputPath = Join-Path $outputFolder $filename

        try {
            # Create file with UTF8 encoding
            $text | Out-File -FilePath $outputPath -Encoding UTF8 -NoNewline
            Write-Host "  ✅ Created → $filename" -ForegroundColor Green
            $successCount++
        }
        catch {
            Write-Host "  ❌ Failed → $filename (Error: $_)" -ForegroundColor Red
            $failCount++
        }
    }

    # ── Summary ────────────────────────────────────────────────────────────────
    Write-Host ""
    Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -ForegroundColor DarkGray
    Write-Host "📊 SUMMARY" -ForegroundColor White
    Write-Host "   ✅ Berhasil dibuat : $successCount file" -ForegroundColor Green
    if ($failCount -gt 0) {
        Write-Host "   ❌ Gagal : $failCount file" -ForegroundColor Red
    }
    Write-Host "   📁 Output folder : $outputFolder" -ForegroundColor Gray
    Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -ForegroundColor DarkGray
    Write-Host ""

    # ── Ask to continue ────────────────────────────────────────────────────────
    $again = Read-Host "🔁 Generate files lagi? (Y = ya, Enter/N = keluar)"
    
    if ($again.Trim().ToLower() -ne 'y') {
        break
    }

    Clear-Host

} while ($true)

Write-Host ""
Write-Host "👋 TextToFileGenerator selesai. Sampai jumpa!" -ForegroundColor DarkCyan
Write-Host ""