// Data Input modal — toggle + reorder fields, add up to 4 custom fields.
const { useState: useStateDI } = React;

// Built-in fields (title + desc are core, not toggleable here).
const BUILTIN_FIELDS = [
  { key: 'shot',     label: 'Shot Type',    icon: 'IconShotType',  placeholder: 'MS' },
  { key: 'camera',   label: 'Camera',       icon: 'IconCameraBody', placeholder: 'ARRI Mini LF' },
  { key: 'lens',     label: 'Lens',         icon: 'IconAperture',  placeholder: '35mm' },
  { key: 'move',     label: 'Movement',     icon: 'IconArrows',    placeholder: 'Static' },
  { key: 'duration', label: 'Duration',     icon: 'IconClock',     placeholder: '3s' },
  { key: 'location', label: 'Location',     icon: 'IconLocation',  placeholder: 'INT — Loft' },
];

function DataInputModal({ config, onSave, onClose }) {
  // Combined ordered list — entries are { key, kind: 'builtin'|'custom', enabled, label? }
  const initial = (() => {
    const order = config.order && config.order.length ? config.order : [
      ...BUILTIN_FIELDS.map(f => ({ key: f.key, kind: 'builtin' })),
      ...config.custom.map(c => ({ key: c.key, kind: 'custom' })),
    ];
    return order.map(o => {
      if (o.kind === 'builtin') {
        const def = BUILTIN_FIELDS.find(f => f.key === o.key);
        if (!def) return null;
        return { ...def, kind: 'builtin', enabled: !!config.enabled[o.key] };
      }
      const cf = config.custom.find(c => c.key === o.key);
      if (!cf) return null;
      return { ...cf, kind: 'custom', icon: null, enabled: true };
    }).filter(Boolean);
  })();

  const [items, setItems] = useStateDI(initial);
  const [drag, setDrag] = useStateDI(null);

  const customCount = items.filter(i => i.kind === 'custom').length;

  const toggle = (i) => setItems(arr => arr.map((x, xi) => xi === i ? { ...x, enabled: !x.enabled } : x));
  const updLabel = (i, v) => setItems(arr => arr.map((x, xi) => xi === i ? { ...x, label: v } : x));
  const remove = (i) => setItems(arr => arr.filter((_, xi) => xi !== i));
  const addCustom = () => {
    if (customCount >= 4) return;
    setItems(arr => [...arr, {
      key: 'cf_' + Math.random().toString(36).slice(2,7),
      kind: 'custom', label: '', enabled: true
    }]);
  };

  const onDragStart = (i) => (e) => {
    e.dataTransfer.effectAllowed = 'move';
    setDrag({ from: i, over: null, side: null });
  };
  const onDragOver = (i) => (e) => {
    e.preventDefault();
    if (!drag || drag.from === i) return;
    const r = e.currentTarget.getBoundingClientRect();
    const side = (e.clientY - r.top) < r.height / 2 ? 'before' : 'after';
    setDrag(d => d && (d.over !== i || d.side !== side) ? { ...d, over: i, side } : d);
  };
  const onDrop = (i) => (e) => {
    e.preventDefault();
    if (!drag || drag.from === i) { setDrag(null); return; }
    setItems(arr => {
      const next = [...arr];
      const [m] = next.splice(drag.from, 1);
      let target = i;
      if (drag.from < i) target -= 1;
      if (drag.side === 'after') target += 1;
      next.splice(target, 0, m);
      return next;
    });
    setDrag(null);
  };
  const onDragEnd = () => setDrag(null);

  const save = () => {
    const enabled = {};
    BUILTIN_FIELDS.forEach(f => { enabled[f.key] = false; });
    const custom = [];
    const order = [];
    items.forEach(it => {
      if (it.kind === 'builtin') {
        enabled[it.key] = !!it.enabled;
        order.push({ key: it.key, kind: 'builtin' });
      } else if (it.label.trim()) {
        custom.push({ key: it.key, label: it.label.trim() });
        order.push({ key: it.key, kind: 'custom' });
      }
    });
    onSave({ enabled, custom, order });
    onClose();
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal modal-wide" onClick={(e) => e.stopPropagation()}>
        <h2>Data input</h2>
        <p className="modal-sub">Toggle, reorder, or add fields. Drag the handle to reorder. Up to 4 custom fields.</p>

        <div className="di-list">
          {items.map((it, i) => {
            const Icon = it.icon ? window[it.icon] : null;
            const isOver = drag && drag.over === i;
            const cls = [
              'di-row',
              !it.enabled ? 'off' : '',
              drag?.from === i ? 'dragging' : '',
              isOver && drag.side === 'before' ? 'drop-before' : '',
              isOver && drag.side === 'after' ? 'drop-after' : '',
            ].filter(Boolean).join(' ');
            return (
              <div
                key={it.key}
                className={cls}
                draggable
                onDragStart={onDragStart(i)}
                onDragOver={onDragOver(i)}
                onDrop={onDrop(i)}
                onDragEnd={onDragEnd}
              >
                <div className="di-handle" title="Drag to reorder"><IconGrip /></div>
                <div className="di-row-icon">
                  {Icon ? <Icon /> : <span className="di-dot di-dot-grey" />}
                </div>
                {it.kind === 'builtin' ? (
                  <div className="di-row-label">{it.label}</div>
                ) : (
                  <input
                    className="di-row-input"
                    value={it.label}
                    onChange={(e) => updLabel(i, e.target.value)}
                    placeholder="Custom field name (e.g. Audio note)"
                  />
                )}
                {it.kind === 'builtin' ? (
                  <button
                    className={`di-toggle ${it.enabled ? 'on' : ''}`}
                    onClick={() => toggle(i)}
                    title={it.enabled ? 'Hide field' : 'Show field'}
                  >
                    <span className="di-toggle-dot" />
                  </button>
                ) : (
                  <button className="icon-btn" onClick={() => remove(i)} title="Remove field">
                    <IconTrash />
                  </button>
                )}
              </div>
            );
          })}
        </div>

        {customCount < 4 && (
          <button className="btn btn-ghost di-add-custom" onClick={addCustom}>
            <IconPlus /> Add custom field <span className="di-section-hint">{customCount}/4</span>
          </button>
        )}

        <div className="modal-actions">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary" onClick={save}><IconCheck /> Save</button>
        </div>
      </div>
    </div>
  );
}

window.DataInputModal = DataInputModal;
window.BUILTIN_FIELDS = BUILTIN_FIELDS;
