// FormSheet — a generic bottom-sheet form used for Add/Edit on every entity.
// Pass `fields` describing the inputs, plus initial values, and handlers.
//
// Field shape:
//   { name, label, type, placeholder, options, default, hint, min, max, step }
//   type ∈ 'text' | 'textarea' | 'choice' | 'multichoice' | 'number' | 'toggle'
//
// `choice` and `multichoice` options: [{ value, label, color? }]

function FormSheet({
  title, eyebrow, fields, initial,
  submitLabel = 'Save', deleteLabel = 'Delete',
  onClose, onSubmit, onDelete,
}) {
  const [values, setValues] = React.useState(() => {
    const v = { ...(initial || {}) };
    (fields || []).forEach(f => {
      if (v[f.name] === undefined) {
        v[f.name] = f.default !== undefined
          ? f.default
          : (f.type === 'toggle' ? false
             : f.type === 'multichoice' ? []
             : f.type === 'number' ? (f.min ?? 1)
             : '');
      }
    });
    return v;
  });

  const setField = (name, value) =>
    setValues(v => ({ ...v, [name]: value }));

  // Stop bubbling clicks inside the sheet from closing it via backdrop.
  const stop = (e) => e.stopPropagation();

  return (
    <>
      {/* Backdrop */}
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0,
        background: 'rgba(29,24,18,0.36)',
        backdropFilter: 'blur(2px)',
        zIndex: 80,
        animation: 'wos-fade-in 200ms ease',
      }}/>

      {/* Sheet */}
      <div onClick={stop} style={{
        position: 'fixed', bottom: 0, left: 0, right: 0,
        background: W.card,
        borderTopLeftRadius: 24, borderTopRightRadius: 24,
        boxShadow: '0 -16px 44px -20px rgba(29,24,18,0.4)',
        padding: '14px 0 26px',
        zIndex: 90,
        maxHeight: '92dvh',
        maxWidth: 640, margin: '0 auto',
        display: 'flex', flexDirection: 'column',
        animation: 'wos-sheet-rise 280ms cubic-bezier(0.2, 0.8, 0.2, 1)',
      }}>
        {/* Grabber */}
        <div style={{
          width: 38, height: 4, borderRadius: 999, background: W.faint,
          margin: '0 auto 12px',
        }}/>

        {/* Header */}
        <div style={{
          padding: '0 22px 14px',
          display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
          borderBottom: `0.5px solid ${W.lineSoft}`,
        }}>
          <div>
            {eyebrow && (
              <div style={{
                fontFamily: FONT_UI, fontSize: 10, fontWeight: 600,
                letterSpacing: 1.8, textTransform: 'uppercase', color: W.muted,
              }}>{eyebrow}</div>
            )}
            <div style={{
              fontFamily: FONT_DISPLAY, fontSize: 22, fontWeight: 500,
              color: W.ink, letterSpacing: -0.2, lineHeight: 1.1, marginTop: 4,
            }}>{title}</div>
          </div>
          <button onClick={onClose} style={{
            background: 'transparent', border: 'none', cursor: 'pointer',
            fontFamily: FONT_UI, fontSize: 13, color: W.muted, padding: 0,
          }}>Cancel</button>
        </div>

        {/* Fields — scrollable */}
        <div style={{
          flex: 1, overflowY: 'auto', overflowX: 'hidden',
          padding: '18px 22px',
          display: 'flex', flexDirection: 'column', gap: 16,
        }}>
          {(fields || []).map(f => (
            <FormField key={f.name} field={f}
              value={values[f.name]}
              onChange={(v) => setField(f.name, v)}
              values={values}/>
          ))}
        </div>

        {/* Actions */}
        <div style={{
          padding: '12px 22px 0',
          borderTop: `0.5px solid ${W.lineSoft}`,
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          {onDelete && (
            <button onClick={onDelete} style={{
              padding: '13px 0', flex: 1,
              background: 'transparent', color: W.red,
              border: `0.5px solid ${W.line}`, borderRadius: 999, cursor: 'pointer',
              fontFamily: FONT_UI, fontSize: 13.5, fontWeight: 500,
            }}>{deleteLabel}</button>
          )}
          <button onClick={() => onSubmit(values)} style={{
            padding: '13px 0', flex: onDelete ? 2 : 1,
            background: W.ink, color: W.bg, border: 'none', borderRadius: 999,
            cursor: 'pointer',
            fontFamily: FONT_UI, fontSize: 14, fontWeight: 500,
          }}>{submitLabel}</button>
        </div>
      </div>

      <style>{`
        @keyframes wos-sheet-rise {
          from { transform: translateY(100%); }
          to   { transform: translateY(0); }
        }
        @keyframes wos-fade-in {
          from { opacity: 0; }
          to   { opacity: 1; }
        }
      `}</style>
    </>
  );
}

