// two_column block — the only container. Holds two ordered arrays of sub-blocks
// (`left`, `right`). Sub-blocks are leaf blocks only (no nested containers — the
// one-level cap the server also enforces), so the column editor's palette is the
// set of non-container registered blocks.
import { registerBlock, getBlock, listBlocks, makeBlockId } from '../registry'
import BlockRenderer from '../BlockRenderer.jsx'

// ── Renderer ──────────────────────────────────────────────────────────
function TwoColumnBlock({ props }) {
  const left = Array.isArray(props.left) ? props.left : []
  const right = Array.isArray(props.right) ? props.right : []
  return (
    <div className="page-two-column">
      <div className="page-column">
        {left.map((b) => (
          <BlockRenderer key={b.id} block={b} />
        ))}
      </div>
      <div className="page-column">
        {right.map((b) => (
          <BlockRenderer key={b.id} block={b} />
        ))}
      </div>
    </div>
  )
}

// ── Column editor ─────────────────────────────────────────────────────
// Manages one side's array: add (from the leaf palette), edit each via its own
// registry editor, reorder, remove.
function ColumnEditor({ title, items, onChange }) {
  const list = Array.isArray(items) ? items : []
  const palette = listBlocks().filter((b) => !b.container)

  function addBlock(type) {
    const def = getBlock(type)
    if (!def) return
    const block = { id: makeBlockId(), type, version: def.version, visible: true, props: def.defaults() }
    onChange([...list, block])
  }
  function updateAt(i, nextProps) {
    onChange(list.map((b, j) => (j === i ? { ...b, props: nextProps } : b)))
  }
  function removeAt(i) {
    onChange(list.filter((_, j) => j !== i))
  }
  function move(i, dir) {
    const j = i + dir
    if (j < 0 || j >= list.length) return
    const next = [...list]
    ;[next[i], next[j]] = [next[j], next[i]]
    onChange(next)
  }

  return (
    <div className="pb-column-editor">
      <div className="pb-column-head">
        <span className="field-label" style={{ margin: 0 }}>{title}</span>
        <select
          className="select pb-add-select"
          value=""
          onChange={(e) => {
            if (e.target.value) addBlock(e.target.value)
            e.target.value = ''
          }}
        >
          <option value="">+ Add block…</option>
          {palette.map((b) => (
            <option key={b.type} value={b.type}>
              {b.label}
            </option>
          ))}
        </select>
      </div>

      {list.length === 0 && (
        <p className="sans dim" style={{ fontSize: '0.8rem', margin: '4px 0' }}>Empty column.</p>
      )}

      {list.map((block, i) => {
        const def = getBlock(block.type)
        const Editor = def?.editor
        return (
          <div key={block.id} className="pb-subblock">
            <div className="pb-subblock-head">
              <span className="sans dim" style={{ fontSize: '0.78rem' }}>{def?.label || block.type}</span>
              <div className="pb-subblock-actions">
                <button type="button" className="pill pb-mini" disabled={i === 0} onClick={() => move(i, -1)} title="Move up">↑</button>
                <button type="button" className="pill pb-mini" disabled={i === list.length - 1} onClick={() => move(i, 1)} title="Move down">↓</button>
                <button type="button" className="pill pb-mini" onClick={() => removeAt(i)} title="Remove">✕</button>
              </div>
            </div>
            {Editor && <Editor props={block.props || {}} onChange={(p) => updateAt(i, p)} />}
          </div>
        )
      })}
    </div>
  )
}

function TwoColumnEditor({ props, onChange }) {
  return (
    <div className="pb-two-column-editor">
      <ColumnEditor title="Left column" items={props.left} onChange={(left) => onChange({ ...props, left })} />
      <ColumnEditor title="Right column" items={props.right} onChange={(right) => onChange({ ...props, right })} />
    </div>
  )
}

registerBlock({
  type: 'two_column',
  version: 1,
  label: 'Two columns',
  icon: '▥',
  component: TwoColumnBlock,
  editor: TwoColumnEditor,
  defaults: () => ({ left: [], right: [] }),
  container: true,
  containerSlots: ['left', 'right'],
})
