// Document Style — how quote & invoice PDFs look (tenants.settings.docs).
//
// The preview pane is the REAL renderer: every change POSTs the candidate
// settings to /api/tenant/doc-preview, which runs buildDocPdf on sample data
// and streams back an actual PDF. What you see here is byte-for-byte the
// engine customers' documents come from — no HTML mock-up to drift.

const DOC_FONT_OPTIONS = [
    { id: 'modern',     label: 'Modern',     hint: 'Clean sans-serif (Helvetica)' },
    { id: 'classic',    label: 'Classic',    hint: 'Traditional serif (Times)' },
    { id: 'typewriter', label: 'Typewriter', hint: 'Fixed-width (Courier)' },
];
const DOC_LOGO_SIZE_OPTIONS = [
    { id: 'small', label: 'Small' }, { id: 'medium', label: 'Medium' }, { id: 'large', label: 'Large' },
];
// Defaults mirror server DOC_DEFAULTS (Midnight look).
const DOC_DEFAULT_BRAND  = '#172647';
const DOC_DEFAULT_ACCENT = '#2563eb';
// Print-appropriate palettes — deep inks for headings, livelier for accents.
const DOC_BRAND_PALETTE  = ['#172647', '#1a1a2e', '#1f2937', '#312e81', '#14532d', '#4c1d24', '#7c2d12', '#3b0764', '#000000'];
const DOC_ACCENT_PALETTE = ['#2563eb', '#4f7cff', '#f59e0b', '#10b981', '#ef4444', '#8b5cf6', '#ec4899', '#14b8a6', '#6b7280'];

