// image block — a single image with optional caption and alignment. Upload
// reuses the shared admin uploader (returns { url }); the block stays URL-based
// until the Wave 3 asset picker lands.
import { useState } from 'react'
import { registerBlock } from '../registry'
import { api } from '../../api/client.js'
import { SelectField, TextField } from '../editorKit.jsx'

const ALIGN = [
  ['left', 'Left'],
  ['center', 'Center'],
  ['right', 'Right'],
  ['full', 'Full width'],
]
const VALID = ['left', 'center', 'right', 'full']

function ImageBlock({ props }) {
  if (!props.src) return null
  const align = VALID.includes(props.alignment) ? props.alignment : 'center'
  return (
    <figure className={`page-image page-image--${align}`}>
      <img src={props.src} alt={props.alt || ''} />
      {props.caption && <figcaption>{props.caption}</figcaption>}
    </figure>
  )
}

function ImageEditor({ props, onChange }) {
  const [uploading, setUploading] = useState(false)
  const [error, setError] = useState('')

  async function onUpload(e) {
    const file = e.target.files?.[0]
    e.target.value = ''
    if (!file) return
    setUploading(true)
    setError('')
    try {
      const { url } = await api.admin.upload(file)
      onChange({ ...props, src: url })
    } catch (err) {
      setError(err.message || 'Upload failed')
    } finally {
      setUploading(false)
    }
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div>
        <span className="field-label">Image</span>
        <input
          type="file"
          accept="image/*"
          onChange={onUpload}
          className="sans"
          style={{ color: 'var(--muted)', fontSize: '0.85rem', display: 'block' }}
        />
        {uploading && <span className="sans dim" style={{ fontSize: '0.8rem' }}> uploading…</span>}
        {error && <span className="sans" style={{ fontSize: '0.8rem', color: '#d98b84' }}>{error}</span>}
        {props.src && (
          <img
            src={props.src}
            alt=""
            style={{ display: 'block', marginTop: 10, maxWidth: '100%', borderRadius: 8, border: '1px solid var(--line)' }}
          />
        )}
      </div>
      <TextField
        label="Alt text"
        hint="Describes the image for screen readers and when it fails to load."
        value={props.alt}
        maxLength={300}
        onChange={(alt) => onChange({ ...props, alt })}
      />
      <TextField
        label="Caption (optional)"
        value={props.caption}
        maxLength={500}
        onChange={(caption) => onChange({ ...props, caption })}
      />
      <SelectField
        label="Alignment"
        value={props.alignment || 'center'}
        onChange={(alignment) => onChange({ ...props, alignment })}
        options={ALIGN}
      />
    </div>
  )
}

registerBlock({
  type: 'image',
  version: 1,
  label: 'Image',
  icon: '🖼',
  component: ImageBlock,
  editor: ImageEditor,
  defaults: () => ({ src: '', alt: '', caption: '', alignment: 'center' }),
})
