// Company Profile — business name + the letterhead block that prints on
// quote/invoice PDFs (tenants.settings.billing) + the shipping/ship-from
// location (tenants.settings.shipping). Structured city/state/ZIP fields
// (not one free-text line) because tax + shipping calculation will key off
// them — anything that needs a billing or shipping address reads from here.

const CompanySection = ({ tenant, onTenantChange }) => {
    const b  = tenant?.billing  || {};
    const sh = tenant?.shipping || {};
    const tm = tenant?.terms    || {};
    const [form, setForm] = React.useState({
        name:    tenant?.name || '',
        address: b.address || '', city: b.city || '', state: b.state || '',
        zip:     b.zip     || '', country: b.country || '',
        phone:   b.phone   || '', email: b.email || '', website: b.website || '',
        ship_same:    sh.same_as_billing !== false,   // default: ship-from = billing
        ship_address: sh.address || '', ship_city: sh.city || '', ship_state: sh.state || '',
        ship_zip:     sh.zip     || '', ship_country: sh.country || '',
        terms_version: tm.version || '', terms_text: tm.text || '',
    });
    const [saving, setSaving] = React.useState(false);
    const [saved, setSaved]   = React.useState(false);
    const [error, setError]   = React.useState('');
    const [tplBusy, setTplBusy] = React.useState(false);
    const set = (k) => (e) => { setForm(p => ({ ...p, [k]: e.target.value })); setSaved(false); };

    // Plan gate display (0035): server enforces; null entitlements = unlocked
    // (matches the UI convention everywhere else). Clearing existing terms
    // stays possible on any plan — no trapped config.
    const feats = tenant?.entitlements?.features;
    const termsLocked = !!feats && feats['terms.custom'] !== true;

    const handleInsertTemplate = async () => {
        if (form.terms_text.trim() &&
            !window.confirm('Replace the current terms text with the starter template?')) return;
        setTplBusy(true);
        try {
            const t = await api.getTermsTemplate();
            setForm(p => ({ ...p, terms_text: t.template, terms_version: p.terms_version || '1.0' }));
            setSaved(false);
        } catch (err) { setError(err.message); }
        finally { setTplBusy(false); }
    };

    const handleSave = async (e) => {
        e.preventDefault();
        setSaving(true); setError(''); setSaved(false);
        try {
            const payload = {
                name: form.name,
                billing: {
                    address: form.address, city: form.city, state: form.state,
                    zip: form.zip, country: form.country,
                    phone: form.phone, email: form.email, website: form.website,
                },
                shipping: {
                    same_as_billing: form.ship_same,
                    address: form.ship_address, city: form.ship_city, state: form.ship_state,
                    zip: form.ship_zip, country: form.ship_country,
                },
            };
            // Locked plans only ever send a CLEAR (allowed); sending the
            // unchanged text would 403 the whole save, blocking address edits.
            if (!termsLocked || (!form.terms_text.trim() && (tm.text || '').trim())) {
                payload.terms = { version: form.terms_version, text: form.terms_text };
            }
            const updated = await api.updateTenant(payload);
            onTenantChange && onTenantChange(updated);
            setSaved(true);
        } catch (err) { setError(err.message); }
        finally { setSaving(false); }
    };

    // One address block, used for both billing and shipping (prefix keys the
    // fields). Called as a plain function — NOT <AddressFields/> — because a
    // component defined inside render gets a new identity each render, which
    // remounts the inputs and drops focus on every keystroke.
    const addressFields = (p = '') => (
        <>
            <div className="form-group full-width">
                <label className="form-label">Street address</label>
                <input className="form-input" value={form[p + 'address']} onChange={set(p + 'address')} maxLength={500} placeholder="123 Main St, Suite 4" />
            </div>
            <div className="form-group">
                <label className="form-label">City</label>
                <input className="form-input" value={form[p + 'city']} onChange={set(p + 'city')} maxLength={100} placeholder="Springfield" />
            </div>
            <div className="form-group">
                <label className="form-label">State / Province</label>
                <input className="form-input" value={form[p + 'state']} onChange={set(p + 'state')} maxLength={100} placeholder="IL" />
            </div>
            <div className="form-group">
                <label className="form-label">ZIP / Postal code</label>
                <input className="form-input" value={form[p + 'zip']} onChange={set(p + 'zip')} maxLength={20} placeholder="62701" />
            </div>
            <div className="form-group">
                <label className="form-label">Country</label>
                <input className="form-input" value={form[p + 'country']} onChange={set(p + 'country')} maxLength={100} placeholder="USA" />
            </div>
        </>
    );

    return (
        <form onSubmit={handleSave} className="settings-form">
            {error && <div className="api-error">{error}</div>}
            {saved && <div className="api-success"><i className="fas fa-check"></i> Saved — new quotes and invoices will use these details.</div>}

            <div className="form-group" style={{ marginBottom: '1rem' }}>
                <label className="form-label">Business name</label>
                <input className="form-input" value={form.name} onChange={set('name')} maxLength={255} required />
                <p className="form-hint" style={{ marginTop: '0.375rem' }}>Shown across the CRM and at the top of your PDFs.</p>
            </div>

            <div className="form-section">
                <h4><i className="fas fa-file-invoice" style={{ marginRight: '0.375rem' }}></i>Business address &amp; letterhead</h4>
                <p className="form-hint" style={{ marginTop: 0, marginBottom: '1rem' }}>
                    Your billing address — it prints under your business name on every quote and invoice,
                    and it's what tax calculation will be based on. Leave anything blank to keep it off the documents.
                </p>
                <div className="form-grid">
                    {addressFields()}
                    <div className="form-group">
                        <label className="form-label">Phone</label>
                        <input className="form-input" value={form.phone} onChange={set('phone')} maxLength={50} placeholder="(555) 010-0000" />
                    </div>
                    <div className="form-group">
                        <label className="form-label">Email</label>
                        <input className="form-input" type="email" value={form.email} onChange={set('email')} maxLength={255} placeholder="billing@yourbusiness.com" />
                    </div>
                    <div className="form-group full-width">
                        <label className="form-label">Website</label>
                        <input className="form-input" value={form.website} onChange={set('website')} maxLength={255} placeholder="yourbusiness.com" />
                    </div>
                </div>
            </div>

            <div className="form-section">
                <h4><i className="fas fa-truck" style={{ marginRight: '0.375rem' }}></i>Shipping location</h4>
                <p className="form-hint" style={{ marginTop: 0, marginBottom: '0.75rem' }}>
                    Where you ship from — shipping and tax rules will use this as the origin.
                </p>
                {/* Chip toggle, not a checkbox (house rule) */}
                <div className="chip-row" style={{ display: 'flex', gap: '0.5rem', marginBottom: '1rem' }}>
                    {[[true, 'Same as billing address'], [false, 'Different location']].map(([val, label]) => (
                        <button key={String(val)} type="button"
                            className={`filter-chip ${form.ship_same === val ? 'active' : ''}`}
                            onClick={() => { setForm(p => ({ ...p, ship_same: val })); setSaved(false); }}>
                            {label}
                        </button>
                    ))}
                </div>
                {!form.ship_same && (
                    <div className="form-grid">
                        {addressFields('ship_')}
                    </div>
                )}
            </div>

            <div className="form-section">
                <h4><i className="fas fa-file-signature" style={{ marginRight: '0.375rem' }}></i>Service terms
                    {termsLocked && <span style={{ marginLeft: '0.5rem', fontSize: '0.75rem', color: 'var(--text-3)' }}><i className="fas fa-lock"></i> Paid plan</span>}
                </h4>
                <p className="form-hint" style={{ marginTop: 0, marginBottom: '0.5rem' }}>
                    The Terms of Service your customers agree to when they accept a quote online.
                    Shown in full on the accept page; the exact text and version are recorded with each
                    acceptance. <strong>Bump the version on any meaningful change</strong> — leave the text
                    empty to skip the terms step entirely.
                </p>
                <p className="form-hint" style={{ marginTop: 0, marginBottom: '1rem' }}>
                    <i className="fas fa-info-circle" style={{ marginRight: '0.25rem' }}></i>
                    Your terms are your own: we provide the mechanism and the acceptance records,
                    not legal advice. Have a legal professional review your terms before using them
                    with customers.
                </p>
                {termsLocked ? (
                    <p className="form-hint" style={{ marginBottom: '1rem' }}>
                        Setting custom service terms is part of the paid plan. Quotes and acceptance
                        work fully on your plan — customers simply accept without a terms step.
                        {form.terms_text && ' Your existing terms remain in force and can be cleared any time.'}
                    </p>
                ) : (
                    <div style={{ marginBottom: '0.75rem' }}>
                        <button type="button" className="btn btn-secondary btn-small" disabled={tplBusy}
                            onClick={handleInsertTemplate}>
                            <i className="fas fa-file-alt"></i> {tplBusy ? 'Loading…' : 'Insert starter template'}
                        </button>
                    </div>
                )}
                <div className="form-grid">
                    <div className="form-group">
                        <label className="form-label">Version</label>
                        <input className="form-input" value={form.terms_version} onChange={set('terms_version')}
                            maxLength={50} placeholder="1.0" disabled={termsLocked && !form.terms_text} />
                    </div>
                    <div className="form-group full-width">
                        <label className="form-label">Terms text</label>
                        <textarea className="form-input" value={form.terms_text} onChange={set('terms_text')}
                            rows={10} placeholder="Paste your service terms here…"
                            style={{ fontFamily: 'inherit', resize: 'vertical' }}
                            disabled={termsLocked && !form.terms_text} />
                    </div>
                </div>
            </div>

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