// Businesses — the platform operator's tenant console (is_platform only).
// Migrated from the AdminPanel drawer. Tenant users never see this section;
// the card itself is gated in SettingsView.

const PlatformSection = ({ currentUser }) => {
    const [tenants, setTenants]               = React.useState([]);
    const [tenantsLoading, setTenantsLoading] = React.useState(true);
    const [showOnboardForm, setShowOnboardForm] = React.useState(false);
    // invite tokens are shown ONCE (server stores only hashes) — keep the
    // freshest one per tenant in memory so the packet/link stay grabbable
    // until this screen is left.
    const [freshInvites, setFreshInvites]     = React.useState({});   // tenantId → { url, token, email }

    const loadTenants = () => {
        setTenantsLoading(true);
        api.getTenants().then(setTenants).catch(console.error).finally(() => setTenantsLoading(false));
    };
    React.useEffect(loadTenants, []);

    const handleOnboard = async (form) => {
        const r = await api.createTenant(form);
        setFreshInvites(p => ({ ...p, [r.tenant.id]: { url: r.invite_url, token: r.invite_token, email: r.email } }));
        setShowOnboardForm(false);
        loadTenants();
        return r;
    };

    const handleReinvite = async (tenant) => {
        try {
            const r = await api.reinviteTenant(tenant.id);
            setFreshInvites(p => ({ ...p, [tenant.id]: { url: r.invite_url, token: r.invite_token, email: r.email } }));
        } catch (err) { alert(err.message); }
    };

    const handleSuspend = async (tenant) => {
        const to = tenant.status === 'active' ? 'suspended' : 'active';
        if (to === 'suspended' && !window.confirm(`Suspend "${tenant.name}"? All their users will be locked out until reactivated.`)) return;
        try { await api.platformUpdateTenant(tenant.id, { status: to }); loadTenants(); }
        catch (err) { alert(err.message); }
    };

    // Authenticated PDF download → blob → save. (A bare <a href> would miss
    // the Authorization header.)
    const downloadPacket = async (tenant) => {
        const inviteTok = freshInvites[tenant.id]?.token;
        const res = await fetch(api.tenantPacketUrl(tenant.id, inviteTok), {
            headers: { Authorization: `Bearer ${getToken()}` },
        });
        if (!res.ok) { alert('Packet download failed.'); return; }
        const blob = await res.blob();
        const a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = `${tenant.slug}-onboarding-packet.pdf`;
        a.click();
        URL.revokeObjectURL(a.href);
    };

    return (
        <div className="settings-form">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem' }}>
                <p style={{ fontSize: '0.875rem', color: 'var(--text-3)' }}>
                    Each business gets its own isolated workspace. Onboarding creates the workspace,
                    its owner, an activation link, and the PDF welcome packet — one button.
                </p>
                <button className="btn btn-primary btn-small" onClick={() => setShowOnboardForm(s => !s)}>
                    <i className={`fas ${showOnboardForm ? 'fa-times' : 'fa-plus'}`}></i>
                    {showOnboardForm ? ' Cancel' : ' Onboard Business'}
                </button>
            </div>

            {showOnboardForm && (
                <div className="admin-form-card">
                    <h4 style={{ marginBottom: '1rem' }}>
                        <i className="fas fa-city" style={{ marginRight: '0.375rem' }}></i>New Business
                    </h4>
                    <OnboardTenantForm onSubmit={handleOnboard} onCancel={() => setShowOnboardForm(false)} />
                </div>
            )}

            {tenantsLoading ? (
                <div className="loading-state"><i className="fas fa-spinner fa-spin"></i> Loading…</div>
            ) : tenants.length === 0 ? (
                <p style={{ color: 'var(--text-3)', fontSize: '0.875rem' }}>No businesses yet — onboard the first one above.</p>
            ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
                    {tenants.map(t => (
                        <div key={t.id} className="team-card">
                            <div className="team-card-bar" style={{ background: t.status === 'active' ? 'var(--success)' : 'var(--text-3)' }}></div>
                            <div className="team-card-body">
                                <div className="team-card-header">
                                    <div>
                                        <span className="team-card-name">{t.name}</span>
                                        <span className="team-card-desc">
                                            {t.owner_email || 'no owner yet'} · {t.user_count} user{t.user_count === 1 ? '' : 's'} · {t.account_count} account{t.account_count === 1 ? '' : 's'}
                                            {t.pending_invites > 0 && <span style={{ color: 'var(--warning)' }}> · invite pending</span>}
                                            {t.status !== 'active' && <span style={{ color: 'var(--danger)' }}> · SUSPENDED</span>}
                                        </span>
                                    </div>
                                    <div style={{ display: 'flex', gap: '0.375rem' }}>
                                        <button className="btn-icon-sm" title="Download onboarding packet (PDF)" onClick={() => downloadPacket(t)}>
                                            <i className="fas fa-file-pdf"></i>
                                        </button>
                                        <button className="btn-icon-sm" title="Generate a fresh activation link" onClick={() => handleReinvite(t)}>
                                            <i className="fas fa-envelope-open-text"></i>
                                        </button>
                                        <button className="btn-icon-sm danger" title={t.status === 'active' ? 'Suspend business' : 'Reactivate business'} onClick={() => handleSuspend(t)}>
                                            <i className={`fas ${t.status === 'active' ? 'fa-ban' : 'fa-undo'}`}></i>
                                        </button>
                                    </div>
                                </div>
                                {freshInvites[t.id] && (
                                    <div className="note-box success" style={{ marginTop: '0.6rem' }}>
                                        {freshInvites[t.id].email?.sent ? (
                                            <div style={{ marginBottom: '0.375rem' }}>
                                                <i className="fas fa-paper-plane" style={{ color: 'var(--success)', marginRight: '0.375rem' }}></i>
                                                Welcome email + onboarding packet sent to <strong>{t.owner_email}</strong> from {freshInvites[t.id].email.from}.
                                            </div>
                                        ) : freshInvites[t.id].email ? (
                                            <div style={{ marginBottom: '0.375rem' }}>
                                                <i className="fas fa-triangle-exclamation" style={{ color: 'var(--warning)', marginRight: '0.375rem' }}></i>
                                                {freshInvites[t.id].email.reason === 'no_mailbox'
                                                    ? 'No mailbox connected — send the link + packet manually (Settings → Email to automate this).'
                                                    : "Welcome email didn't send — share the link + packet manually."}
                                            </div>
                                        ) : null}
                                        <strong>Activation link</strong> (single-use, 7 days — copy it now, it won't be shown again):<br />
                                        <code>{freshInvites[t.id].url}</code>
                                        <button className="btn btn-secondary btn-small" style={{ marginLeft: '0.5rem' }}
                                                onClick={() => navigator.clipboard.writeText(freshInvites[t.id].url)}>
                                            <i className="fas fa-copy"></i> Copy
                                        </button>
                                    </div>
                                )}
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
};

// Platform-operator intake form — the whole onboarding is these four fields.
const OnboardTenantForm = ({ onSubmit, onCancel }) => {
    const [form, setForm]   = React.useState({ business_name: '', owner_first: '', owner_last: '', owner_email: '' });
    const [error, setError] = React.useState('');
    const [saving, setSaving] = React.useState(false);
    const set = (k) => (e) => setForm(p => ({ ...p, [k]: e.target.value }));

    const handleSubmit = async (e) => {
        e.preventDefault();
        setSaving(true); setError('');
        try { await onSubmit(form); }
        catch (err) { setError(err.message); setSaving(false); }
    };

    return (
        <form onSubmit={handleSubmit}>
            {error && <div className="api-error" style={{ marginBottom: '0.75rem' }}>{error}</div>}
            <div className="form-grid">
                <div className="form-group full-width">
                    <label className="form-label">Business Name *</label>
                    <input type="text" className="form-input" value={form.business_name} onChange={set('business_name')} placeholder="e.g. Sunrise Cleaning Co" required autoFocus />
                </div>
                <div className="form-group">
                    <label className="form-label">Owner First Name *</label>
                    <input type="text" className="form-input" value={form.owner_first} onChange={set('owner_first')} required />
                </div>
                <div className="form-group">
                    <label className="form-label">Owner Last Name *</label>
                    <input type="text" className="form-input" value={form.owner_last} onChange={set('owner_last')} required />
                </div>
                <div className="form-group full-width">
                    <label className="form-label">Owner Email *</label>
                    <input type="email" className="form-input" value={form.owner_email} onChange={set('owner_email')} required />
                </div>
            </div>
            <div className="btn-group" style={{ marginTop: 0 }}>
                <button type="button" className="btn btn-secondary btn-small" onClick={onCancel} disabled={saving}>Cancel</button>
                <button type="submit" className="btn btn-primary btn-small" disabled={saving}>
                    {saving ? <><i className="fas fa-spinner fa-spin"></i> Creating workspace…</> : <><i className="fas fa-rocket"></i> Create Workspace</>}
                </button>
            </div>
        </form>
    );
};
