// Website Leads — connect contact forms to the CRM.
//
// The intake-keys UI moved here from LeadsView (it always said "until the
// self-serve settings screens exist" — this is that screen). Keys are the
// trust anchor of the public POST /api/leads endpoint: label-only listing,
// plaintext shown exactly once at mint, revoke-not-delete.

const LeadsIntakeSection = () => {
    const [keys, setKeys]           = React.useState([]);
    const [newLabel, setNewLabel]   = React.useState('');
    const [mintedKey, setMintedKey] = React.useState(null);   // { label, key } — shown once
    const [busy, setBusy]           = React.useState(false);
    const [err, setErr]             = React.useState('');

    const loadKeys = () => api.getIntakeKeys().then(setKeys).catch(e => setErr(e.message));
    React.useEffect(() => { loadKeys(); }, []);

    const run = async (fn) => {
        setBusy(true); setErr('');
        try { await fn(); } catch (e) { setErr(e.message); }
        finally { setBusy(false); }
    };

    const mintKey = () => run(async () => {
        const k = await api.createIntakeKey(newLabel);
        setMintedKey({ label: k.label, key: k.key });
        setNewLabel('');
        await loadKeys();
    });
    const revokeKey = (k) => {
        if (!window.confirm(`Revoke "${k.label}"? Anything using it stops delivering immediately.`)) return;
        run(async () => { await api.revokeIntakeKey(k.id); await loadKeys(); });
    };

    return (
        <div className="settings-form">
            {err && <div className="api-error">{err}</div>}

            <div className="form-section">
                <h4><i className="fas fa-plug" style={{ marginRight: '0.375rem' }}></i>How it works</h4>
                <p className="form-hint" style={{ marginTop: 0 }}>
                    Your website (or whoever built it) sends each form submission to this CRM with
                    an <strong>intake key</strong> — and it appears in your Leads inbox automatically.
                    Give each website its own key so one can be turned off without touching the others.
                </p>
                <p className="form-hint">
                    The technical contract for your web developer lives in <code>docs/LEADS_INTAKE.md</code>:
                    a <code>POST /api/leads</code> with the key, plus name / email / phone / message.
                </p>
            </div>

            <div className="form-section">
                <h4><i className="fas fa-key" style={{ marginRight: '0.375rem' }}></i>Intake keys</h4>
                {mintedKey && (
                    <div className="api-success">
                        Key for <strong>{mintedKey.label}</strong> — copy it now, it won't be shown again:
                        <div style={{ fontFamily: 'monospace', marginTop: '0.4rem', wordBreak: 'break-all', userSelect: 'all' }}>{mintedKey.key}</div>
                        <button className="btn btn-secondary btn-small" style={{ marginTop: '0.5rem' }}
                            onClick={() => { navigator.clipboard.writeText(mintedKey.key).catch(() => {}); setMintedKey(null); }}>
                            <i className="fas fa-copy"></i> Copy & hide
                        </button>
                    </div>
                )}
                <div style={{ display: 'flex', gap: '0.5rem', marginBottom: '0.75rem' }}>
                    <input className="form-input" style={{ maxWidth: 280 }} placeholder="Label (e.g. company website)"
                        value={newLabel} onChange={e => setNewLabel(e.target.value)} />
                    <button className="btn btn-primary btn-small" disabled={busy || !newLabel.trim()} onClick={mintKey}>
                        <i className="fas fa-plus"></i> Create key
                    </button>
                </div>
                <table className="data-table">
                    <thead><tr><th>Label</th><th>Created</th><th>By</th><th>Status</th><th></th></tr></thead>
                    <tbody>
                        {keys.length === 0
                            ? <tr><td colSpan={5} style={{ textAlign: 'center', color: 'var(--text-3)', padding: '1rem' }}>No keys yet — create one to connect your first website.</td></tr>
                            : keys.map(k => (
                                <tr key={k.id}>
                                    <td style={{ fontWeight: 500 }}>{k.label}</td>
                                    <td>{formatDate(k.created_at)}</td>
                                    <td>{k.created_by_name || '—'}</td>
                                    <td>{k.revoked_at
                                        ? <span className="badge secondary">revoked</span>
                                        : <span className="badge success">active</span>}</td>
                                    <td>{!k.revoked_at && (
                                        <button className="btn-icon-sm danger" title="Revoke" onClick={() => revokeKey(k)}><i className="fas fa-ban"></i></button>
                                    )}</td>
                                </tr>
                            ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
};
