// Logo & Appearance — tenant branding (tenants.settings.branding).
//
// Logos are a small library (up to 3 — e.g. full lockup, square mark,
// one-color) with a placement map deciding which shows where: in the app's
// top nav, on quote/invoice PDFs, and atop outgoing emails. Each logo
// travels as a data URI (PNG/JPEG, server-capped at 400 KB decoded). A
// placement left unassigned falls back to the first logo. Custom CSS is the
// deliberately-buried power feature: applied via textContent into a
// dedicated <style> tag (so it can't escape the stylesheet), and the server
// rejects external url()/@import so a stylesheet can never phone out.

const LOGO_CLIENT_MAX = 400 * 1024;   // mirror of the server cap, for a friendly early error
const LOGO_LIB_MAX    = 3;            // mirror of the server library cap

const LOGO_PLACEMENTS = [
    { key: 'app',   label: 'In the app',        icon: 'fa-desktop' },
    { key: 'docs',  label: 'Quotes & invoices', icon: 'fa-file-invoice' },
    { key: 'email', label: 'Emails',            icon: 'fa-envelope' },
];

const BrandingSection = ({ tenant, onTenantChange }) => {
    const branding = tenant?.branding || {};
    // Legacy single logo shows up as the first library entry, so nothing a
    // tenant uploaded before the library existed ever disappears on them.
    const initialLogos = Array.isArray(branding.logos) && branding.logos.length
        ? branding.logos
        : (branding.logo ? [{ id: 'logo-1', name: 'Logo 1', data: branding.logo }] : []);
    const [logos, setLogos]           = React.useState(initialLogos);
    const [placements, setPlacements] = React.useState(branding.placements || {});
    const [css, setCss]               = React.useState(branding.custom_css || '');
    const [showCss, setShowCss]       = React.useState(Boolean(branding.custom_css));
    const [saving, setSaving]         = React.useState(false);
    const [saved, setSaved]           = React.useState(false);
    const [error, setError]           = React.useState('');
    const [showStudio, setShowStudio] = React.useState(false);

    const addLogo = (dataUri, name) => {
        const id = `logo-${Date.now().toString(36)}`;
        setLogos(ls => [...ls, { id, name: name || `Logo ${ls.length + 1}`, data: dataUri }]);
        setSaved(false);
    };

    // Oversized uploads get DOWNSCALED here instead of rejected — a rep
    // shouldn't need an image editor to use their phone-camera logo. Contain-
    // fit within LOGO_FIT_PX, re-encoded as PNG; the server's dimension/byte
    // caps stay as the hard backstop.
    const LOGO_FIT_PX = 1600;
    const handleFile = (file) => {
        setError(''); setSaved(false);
        if (!file) return;
        if (logos.length >= LOGO_LIB_MAX) { setError(`You can keep up to ${LOGO_LIB_MAX} logos — remove one first.`); return; }
        if (!['image/png', 'image/jpeg'].includes(file.type)) { setError('Please choose a PNG or JPEG image.'); return; }
        const reader = new FileReader();
        reader.onload = () => {
            const img = new Image();
            img.onload = () => {
                let { width: w, height: h } = img;
                let data = reader.result;
                if (w > LOGO_FIT_PX || h > LOGO_FIT_PX) {
                    const scale = LOGO_FIT_PX / Math.max(w, h);
                    const canvas = document.createElement('canvas');
                    canvas.width = Math.round(w * scale); canvas.height = Math.round(h * scale);
                    canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);
                    data = canvas.toDataURL('image/png');
                }
                // Rough decoded size from the base64 length — mirrors the server cap.
                if ((data.length - data.indexOf(',') - 1) * 0.75 > LOGO_CLIENT_MAX) {
                    setError(`That image is too heavy even after resizing — max ${LOGO_CLIENT_MAX / 1024} KB. A simpler PNG works best.`);
                    return;
                }
                addLogo(data);
            };
            img.onerror = () => setError('That file could not be read as an image.');
            img.src = reader.result;
        };
        reader.readAsDataURL(file);
    };

    const removeLogo = (id) => {
        setLogos(ls => ls.filter(l => l.id !== id));
        // Placements pointing at a removed logo clear with it — the server
        // rejects dangling ids, and silently-broken is worse than unassigned.
        setPlacements(p => Object.fromEntries(Object.entries(p).map(([k, v]) => [k, v === id ? null : v])));
        setSaved(false);
    };

    const togglePlacement = (key, logoId) => {
        setPlacements(p => ({ ...p, [key]: p[key] === logoId ? null : logoId }));
        setSaved(false);
    };

    const renameLogo = (id, name) => {
        setLogos(ls => ls.map(l => l.id === id ? { ...l, name } : l));
        setSaved(false);
    };

    const handleSave = async () => {
        setSaving(true); setError(''); setSaved(false);
        try {
            const updated = await api.updateTenant({ branding: {
                logos,
                placements,
                logo: null,   // library is the source of truth once saved here
                custom_css: css.trim() ? css : null,
            } });
            onTenantChange && onTenantChange(updated);   // MainApp re-applies logo + CSS live
            setSaved(true);
        } catch (err) { setError(err.message); }
        finally { setSaving(false); }
    };

    return (
        <div className="settings-form">
            {error && <div className="api-error">{error}</div>}
            {saved && <div className="api-success"><i className="fas fa-check"></i> Saved — your workspace look is updated.</div>}

            <div className="form-section">
                <h4><i className="fas fa-image" style={{ marginRight: '0.375rem' }}></i>Company logos</h4>
                <p className="form-hint" style={{ marginTop: 0, marginBottom: '1rem' }}>
                    Keep up to {LOGO_LIB_MAX} versions of your logo and choose where each one shows.
                    A spot with nothing assigned uses your first logo. PNG or JPEG, up to 400 KB each.
                </p>

                {logos.length === 0 && (
                    <div className="logo-preview-box" style={{ marginBottom: '0.75rem' }}>
                        <span className="form-hint">No logos yet</span>
                    </div>
                )}

                <div className="logo-library">
                    {logos.map(l => (
                        <div key={l.id} className="logo-card">
                            <div className="logo-preview-box"><img src={l.data} alt={l.name || 'Logo'} /></div>
                            <input className="form-input logo-card-name" value={l.name || ''} maxLength={60}
                                   onChange={e => renameLogo(l.id, e.target.value)} placeholder="Name this logo" />
                            <div className="logo-card-placements">
                                {LOGO_PLACEMENTS.map(p => (
                                    <button key={p.key} type="button"
                                            className={`filter-chip ${placements[p.key] === l.id ? 'active' : ''}`}
                                            title={`Show this logo: ${p.label}`}
                                            onClick={() => togglePlacement(p.key, l.id)}>
                                        <i className={`fas ${p.icon}`} style={{ marginRight: '0.3rem' }}></i>{p.label}
                                    </button>
                                ))}
                            </div>
                            <button className="btn btn-secondary btn-small" onClick={() => removeLogo(l.id)}>
                                <i className="fas fa-times"></i> Remove
                            </button>
                        </div>
                    ))}
                </div>

                <div style={{ display: 'flex', gap: '0.5rem', marginTop: '0.75rem', flexWrap: 'wrap' }}>
                    {logos.length < LOGO_LIB_MAX && (
                        <label className="btn btn-secondary btn-small" style={{ cursor: 'pointer', display: 'inline-flex' }}>
                            <i className="fas fa-upload"></i> {logos.length ? 'Add another logo' : 'Upload a logo'}
                            <input type="file" accept="image/png,image/jpeg" style={{ display: 'none' }}
                                   onChange={e => { handleFile(e.target.files[0]); e.target.value = ''; }} />
                        </label>
                    )}
                    <button type="button" className="btn btn-secondary btn-small" onClick={() => setShowStudio(true)}>
                        <i className="fas fa-wand-magic-sparkles"></i> Create a basic logo
                    </button>
                </div>
            </div>

            {showStudio && (
                <LogoStudioModal
                    tenantName={tenant?.name}
                    defaultColor={tenant?.docs?.accent}
                    canAdd={logos.length < LOGO_LIB_MAX}
                    onAdd={addLogo}
                    onClose={() => setShowStudio(false)} />
            )}

            <div className="form-section">
                <button type="button" className="settings-advanced-toggle" onClick={() => setShowCss(s => !s)}>
                    <i className={`fas ${showCss ? 'fa-chevron-down' : 'fa-chevron-right'}`}></i>
                    Advanced: custom CSS
                </button>
                {showCss && (
                    <div style={{ marginTop: '0.75rem' }}>
                        <p className="form-hint" style={{ marginTop: 0, marginBottom: '0.75rem' }}>
                            For the adventurous: extra styling applied on top of your chosen theme, for
                            everyone in your workspace. If something looks broken afterwards, just clear
                            this box and save. External URLs and <code>@import</code> aren't allowed.
                        </p>
                        <textarea className="form-input form-textarea" style={{ fontFamily: 'monospace', fontSize: '0.8125rem', minHeight: 140 }}
                                  value={css} onChange={e => { setCss(e.target.value); setSaved(false); }}
                                  placeholder={'.rail { background: #14532d; }'} />
                    </div>
                )}
            </div>

            <div className="btn-group" style={{ marginTop: 0 }}>
                <button className="btn btn-primary" onClick={handleSave} disabled={saving}>
                    {saving ? <><i className="fas fa-spinner fa-spin"></i> Saving…</> : <><i className="fas fa-check"></i> Save</>}
                </button>
            </div>
        </div>
    );
};
