// TaskListEditor — the ONE editor for a "when a customer pays" task list
// ([{ title, notes }], the 0041 shape). Hosts: the product form's
// tasks_on_paid and Settings → Task Presets. Rows reorder with ↑/↓ buttons
// (deliberately not drag: rows hold text inputs, and drag handles on
// input-bearing rows fight text selection — PhotoGallery's caption trap).
//
// Props: tasks, onChange(nextTasks), max (default 15), presets (optional
// [{id,name,tasks}] — renders "Apply preset" chips that APPEND a copy of the
// preset's tasks; titles already present are skipped so combining Web + CRM
// never double-books a shared task).

const TASKS_ON_PAID_MAX = 15;

const TaskListEditor = ({ tasks, onChange, max = TASKS_ON_PAID_MAX, presets = null }) => {
    const list = tasks || [];
    const update = (next) => onChange(next);

    const addRow    = () => update([...list, { title: '', notes: '' }]);
    const removeRow = (i) => update(list.filter((_, x) => x !== i));
    const setField  = (i, key, val) => update(list.map((t, x) => x === i ? { ...t, [key]: val } : t));
    const 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]];
        update(next);
    };

    // Apply = append a COPY (snapshot doctrine — later preset edits never
    // reach this record). Dedupe by title, case-insensitive, matching the
    // server normalizer so what the user sees is what the API keeps.
    const applyPreset = (p) => {
        const have = new Set(list.map(t => (t.title || '').trim().toLowerCase()).filter(Boolean));
        const fresh = (p.tasks || []).filter(t => !have.has(t.title.toLowerCase()));
        update([...list, ...fresh.map(t => ({ title: t.title, notes: t.notes || '' }))].slice(0, max));
    };
    const presetApplied = (p) => {
        const have = new Set(list.map(t => (t.title || '').trim().toLowerCase()));
        return (p.tasks || []).length > 0 && p.tasks.every(t => have.has(t.title.toLowerCase()));
    };

    return (
        <div>
            {presets && presets.length > 0 && (
                <div className="tag-filter-row" style={{ alignItems: 'center', marginBottom: '0.5rem' }}>
                    <span style={{ fontSize: '0.75rem', color: 'var(--text-3)' }}>Apply preset:</span>
                    {presets.map(p => {
                        const on = presetApplied(p);
                        return (
                            <span key={p.id} className="tag-pill tag-filter-chip"
                                  style={on ? { background: 'var(--accent, #3b82f6)', color: '#fff', cursor: 'default' }
                                            : { cursor: 'pointer', opacity: 0.85 }}
                                  title={on ? 'All of this preset\'s tasks are on the list'
                                            : `Add ${p.tasks.length} task${p.tasks.length === 1 ? '' : 's'}: ${p.tasks.map(t => t.title).join(', ')}`}
                                  onClick={() => !on && applyPreset(p)}>
                                {p.name}{on && <i className="fas fa-check" style={{ marginLeft: '0.3rem', fontSize: '0.65rem' }}></i>}
                            </span>
                        );
                    })}
                </div>
            )}
            {list.map((t, i) => (
                <div key={i} style={{ display: 'flex', gap: '0.5rem', marginBottom: '0.4rem', alignItems: 'center' }}>
                    <span style={{ fontSize: '0.75rem', color: 'var(--text-3)', width: '1.2rem', textAlign: 'right' }}>{i + 1}.</span>
                    <input className="form-input" style={{ flex: '1 1 40%' }} maxLength={120}
                           value={t.title} placeholder="Task title — e.g. Deploy site and follow up"
                           onChange={e => setField(i, 'title', e.target.value)} />
                    <input className="form-input" style={{ flex: '1 1 50%' }} maxLength={500}
                           value={t.notes || ''} placeholder="Notes for the rep (optional)"
                           onChange={e => setField(i, 'notes', e.target.value)} />
                    <button type="button" className="btn btn-secondary btn-small" title="Move up"
                            disabled={i === 0} onClick={() => move(i, -1)}><i className="fas fa-arrow-up"></i></button>
                    <button type="button" className="btn btn-secondary btn-small" title="Move down"
                            disabled={i === list.length - 1} onClick={() => move(i, 1)}><i className="fas fa-arrow-down"></i></button>
                    <button type="button" className="btn btn-secondary btn-small" title="Remove task"
                            onClick={() => removeRow(i)}><i className="fas fa-times"></i></button>
                </div>
            ))}
            {list.length < max && (
                <button type="button" className="btn btn-secondary btn-small" onClick={addRow}>
                    <i className="fas fa-plus"></i> Add task
                </button>
            )}
        </div>
    );
};
