// Logo & Appearance — tenant branding (tenants.settings.branding).
//
// Logo travels as a data URI (PNG/JPEG, server-capped at 400 KB decoded) —
// it shows in the top nav for everyone in the workspace and on PDF
// letterheads. 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 BrandingSection = ({ tenant, onTenantChange }) => {
    const branding = tenant?.branding || {};
    const [logoPreview, setLogoPreview] = React.useState(branding.logo || null);
    const [logoDirty, setLogoDirty]     = React.useState(false);
    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 handleFile = (file) => {
        setError(''); setSaved(false);
        if (!file) return;
        if (!['image/png', 'image/jpeg'].includes(file.type)) { setError('Please choose a PNG or JPEG image.'); return; }
        if (file.size > LOGO_CLIENT_MAX) { setError(`That image is too large — max ${LOGO_CLIENT_MAX / 1024} KB. Tip: a logo around 400×100 px is plenty.`); return; }
        const reader = new FileReader();
        reader.onload = () => { setLogoPreview(reader.result); setLogoDirty(true); };
        reader.readAsDataURL(file);
    };

    const handleSave = async () => {
        setSaving(true); setError(''); setSaved(false);
        try {
            const patch = { branding: {} };
            if (logoDirty) patch.branding.logo = logoPreview;                 // null = remove
            patch.branding.custom_css = css.trim() ? css : null;
            const updated = await api.updateTenant(patch);
            onTenantChange && onTenantChange(updated);   // MainApp re-applies logo + CSS live
            setLogoDirty(false);
            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 logo</h4>
                <p className="form-hint" style={{ marginTop: 0, marginBottom: '1rem' }}>
                    Shows in the top bar for everyone in your workspace and on your quote and
                    invoice PDFs. PNG or JPEG, up to 400 KB.
                </p>
                <div style={{ display: 'flex', gap: '1.25rem', alignItems: 'center', flexWrap: 'wrap' }}>
                    <div className="logo-preview-box">
                        {logoPreview
                            ? <img src={logoPreview} alt="Your logo" />
                            : <span className="form-hint">No logo yet</span>}
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                        <label className="btn btn-secondary btn-small" style={{ cursor: 'pointer' }}>
                            <i className="fas fa-upload"></i> {logoPreview ? 'Replace logo' : 'Upload logo'}
                            <input type="file" accept="image/png,image/jpeg" style={{ display: 'none' }}
                                   onChange={e => { handleFile(e.target.files[0]); e.target.value = ''; }} />
                        </label>
                        {logoPreview && (
                            <button className="btn btn-secondary btn-small" onClick={() => { setLogoPreview(null); setLogoDirty(true); setSaved(false); }}>
                                <i className="fas fa-times"></i> Remove logo
                            </button>
                        )}
                    </div>
                </div>
            </div>

            <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={'.top-nav { 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>
    );
};
