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

const SCAFFOLD = `import React from 'react'

// group { Copy }
const headlineText = $(headlineText:RichText={ text: "Your headline" });
const subheadText = $(subheadText:RichText={ text: "Your subhead" });
// endgroup

// group { Styling }
const backgroundColor = $(backgroundColor:Color="#FFFFFF");
const textColor = $(textColor:Color="#111827");
const ctaBackground = $(ctaBackground:Color="#111827");
// endgroup

// group { CTA }
const ctaLabel = $(ctaLabel:RichText={ text: "Shop now" });
const ctaHref = $(ctaHref:String="/");
// endgroup

const __COMPONENT__ = () => {
  return (
    <section
      style={{
        backgroundColor,
        color: textColor,
        padding: '48px 24px',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: '16px',
        textAlign: 'center',
      }}
    >
      <h1 style={{ margin: 0, fontSize: 40, fontWeight: 600 }}>{headlineText}</h1>
      <p style={{ margin: 0, maxWidth: 640 }}>{subheadText}</p>
      <a
        href={ctaHref}
        style={{
          backgroundColor: ctaBackground,
          color: '#FFFFFF',
          padding: '12px 20px',
          borderRadius: 8,
          textDecoration: 'none',
        }}
      >
        {ctaLabel}
      </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 templateLegacyInitCommand(name, opts) {
  try {
    if (!name) {
      throw new Error('name argument is required (e.g. `bild template legacy 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.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 legacy validate <file>` or `bild library add <file>`',
      ),
    )
  } catch (error) {
    console.error(chalk.red(`\ntemplate legacy init failed: ${error.message}`))
    process.exit(1)
  }
}

module.exports = templateLegacyInitCommand