function FormField({ field, value, onChange, values }) {
  // Conditional visibility
  if (field.showWhen && !field.showWhen(values)) return null;

  const label = (
    <div style={{
      fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
      letterSpacing: 1.4, textTransform: 'uppercase', color: W.muted,
      marginBottom: 8,
    }}>{field.label}</div>
  );

  // Text
  if (field.type === 'text' || !field.type) {
    return (
      <div>
        {label}
        <input
          value={value || ''}
          onChange={(e) => onChange(e.target.value)}
          placeholder={field.placeholder}
          style={textInputStyle}
        />
        {field.hint && <div style={hintStyle}>{field.hint}</div>}
      </div>
    );
  }

  // Date — native date picker styled to match.
  if (field.type === 'date') {
    return (
      <div>
        {label}
        <input
          type="date"
          value={value || ''}
          onChange={(e) => onChange(e.target.value)}
          style={{ ...textInputStyle, fontFamily: FONT_UI }}/>
        {field.hint && <div style={hintStyle}>{field.hint}</div>}
      </div>
    );
  }

  // Color — native color picker + hex input.
  if (field.type === 'color') {
    return (
      <div>
        {label}
        <div style={{
          padding: '10px 14px',
          background: W.bg, border: `0.5px solid ${W.line}`, borderRadius: 12,
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <input
            type="color"
            value={value || '#cccccc'}
            onChange={(e) => onChange(e.target.value)}
            style={{
              width: 40, height: 40, padding: 0, border: 'none',
              background: 'transparent', cursor: 'pointer',
              borderRadius: 8,
            }}/>
          <input
            type="text"
            value={value || ''}
            onChange={(e) => onChange(e.target.value)}
            placeholder="#cccccc"
            style={{
              flex: 1, border: 'none', background: 'transparent', outline: 'none', padding: 0,
              fontFamily: FONT_MONO, fontSize: 14, color: W.ink, letterSpacing: 1.2,
            }}/>
        </div>
      </div>
    );
  }

  // Textarea
  if (field.type === 'textarea') {
    return (
      <div>
        {label}
        <textarea
          value={value || ''}
          onChange={(e) => onChange(e.target.value)}
          placeholder={field.placeholder}
          rows={field.rows || 3}
          style={{ ...textInputStyle, resize: 'none', fontFamily: FONT_UI }}
        />
      </div>
    );
  }

  // Number with stepper
  if (field.type === 'number') {
    const min = field.min ?? 0;
    const max = field.max ?? 99;
    const step = field.step ?? 1;
    return (
      <div>
        {label}
        <div style={{
          padding: '12px 14px',
          background: W.bg, border: `0.5px solid ${W.line}`, borderRadius: 12,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div style={{ fontFamily: FONT_UI, fontSize: 12.5, color: W.muted }}>
            {field.unit || ''}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <button onClick={() => onChange(Math.max(min, (value || 0) - step))} style={stepBtnStyle}>−</button>
            <div style={{
              fontFamily: FONT_DISPLAY, fontSize: 22, color: W.ink, minWidth: 32,
              textAlign: 'center', letterSpacing: -0.3,
            }}>{value}</div>
            <button onClick={() => onChange(Math.min(max, (value || 0) + step))} style={stepBtnStyle}>+</button>
          </div>
        </div>
      </div>
    );
  }

  // Toggle
  if (field.type === 'toggle') {
    return (
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div>
          <div style={{ fontFamily: FONT_UI, fontSize: 14, fontWeight: 500, color: W.ink }}>
            {field.label}
          </div>
          {field.hint && (
            <div style={{ fontFamily: FONT_UI, fontSize: 11.5, color: W.muted, marginTop: 2 }}>
              {field.hint}
            </div>
          )}
        </div>
        <button onClick={() => onChange(!value)} style={{
          width: 44, height: 26, borderRadius: 999,
          background: value ? W.ink : W.faint,
          border: 'none', cursor: 'pointer', padding: 0,
          position: 'relative', flexShrink: 0,
          transition: 'background 200ms ease',
        }}>
          <div style={{
            position: 'absolute', top: 2,
            left: value ? 20 : 2,
            width: 22, height: 22, borderRadius: 999, background: W.bg,
            transition: 'left 200ms ease',
            boxShadow: '0 1px 3px rgba(0,0,0,0.18)',
          }}/>
        </button>
      </div>
    );
  }

  // Choice — chips
  if (field.type === 'choice') {
    return (
      <div>
        {label}
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {(field.options || []).map(o => {
            const active = value === o.value;
            const accent = o.color || W.ink;
            return (
              <button key={String(o.value)} onClick={() => onChange(o.value)} style={{
                padding: '8px 14px',
                background: active ? accent : W.bg,
                color: active ? W.bg : W.ink2,
                border: `0.5px solid ${active ? accent : W.line}`,
                borderRadius: 999, cursor: 'pointer',
                fontFamily: FONT_UI, fontSize: 12.5, fontWeight: 500,
              }}>{o.label}</button>
            );
          })}
        </div>
      </div>
    );
  }

  // Multichoice
  if (field.type === 'multichoice') {
    const arr = Array.isArray(value) ? value : [];
    const toggle = (v) => onChange(arr.includes(v) ? arr.filter(x => x !== v) : [...arr, v]);
    return (
      <div>
        {label}
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {(field.options || []).map(o => {
            const active = arr.includes(o.value);
            const accent = o.color || W.ink;
            return (
              <button key={String(o.value)} onClick={() => toggle(o.value)} style={{
                padding: '8px 14px',
                background: active ? accent : W.bg,
                color: active ? W.bg : W.ink2,
                border: `0.5px solid ${active ? accent : W.line}`,
                borderRadius: 999, cursor: 'pointer',
                fontFamily: FONT_UI, fontSize: 12.5, fontWeight: 500,
              }}>{o.label}</button>
            );
          })}
        </div>
      </div>
    );
  }

  return null;
}

const textInputStyle = {
  width: '100%', padding: '12px 14px',
  background: W.bg, border: `0.5px solid ${W.line}`, borderRadius: 12,
  fontFamily: FONT_UI, fontSize: 15, color: W.ink,
  outline: 'none', boxSizing: 'border-box',
};

const hintStyle = {
  fontFamily: FONT_UI, fontSize: 11.5, color: W.muted, marginTop: 6,
};

const stepBtnStyle = {
  width: 32, height: 32, borderRadius: 999,
  background: W.card, border: `0.5px solid ${W.line}`,
  cursor: 'pointer', padding: 0,
  fontFamily: FONT_DISPLAY, fontSize: 18, color: W.ink, lineHeight: 1,
  display: 'flex', alignItems: 'center', justifyContent: 'center',
};

Object.assign(window, { FormSheet, FormField });
