// cta block — a call-to-action button/link. Renders as an anchor styled with the
// existing button system (primary / secondary).
import { registerBlock } from '../registry'
import { SelectField, TextField } from '../editorKit.jsx'

const STYLES = [
  ['primary', 'Primary'],
  ['secondary', 'Secondary'],
]

function CtaBlock({ props }) {
  if (!props.url || !props.text) return null
  const style = props.style === 'secondary' ? 'secondary' : 'primary'
  // External links get a safe rel; same-origin relative links don't need it.
  const external = /^https?:\/\//i.test(props.url)
  return (
    <div className="page-cta-wrap">
      <a
        className={`btn btn-sq page-cta page-cta--${style}`}
        href={props.url}
        {...(external ? { rel: 'noopener noreferrer nofollow' } : {})}
      >
        {props.text}
      </a>
    </div>
  )
}

function CtaEditor({ props, onChange }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <TextField
        label="Button text"
        value={props.text}
        maxLength={100}
        onChange={(text) => onChange({ ...props, text })}
      />
      <TextField
        label="URL"
        hint="A full https:// link or a same-site path like /wiki/getting-started."
        value={props.url}
        placeholder="https://…"
        onChange={(url) => onChange({ ...props, url })}
      />
      <SelectField
        label="Style"
        value={props.style || 'primary'}
        onChange={(style) => onChange({ ...props, style })}
        options={STYLES}
      />
    </div>
  )
}

registerBlock({
  type: 'cta',
  version: 1,
  label: 'Button',
  icon: '⇥',
  component: CtaBlock,
  editor: CtaEditor,
  defaults: () => ({ text: '', url: '', style: 'primary' }),
})
