import React, { useState, useEffect, useRef, useCallback } from 'react';
import { MANAGEMENT_URL } from '../auth/authConfig';

// ─── Session-level cache — avoids repeat API calls ────────────
const _cache = new Map();

// ─── HelpIcon ─────────────────────────────────────────────────
// Usage:  <HelpIcon helpKey="client.wizard.budget" label="Budget" />
//
// helpKey format: {app}.{section}.{element}
//   client.wizard.objective    client.wizard.budget
//   client.wizard.audience     client.wizard.channels
// ─────────────────────────────────────────────────────────────
export default function HelpIcon({ helpKey, label }) {
    const [open, setOpen] = useState(false);
    const [content, setContent] = useState(null);   // { title, body }
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const modalRef = useRef(null);

    // ── Fetch on open ──
    const fetchContent = useCallback(async () => {
        if (_cache.has(helpKey)) {
            setContent(_cache.get(helpKey));
            return;
        }

        setLoading(true);
        setError(null);

        try {
            // /api/help is anonymous — no session token required
            const res = await fetch(`${MANAGEMENT_URL}/api/help/${encodeURIComponent(helpKey)}`);
            const data = await res.json();

            if (data.ok) {
                const entry = { title: data.title, body: data.body };
                _cache.set(helpKey, entry);
                setContent(entry);
            } else {
                setError(data.error || 'No help content available yet.');
            }
        } catch (err) {
            setError('Could not load help content.');
        } finally {
            setLoading(false);
        }
    }, [helpKey]);

    const handleOpen = () => {
        setOpen(true);
        fetchContent();
    };

    const handleClose = () => setOpen(false);

    // ── Close on Escape or outside click ──
    useEffect(() => {
        if (!open) return;

        const onKey = (e) => { if (e.key === 'Escape') handleClose(); };
        const onClick = (e) => {
            if (modalRef.current && !modalRef.current.contains(e.target)) handleClose();
        };

        document.addEventListener('keydown', onKey);
        document.addEventListener('mousedown', onClick);
        return () => {
            document.removeEventListener('keydown', onKey);
            document.removeEventListener('mousedown', onClick);
        };
    }, [open]);

    return (
        <>
            {/* ── Trigger: floating icon + label ── */}
            <button className="help-trigger" onClick={handleOpen} title={`Help: ${label || helpKey}`}>
                <span className="help-trigger-icon">
                    <svg width="14" height="14" viewBox="0 0 16 16" fill="none"
                        stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
                        <circle cx="8" cy="8" r="7" />
                        <path d="M6 6c0-1.1.9-2 2-2s2 .9 2 2c0 1-.6 1.5-1.3 2S8 9.5 8 10" />
                        <circle cx="8" cy="12.5" r=".75" fill="currentColor" stroke="none" />
                    </svg>
                </span>
                {label && <span className="help-trigger-label">{label}</span>}
            </button>

            {/* ── Modal ── */}
            {open && (
                <div className="help-overlay">
                    <div className="help-modal" ref={modalRef} role="dialog" aria-modal="true"
                        aria-label={content?.title || 'Help'}>

                        <div className="help-modal-header">
                            <div className="help-modal-title-row">
                                <span className="help-modal-icon">
                                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none"
                                        stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">
                                        <circle cx="8" cy="8" r="7" />
                                        <path d="M6 6c0-1.1.9-2 2-2s2 .9 2 2c0 1-.6 1.5-1.3 2S8 9.5 8 10" />
                                        <circle cx="8" cy="12.5" r=".75" fill="currentColor" stroke="none" />
                                    </svg>
                                </span>
                                <h3 className="help-modal-title">
                                    {loading ? 'Loading…' : (content?.title || 'Help')}
                                </h3>
                            </div>
                            <button className="help-modal-close" onClick={handleClose} aria-label="Close">
                                <svg width="16" height="16" viewBox="0 0 16 16" fill="none"
                                    stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                                    <path d="M3 3l10 10M13 3L3 13" />
                                </svg>
                            </button>
                        </div>

                        <div className="help-modal-body">
                            {loading && (
                                <div className="help-loading">
                                    <div className="help-spinner" />
                                    <span>Loading help…</span>
                                </div>
                            )}
                            {!loading && error && (
                                <p className="help-error">{error}</p>
                            )}
                            {!loading && content && (
                                <div
                                    className="help-content"
                                    dangerouslySetInnerHTML={{ __html: content.body }}
                                />
                            )}
                        </div>

                        <div className="help-modal-footer">
                            <span className="help-key-badge">{helpKey}</span>
                        </div>
                    </div>
                </div>
            )}
        </>
    );
}
