// Shared create / edit drawer — schema-driven so every screen builds entry forms
// the same way. Field types: text | money | number | date | select | seg | textarea.
// A field with half:true pairs with the next half:true field into one row.

function EntityField({ f, value, onChange }) {
  const v = value ?? '';
  if (f.type === 'select')
    return <Dropdown value={v} options={f.options} onChange={val => onChange(f.key, val)} minWidth={'100%'} icon={f.icon} placeholder={f.placeholder || 'Select'} />;
  if (f.type === 'seg')
    return (
      <div className="seg-full">
        {f.options.map(o => (
          <button key={o.value} className={v === o.value ? 'on' : ''} onClick={() => onChange(f.key, o.value)}>
            {o.dot && <span className="dd-dot" style={{ background: o.dot }} />}{o.label}
          </button>
        ))}
      </div>
    );
  if (f.type === 'textarea')
    return <textarea className="fld" placeholder={f.placeholder} value={v} onChange={e => onChange(f.key, e.target.value)} />;
  // text-like inputs
  return (
    <div className="finput">
      {f.pre && <span className="fpre">{f.pre}</span>}
      {f.icon && !f.pre && <Icon name={f.icon} size={16} color="var(--fg-4)" />}
      <input
        type={f.type === 'date' ? 'date' : 'text'}
        inputMode={f.type === 'money' || f.type === 'number' ? 'decimal' : undefined}
        placeholder={f.placeholder}
        value={v}
        onChange={e => onChange(f.key, e.target.value)}
      />
    </div>
  );
}

function EntityDrawer({ title, sub, icon = 'plus', tint = 'gold', fields, initial = {},
  onClose, onSubmit, onDelete, submitLabel = 'Save', submitIcon = 'check', topContent = null }) {
  const [form, setForm] = useState(initial);
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  // group consecutive half fields into rows
  const rows = [];
  for (let i = 0; i < fields.length; i++) {
    const f = fields[i];
    if (f.half && fields[i + 1] && fields[i + 1].half) { rows.push([f, fields[i + 1]]); i++; }
    else rows.push([f]);
  }

  const required = fields.filter(f => f.required).map(f => f.key);
  const valid = required.every(k => String(form[k] ?? '').trim());

  return (
    <React.Fragment>
      <div className="scrim" onClick={onClose} />
      <div className="drawer zd-scroll">
        <div className="dhead">
          <IconChip icon={icon} tint={tint} size={40} radius={12} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18 }}>{title}</div>
            {sub && <div style={{ fontSize: 12.5, color: 'var(--fg-3)' }}>{sub}</div>}
          </div>
          <button className="iconbtn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>
        <div className="dbody">
          {topContent}
          {rows.map((grp, gi) => grp.length === 2
            ? <div className="drow" key={gi}>{grp.map(f => (
                <div style={{ flex: 1, minWidth: 0 }} key={f.key}><label className="fl">{f.label}</label><EntityField f={f} value={form[f.key]} onChange={set} /></div>
              ))}</div>
            : <div key={gi}><label className="fl">{grp[0].label}</label><EntityField f={grp[0]} value={form[grp[0].key]} onChange={set} /></div>
          )}
          <div className="drawer-foot">
            {onDelete && <button className="iconbtn danger" onClick={onDelete} title="Delete"><Icon name="trash-2" size={17} /></button>}
            <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
            <button className="btn btn-primary" style={{ flex: 1, justifyContent: 'center', opacity: valid ? 1 : .5, pointerEvents: valid ? 'auto' : 'none' }} onClick={() => onSubmit(form)}>
              <Icon name={submitIcon} size={16} />{submitLabel}
            </button>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}

Object.assign(window, { EntityDrawer, EntityField });
