// 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 [newKind, setNewKind]     = React.useState('public'); // most keys connect a website directly
    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, newKind);
        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(); });
    };

    // ── Notification emails (chip editor per key) ────────────────────────────
    // notify.email_to is a string (one) or array (several); empty = leads land
    // in the inbox silently. Edited as chips + an add-input, saved per key.
    const [editNotify, setEditNotify] = React.useState(null); // { keyId, emails: [], input: '' }
    const notifyEmails = (k) => {
        const v = k.notify?.email_to;
        return Array.isArray(v) ? v : (v ? [v] : []);
    };
    const startNotifyEdit = (k) => setEditNotify({ keyId: k.id, emails: notifyEmails(k), input: '' });
    const addNotifyEmail = () => {
        const e = editNotify.input.trim().toLowerCase();
        if (!e) return;
        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)) { setErr(`Not a valid address: ${e}`); return; }
        setErr('');
        setEditNotify(prev => ({ ...prev, emails: [...new Set([...prev.emails, e])], input: '' }));
    };
    const saveNotify = () => run(async () => {
        // Count anything still sitting in the input as intended (typed, not yet Entered).
        const pending = editNotify.input.trim() ? [...editNotify.emails, editNotify.input.trim().toLowerCase()] : editNotify.emails;
        await api.setIntakeKeyNotify(editNotify.keyId, pending);
        setEditNotify(null);
        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>
                        {/* Hide ONLY after a confirmed copy — this key is shown once, so a
                            failed clipboard write must not destroy it. */}
                        <button className="btn btn-secondary btn-small" style={{ marginTop: '0.5rem' }}
                            onClick={async () => {
                                try { await navigator.clipboard.writeText(mintedKey.key); setMintedKey(null); }
                                catch { alert('Copy failed — select the key text and copy it by hand before dismissing.'); }
                            }}>
                            <i className="fas fa-copy"></i> Copy & hide
                        </button>
                    </div>
                )}
                <div style={{ display: 'flex', gap: '0.5rem', marginBottom: '0.5rem', flexWrap: 'wrap', alignItems: 'center' }}>
                    <input className="form-input" style={{ maxWidth: 280 }} placeholder="Label (e.g. company website)"
                        value={newLabel} onChange={e => setNewLabel(e.target.value)} />
                    {/* Key kind as pills (Stripe's publishable/secret split). */}
                    <div style={{ display: 'flex', gap: '0.375rem' }}>
                        {[['public', 'Website (embeddable)'], ['secret', 'Server-side (secret)']].map(([kind, text]) => (
                            <button key={kind} type="button"
                                className={`btn btn-small ${newKind === kind ? 'btn-primary' : 'btn-secondary'}`}
                                onClick={() => setNewKind(kind)}>{text}</button>
                        ))}
                    </div>
                    <button className="btn btn-primary btn-small" disabled={busy || !newLabel.trim()} onClick={mintKey}>
                        <i className="fas fa-plus"></i> Create key
                    </button>
                </div>
                <p className="form-hint" style={{ marginTop: 0 }}>
                    <strong>Website</strong> keys (<code>crmp_</code>) are safe to put right in your site's
                    form code — the worst a copycat can do is send you leads, and you can revoke it.
                    <strong> Server-side</strong> keys (<code>crmk_</code>) are for systems that hold
                    secrets properly — never in a browser or a public repo.
                </p>
                <table className="data-table">
                    <thead><tr><th>Label</th><th>Type</th><th>Created</th><th>Lead emails</th><th>Status</th><th></th></tr></thead>
                    <tbody>
                        {keys.length === 0
                            ? <tr><td colSpan={6} 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><span className="badge secondary">{k.kind === 'public' ? 'website' : 'server-side'}</span></td>
                                    <td>{formatDate(k.created_at)}</td>
                                    <td>
                                        {editNotify?.keyId === k.id ? (
                                            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.25rem', alignItems: 'center', maxWidth: 320 }}>
                                                {editNotify.emails.map(e => (
                                                    <span key={e} className="badge secondary" style={{ display: 'inline-flex', alignItems: 'center', gap: '0.25rem' }}>
                                                        {e}
                                                        <i className="fas fa-times" style={{ cursor: 'pointer' }}
                                                           onClick={() => setEditNotify(prev => ({ ...prev, emails: prev.emails.filter(x => x !== e) }))}></i>
                                                    </span>
                                                ))}
                                                <input className="form-input" style={{ width: 170, padding: '0.2rem 0.4rem' }} placeholder="add email, Enter"
                                                    value={editNotify.input} autoFocus
                                                    onChange={e => setEditNotify(prev => ({ ...prev, input: e.target.value }))}
                                                    onKeyDown={e => { if (e.key === 'Enter' || e.key === ',') { e.preventDefault(); addNotifyEmail(); } }} />
                                                <button className="btn btn-primary btn-small" disabled={busy} onClick={saveNotify}>Save</button>
                                                <button className="btn btn-secondary btn-small" onClick={() => { setEditNotify(null); setErr(''); }}>Cancel</button>
                                            </div>
                                        ) : (
                                            <span className={notifyEmails(k).length ? '' : 'text-muted'}
                                                  style={{ cursor: k.revoked_at ? 'default' : 'pointer' }}
                                                  title={k.revoked_at ? undefined : 'Click to edit who gets emailed when a lead arrives'}
                                                  onClick={() => !k.revoked_at && startNotifyEdit(k)}>
                                                {notifyEmails(k).length
                                                    ? notifyEmails(k).join(', ')
                                                    : <span style={{ color: 'var(--text-3)' }}>inbox only <i className="fas fa-pen" style={{ fontSize: '0.7rem', marginLeft: '0.25rem' }}></i></span>}
                                            </span>
                                        )}
                                    </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>
                <p className="form-hint">
                    <strong>Lead emails:</strong> who gets an email the moment a lead arrives on that
                    key (the visitor's address is set as reply-to). Leave it on "inbox only" and leads
                    just land in the Leads inbox quietly. Up to 5 addresses per website.
                </p>
            </div>
        </div>
    );
};