const DocStyleSection = ({ tenant, onTenantChange }) => {
    const saved = tenant?.docs || {};
    const [brand,  setBrand]  = React.useState(saved.brand  || DOC_DEFAULT_BRAND);
    const [accent, setAccent] = React.useState(saved.accent || DOC_DEFAULT_ACCENT);
    const [font,   setFont]   = React.useState(saved.font   || 'modern');
    const [zebra,  setZebra]  = React.useState(saved.zebra !== false);
    const [logoSize, setLogoSize] = React.useState(saved.logo_size || 'medium');
    const [footerText, setFooterText] = React.useState(saved.footer_text || '');
    const [previewUrl, setPreviewUrl]   = React.useState(null);
    const [previewBusy, setPreviewBusy] = React.useState(true);
    const [saving, setSaving]           = React.useState(false);
    const [savedOk, setSavedOk]         = React.useState(false);
    const [error, setError]             = React.useState('');

    const candidate = () => ({
        brand, accent, font, zebra, logo_size: logoSize,
        footer_text: footerText.trim() || null,
    });

    // Debounced live preview — re-render the sample PDF 400ms after the last
    // change. Old object URLs are revoked so a long tweaking session doesn't
    // leak a blob per click.
    React.useEffect(() => {
        setPreviewBusy(true);
        const timer = setTimeout(async () => {
            try {
                const url = await api.previewDocStyle(candidate());
                setPreviewUrl(old => { if (old) URL.revokeObjectURL(old); return url; });
                setError('');
            } catch (err) { setError(err.message); }
            finally { setPreviewBusy(false); }
        }, 400);
        return () => clearTimeout(timer);
    }, [brand, accent, font, zebra, logoSize, footerText]);

    const touch = (setter) => (v) => { setter(v); setSavedOk(false); };

    const handleSave = async () => {
        setSaving(true); setError(''); setSavedOk(false);
        try {
            const updated = await api.updateTenant({ docs: candidate() });
            onTenantChange && onTenantChange(updated);
            setSavedOk(true);
        } catch (err) { setError(err.message); }
        finally { setSaving(false); }
    };

    const handleReset = () => {
        setBrand(DOC_DEFAULT_BRAND); setAccent(DOC_DEFAULT_ACCENT); setFont('modern');
        setZebra(true); setLogoSize('medium'); setFooterText('');
        setSavedOk(false);
    };

    const chipRow = (options, value, onPick) => (
        <div className="docstyle-font-chips">
            {options.map(o => (
                <button key={o.id} type="button"
                        className={`filter-chip ${value === o.id ? 'active' : ''}`}
                        title={o.hint || ''}
                        onClick={() => onPick(o.id)}>
                    {o.label}
                </button>
            ))}
        </div>
    );

    return (
        <div className="settings-form">
            {error && <div className="api-error">{error}</div>}
            {savedOk && <div className="api-success"><i className="fas fa-check"></i> Saved — new quotes and invoices will use this look.</div>}

            <div className="docstyle-layout">
                <div className="docstyle-controls">
                    <div className="form-section">
                        <h4><i className="fas fa-heading" style={{ marginRight: '0.375rem' }}></i>Heading color</h4>
                        <p className="form-hint" style={{ marginTop: 0 }}>Your business name and the table header band.</p>
                        <ColorSwatchPicker value={brand} onChange={touch(setBrand)} palette={DOC_BRAND_PALETTE} />
                    </div>

                    <div className="form-section">
                        <h4><i className="fas fa-fill-drip" style={{ marginRight: '0.375rem' }}></i>Accent color</h4>
                        <p className="form-hint" style={{ marginTop: 0 }}>The big QUOTE / INVOICE title and the divider line.</p>
                        <ColorSwatchPicker value={accent} onChange={touch(setAccent)} palette={DOC_ACCENT_PALETTE} />
                    </div>

                    <div className="form-section">
                        <h4><i className="fas fa-font" style={{ marginRight: '0.375rem' }}></i>Font</h4>
                        {chipRow(DOC_FONT_OPTIONS, font, touch(setFont))}
                        <p className="form-hint">{DOC_FONT_OPTIONS.find(f => f.id === font)?.hint}</p>
                    </div>

                    <div className="form-section">
                        <h4><i className="fas fa-table" style={{ marginRight: '0.375rem' }}></i>Row stripes</h4>
                        {chipRow([{ id: 'on', label: 'Striped' }, { id: 'off', label: 'Plain' }],
                                 zebra ? 'on' : 'off', (v) => touch(setZebra)(v === 'on'))}
                    </div>

                    <div className="form-section">
                        <h4><i className="fas fa-expand-arrows-alt" style={{ marginRight: '0.375rem' }}></i>Logo size</h4>
                        {chipRow(DOC_LOGO_SIZE_OPTIONS, logoSize, touch(setLogoSize))}
                    </div>

                    <div className="form-section">
                        <h4><i className="fas fa-shoe-prints" style={{ marginRight: '0.375rem' }}></i>Footer line</h4>
                        <p className="form-hint" style={{ marginTop: 0 }}>
                            Optional fine print at the bottom of every document — tax ID, payment
                            terms, or a thank-you. Max 300 characters.
                        </p>
                        <textarea className="form-input form-textarea" style={{ minHeight: 60 }} maxLength={300}
                                  value={footerText} onChange={e => touch(setFooterText)(e.target.value)}
                                  placeholder="Thank you for your business! · Tax ID 00-0000000" />
                    </div>

                    <p className="form-hint">
                        Which logo prints here is set in <strong>Logo &amp; Appearance</strong> —
                        the preview already uses your "Quotes &amp; invoices" logo and letterhead.
                    </p>

                    <div className="btn-group" style={{ marginTop: '0.5rem' }}>
                        <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>
                        <button className="btn btn-secondary" onClick={handleReset}>
                            <i className="fas fa-undo"></i> Reset to default
                        </button>
                    </div>
                </div>

                <div className="docstyle-preview">
                    <div className="docstyle-preview-label">
                        Live preview {previewBusy && <i className="fas fa-spinner fa-spin" style={{ marginLeft: '0.375rem' }}></i>}
                    </div>
                    {previewUrl
                        ? <iframe title="Document preview" src={`${previewUrl}#toolbar=0&navpanes=0`} />
                        : <div className="docstyle-preview-empty">{error ? 'Preview unavailable' : 'Rendering…'}</div>}
                </div>
            </div>
        </div>
    );
};
