const fs = require('fs')
const path = require('path')
const chalk = require('chalk')

/** V2 scaffold: pure JavaScript / JSX (no BILDIT $() template syntax). */
const SCAFFOLD_V2 = `import React from 'react'

/**
 * Pure JS template for BILDIT CMS Templates (v2). Edit markup and styles as needed.
 */
function __COMPONENT__() {
  return (
    <section
      style={{
        padding: '48px 24px',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: '16px',
        textAlign: 'center',
        backgroundColor: '#FFFFFF',
        color: '#111827',
      }}
    >
      <h1 style={{ margin: 0, fontSize: 40, fontWeight: 600 }}>Headline</h1>
      <p style={{ margin: 0, maxWidth: 640 }}>Subhead copy.</p>
      <a
        href="/"
        style={{
          backgroundColor: '#111827',
          color: '#FFFFFF',
          padding: '12px 20px',
          borderRadius: 8,
          textDecoration: 'none',
        }}
      >
        Shop now
      </a>
    </section>
  );
}

export default __COMPONENT__;
`

function toComponentName(name) {
  return name
    .replace(/[^A-Za-z0-9]+/g, ' ')
    .split(' ')
    .filter(Boolean)
    .map((s) => s.charAt(0).toUpperCase() + s.slice(1))
    .join('')
}

async function templateInitCommand(name, opts) {
  try {
    if (!name) throw new Error('name argument is required (e.g. `bild template init hero-standard`)')
    const cmp = toComponentName(name)
    const ext = opts.ts ? '.tsx' : '.jsx'
    const out = path.resolve(opts.out || `${name}${ext}`)
    if (fs.existsSync(out) && !opts.force) {
      throw new Error(`${out} already exists (use --force to overwrite)`)
    }
    const code = SCAFFOLD_V2.replace(/__COMPONENT__/g, cmp)
    fs.mkdirSync(path.dirname(out), { recursive: true })
    fs.writeFileSync(out, code, 'utf8')
    console.log(chalk.green(`Wrote ${out}`))
    console.log(
      chalk.blue(
        'Next: edit the component, then run `bild template validate <file>` or `bild library add <file>`',
      ),
    )
    console.log(
      chalk.dim(
        'For v1 BILDIT $() templates, use `bild template legacy init` instead.',
      ),
    )
  } catch (error) {
    console.error(chalk.red(`\ntemplate init failed: ${error.message}`))
    process.exit(1)
  }
}

module.exports = templateInitCommand
