// Settings → Catalog — which Inventory this workspace gets, and its sizes.
//
// Style is a setting about the business (a pizza shop keeps a menu, a pedal
// maker keeps stock), not a status flag — so it's declared here, by the
// admin, and the operator can seed it at onboarding. Sizes are a controlled
// vocabulary (picked on the product form, never typed — 2026-08-09 rule).
// Server: PUT /api/tenant { catalog: { style, sizes } } → lib/catalog.js.

const CatalogSection = ({ tenant, onTenantChange }) => {
    const cur = (tenant && tenant.catalog) || { style: 'stock', sizes: [] };
    const [style, setStyle]   = React.useState(cur.style);
    const [sizes, setSizes]   = React.useState(cur.sizes || []);
    const [newSize, setNewSize] = React.useState('');
    const [saving, setSaving] = React.useState(false);
    const [error, setError]   = React.useState('');
    const [saved, setSaved]   = React.useState(false);

    const STARTER = ['Small', 'Medium', 'Large', 'X-Large'];
    const dirty = style !== cur.style || JSON.stringify(sizes) !== JSON.stringify(cur.sizes || []);

    const addSize = (e) => {
        e.preventDefault();
        const s = newSize.trim().replace(/\s+/g, ' ');
        if (!s) return;
        if (sizes.some(x => x.toLowerCase() === s.toLowerCase())) { setError(`"${s}" is already in the list.`); return; }
        if (sizes.length >= 12) { setError('Max 12 sizes.'); return; }
        setSizes([...sizes, s]); setNewSize(''); setError('');
    };
    const move = (i, d) => setSizes(arr => { const a = arr.slice(); const j = i + d; if (j < 0 || j >= a.length) return arr; [a[i], a[j]] = [a[j], a[i]]; return a; });

    const save = async () => {
        setSaving(true); setError(''); setSaved(false);
        try {
            const updated = await api.updateTenant({ catalog: { style, sizes } });
            onTenantChange && onTenantChange(updated);
            setSaved(true);
        } catch (err) { setError(err.message); }
        finally { setSaving(false); }
    };

    const chip = (on) => on ? { background: 'var(--accent, #3b82f6)', color: '#fff' } : {};
    return (
        <div className="settings-section">
            {error && <div className="api-error">{error}</div>}
            {saved && !dirty && <div className="api-success">Saved. The change shows the next time the Inventory view opens.</div>}

            <div className="form-group">
                <label className="form-label">Catalog style</label>
                <div className="tag-filter-row">
                    {[['stock', 'Stock', 'fa-boxes', 'SKU, cost, stock levels, reorder points, serial numbers — the full inventory.'],
                      ['menu',  'Menu',  'fa-utensils', 'Name, category, description, sizes, price, and whether it\'s on your website. No stock fields.']]
                      .map(([val, lbl, icon, blurb]) => (
                        <span key={val} className="tag-pill tag-filter-chip" style={chip(style === val)} title={blurb}
                              onClick={() => { setStyle(val); if (val === 'menu' && !sizes.length) setSizes(STARTER); }}>
                            <i className={`fas ${icon}`} style={{ marginRight: '0.3rem' }}></i>{lbl}
                        </span>
                    ))}
                </div>
                <p style={{ fontSize: '0.8125rem', color: 'var(--text-3)', marginTop: '0.35rem' }}>
                    {style === 'menu'
                        ? 'The Inventory view becomes “Menu”: items grouped by category with their sizes, and a one-click publish to your website. Switching back later loses nothing.'
                        : 'The classic inventory: stock quantities, costs, serial-number tracking and low-stock alerts, with website publishing alongside.'}
                </p>
            </div>

            <div className="form-group">
                <label className="form-label">Sizes</label>
                <p style={{ fontSize: '0.8125rem', color: 'var(--text-3)', margin: '0 0 0.5rem' }}>
                    When adding an item that comes in sizes, the form offers exactly this list and saves one item per size
                    (“Pepperoni – Large”). Order here is the order on the form. Leave it empty if nothing you sell comes in sizes.
                </p>
                {sizes.length > 0 && (
                    <table className="data-table" style={{ maxWidth: 420, marginBottom: '0.5rem' }}>
                        <tbody>
                            {sizes.map((s, i) => (
                                <tr key={s}>
                                    <td>{s}</td>
                                    <td style={{ textAlign: 'right', whiteSpace: 'nowrap' }}>
                                        <button type="button" className="btn-icon-sm" title="Move up" disabled={i === 0} onClick={() => move(i, -1)}><i className="fas fa-arrow-up"></i></button>
                                        <button type="button" className="btn-icon-sm" title="Move down" disabled={i === sizes.length - 1} onClick={() => move(i, 1)}><i className="fas fa-arrow-down"></i></button>
                                        <button type="button" className="btn-icon-sm danger" title="Remove (existing items keep their size in the name)" onClick={() => setSizes(sizes.filter((_, x) => x !== i))}><i className="fas fa-times"></i></button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                )}
                <form onSubmit={addSize} style={{ display: 'flex', gap: '0.5rem', maxWidth: 420 }}>
                    <input className="form-input" value={newSize} onChange={e => setNewSize(e.target.value)} placeholder="Add a size — e.g. Half, Whole, 12”" maxLength={30} />
                    <button type="submit" className="btn btn-secondary btn-small" disabled={!newSize.trim()}><i className="fas fa-plus"></i> Add</button>
                </form>
                {sizes.length === 0 && (
                    <button type="button" className="btn-link" style={{ marginTop: '0.5rem', fontSize: '0.8125rem' }} onClick={() => setSizes(STARTER)}>
                        Use Small / Medium / Large / X-Large
                    </button>
                )}
            </div>

            <div className="btn-group">
                <button type="button" className="btn btn-primary" disabled={saving || !dirty} onClick={save}>
                    {saving ? <><i className="fas fa-spinner fa-spin"></i> Saving…</> : <><i className="fas fa-check"></i> Save</>}
                </button>
            </div>
        </div>
    );
};
