/* === library.jsx ====================================================
   Login screen + Demo library home page for UpFlux Studio.
   ===================================================================== */

const DEFAULT_STUDIO_PASSWORD = 'upflux2026';

/* Read the current password from localStorage; falls back to the default
   on first run. Persisted plain (no hashing) — this is a soft access
   gate for sales team, not a security boundary. */
function getStudioPassword() {
    try {
        const stored = localStorage.getItem('studio_password');
        return (stored && stored.length > 0) ? stored : DEFAULT_STUDIO_PASSWORD;
    } catch { return DEFAULT_STUDIO_PASSWORD; }
}
function setStudioPassword(next) {
    try { localStorage.setItem('studio_password', next); } catch {}
}

/* ==================================================================
   LOGIN SCREEN
   ================================================================== */
function LoginScreen({ onAuth }) {
    const [pwd, setPwd] = React.useState('');
    const [err, setErr] = React.useState(false);
    const submit = (e) => {
        e?.preventDefault();
        if (pwd === getStudioPassword()) onAuth();
        else { setErr(true); setTimeout(() => setErr(false), 1800); }
    };

    return (
        <div className="login-screen">
            <div className="login-bg">
                <div className="login-grid-blob" />
            </div>
            <form className="login-card" onSubmit={submit}>
                <div className="login-brand">
                    <span className="mark-wrap">U</span>
                    <span>UpFlux <span style={{ color: 'var(--text-tertiary)', fontWeight: 400 }}>Studio</span></span>
                </div>
                <h1 className="login-title">Acessar o editor de demos</h1>
                <p className="login-sub">
                    Apenas AEs e Sales Engineers da UpFlux. O acesso público à demo
                    do prospect não exige senha.
                </p>
                <div className={`login-field${err ? ' shake' : ''}`}>
                    <label>Senha</label>
                    <input
                        type="password"
                        autoFocus
                        value={pwd}
                        onChange={(e) => setPwd(e.target.value)}
                        placeholder="••••••••"
                    />
                </div>
                {err && (
                    <div className="login-err">
                        <Icon name="alert-triangle" size={12} />
                        Senha incorreta — tente novamente
                    </div>
                )}
                <button type="submit" className="tbtn tbtn--primary login-submit">
                    <Icon name="arrow-right" size={12} />
                    Entrar no Studio
                </button>
                <div className="login-foot">
                    <span className="login-version">
                        Studio {window.STUDIO_DATA.STUDIO_VERSION} · build {window.STUDIO_DATA.STUDIO_BUILD_DATE}
                    </span>
                </div>
            </form>
        </div>
    );
}

/* ==================================================================
   LIBRARY SCREEN
   ================================================================== */
function LibraryScreen({ library, onOpen, onClone, onDelete, onCreate, onLogout }) {
    const [filter, setFilter] = React.useState('all');
    const [query, setQuery] = React.useState('');
    const [menuOpenId, setMenuOpenId] = React.useState(null);
    const [showNewForm, setShowNewForm] = React.useState(false);
    const [showSettings, setShowSettings] = React.useState(false);
    const [showAnswers, setShowAnswers] = React.useState(false);
    const [showAgents, setShowAgents] = React.useState(false);
    const [showHotspots, setShowHotspots] = React.useState(false);

    React.useEffect(() => {
        const close = () => setMenuOpenId(null);
        window.addEventListener('click', close);
        return () => window.removeEventListener('click', close);
    }, []);

    const filtered = library.filter(d => {
        if (filter !== 'all' && d.status !== filter) return false;
        if (query && !`${d.name} ${d.prospect} ${d.industry}`.toLowerCase().includes(query.toLowerCase())) return false;
        return true;
    });

    const counts = {
        all: library.length,
        draft: library.filter(d => d.status === 'draft').length,
        ready: library.filter(d => d.status === 'ready').length,
        shared: library.filter(d => d.status === 'shared').length,
    };

    return (
        <div className="lib-screen">
            <header className="lib-header">
                <div className="lib-header-left">
                    <div className="studio-brand">
                        <span className="mark-wrap">U</span>
                        <span className="name">UpFlux <span className="dim">Studio</span></span>
                    </div>
                    <span className="lib-version-chip">
                        {window.STUDIO_DATA.STUDIO_VERSION}
                    </span>
                </div>
                <div className="lib-header-right">
                    <a href="https://nous.upflux.ai" target="_blank" rel="noopener" className="tbtn">
                        <Icon name="arrow-right" size={12} />
                        Abrir Nous
                    </a>
                    <button className="tbtn" onClick={() => setShowAnswers(true)}>
                        <Icon name="message-circle" size={12} />
                        Respostas P2P
                    </button>
                    <button className="tbtn" onClick={() => setShowAgents(true)}>
                        <Icon name="briefcase" size={12} />
                        Agentes
                    </button>
                    <button className="tbtn" onClick={() => setShowHotspots(true)}>
                        <Icon name="sparkles" size={12} />
                        Hotspots
                    </button>
                    <button className="tbtn" onClick={() => setShowSettings(true)}>
                        <Icon name="settings" size={12} />
                        Configurações
                    </button>
                    <button className="tbtn" onClick={onLogout}>
                        <Icon name="arrow-right" size={12} style={{ transform: 'rotate(180deg)' }} />
                        Sair
                    </button>
                </div>
            </header>

            <div className="lib-hero">
                <div>
                    <h1 className="lib-h1">Biblioteca de demos</h1>
                    <p className="lib-sub">
                        Crie uma demo nova, abra uma existente ou clone para começar
                        rápido a partir de um template.
                    </p>
                </div>
                <button className="lib-new-btn" onClick={() => setShowNewForm(true)}>
                    <Icon name="plus" size={14} />
                    Nova demo
                </button>
            </div>

            <div className="lib-toolbar">
                <div className="lib-filters">
                    {[
                        { id: 'all',    label: 'Todas' },
                        { id: 'draft',  label: 'Rascunho' },
                        { id: 'ready',  label: 'Prontas' },
                        { id: 'shared', label: 'Compartilhadas' },
                    ].map(f => (
                        <button
                            key={f.id}
                            className={`lib-filter${filter === f.id ? ' active' : ''}`}
                            onClick={() => setFilter(f.id)}
                        >
                            {f.label}
                            <span className="lib-filter-count">{counts[f.id]}</span>
                        </button>
                    ))}
                </div>
                <div className="lib-search">
                    <Icon name="search" size={13} style={{ color: 'var(--text-muted)' }} />
                    <input
                        placeholder="Buscar prospect, indústria…"
                        value={query}
                        onChange={(e) => setQuery(e.target.value)}
                    />
                </div>
            </div>

            <div className="lib-grid">
                {filtered.map((d) => (
                    <DemoCard
                        key={d.id}
                        demo={d}
                        menuOpen={menuOpenId === d.id}
                        onToggleMenu={(e) => { e.stopPropagation(); setMenuOpenId(menuOpenId === d.id ? null : d.id); }}
                        onOpen={() => onOpen(d.id)}
                        onClone={() => { onClone(d.id); setMenuOpenId(null); }}
                        onDelete={() => {
                            if (confirm(`Excluir a demo "${d.name}"? Esta ação não pode ser desfeita.`)) {
                                onDelete(d.id);
                            }
                            setMenuOpenId(null);
                        }}
                    />
                ))}
                <button className="lib-card lib-card--add" onClick={() => setShowNewForm(true)}>
                    <span className="lib-card-add-icon">
                        <Icon name="plus" size={20} />
                    </span>
                    <span className="lib-card-add-label">Criar nova demo</span>
                    <span className="lib-card-add-sub">Em branco ou a partir de um template</span>
                </button>
            </div>

            {filtered.length === 0 && (
                <div className="lib-empty">
                    <Icon name="search" size={18} style={{ color: 'var(--text-muted)' }} />
                    <span>Nenhuma demo encontrada para esses filtros.</span>
                </div>
            )}

            {showNewForm && (
                <NewDemoModal
                    library={library}
                    onClose={() => setShowNewForm(false)}
                    onCreate={(name) => { setShowNewForm(false); onCreate(name); }}
                    onClone={(id) => { setShowNewForm(false); onClone(id); }}
                />
            )}
            {showSettings && (
                <SettingsModal onClose={() => setShowSettings(false)} />
            )}
            {showAnswers && (
                <StandardAnswersAdmin onClose={() => setShowAnswers(false)} />
            )}
            {showAgents && (
                <AgentsMediaAdmin onClose={() => setShowAgents(false)} />
            )}
            {showHotspots && (
                <HotspotsAdmin onClose={() => setShowHotspots(false)} />
            )}
        </div>
    );
}

/* ==================================================================
   SETTINGS MODAL — change password + studio info
   ================================================================== */
function SettingsModal({ onClose }) {
    const [current, setCurrent] = React.useState('');
    const [next, setNext] = React.useState('');
    const [confirm, setConfirm] = React.useState('');
    const [feedback, setFeedback] = React.useState(null);  /* { kind: 'ok'|'err', msg } */
    const [show, setShow] = React.useState(false);

    const submit = (e) => {
        e?.preventDefault();
        const stored = getStudioPassword();
        if (current !== stored) {
            setFeedback({ kind: 'err', msg: 'Senha atual incorreta.' });
            return;
        }
        if (!next || next.length < 4) {
            setFeedback({ kind: 'err', msg: 'A nova senha precisa ter ao menos 4 caracteres.' });
            return;
        }
        if (next !== confirm) {
            setFeedback({ kind: 'err', msg: 'A confirmação não bate com a nova senha.' });
            return;
        }
        setStudioPassword(next);
        setFeedback({ kind: 'ok', msg: 'Senha atualizada. Use a nova senha na próxima vez que entrar.' });
        setCurrent(''); setNext(''); setConfirm('');
    };

    const reset = () => {
        if (confirm('Restaurar a senha padrão "upflux2026"?')) {
            try { localStorage.removeItem('studio_password'); } catch {}
            setFeedback({ kind: 'ok', msg: 'Senha restaurada para o padrão "upflux2026".' });
        }
    };

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal" onClick={(e) => e.stopPropagation()}>
                <div className="modal-head">
                    <div>
                        <div className="modal-title">Configurações do Studio</div>
                        <div className="modal-sub">
                            Acesso interno · {window.STUDIO_DATA.STUDIO_VERSION} · build {window.STUDIO_DATA.STUDIO_BUILD_DATE}
                        </div>
                    </div>
                    <button className="modal-close" onClick={onClose}>
                        <Icon name="plus" size={16} style={{ transform: 'rotate(45deg)' }} />
                    </button>
                </div>
                <form className="modal-body" onSubmit={submit}>
                    <div className="share-section">
                        <div className="share-label">
                            Senha do editor
                            <span className="share-label-hint">
                                Quem precisa entrar em <strong>{location.host || 'demo.upflux.ai'}</strong> usa esta senha.
                                Persiste no navegador — cada AE precisa configurar a sua vez ou compartilhar.
                            </span>
                        </div>
                        <div className="settings-fields">
                            <label className="settings-row">
                                <span>Senha atual</span>
                                <input
                                    type={show ? 'text' : 'password'}
                                    className="f-input"
                                    value={current}
                                    onChange={(e) => setCurrent(e.target.value)}
                                    placeholder="A senha que você usa hoje"
                                    autoFocus
                                />
                            </label>
                            <label className="settings-row">
                                <span>Nova senha</span>
                                <input
                                    type={show ? 'text' : 'password'}
                                    className="f-input"
                                    value={next}
                                    onChange={(e) => setNext(e.target.value)}
                                    placeholder="Mín. 4 caracteres"
                                />
                            </label>
                            <label className="settings-row">
                                <span>Confirmar nova senha</span>
                                <input
                                    type={show ? 'text' : 'password'}
                                    className="f-input"
                                    value={confirm}
                                    onChange={(e) => setConfirm(e.target.value)}
                                    placeholder="Repita a nova senha"
                                />
                            </label>
                            <label className="settings-show">
                                <input type="checkbox" checked={show} onChange={(e) => setShow(e.target.checked)} />
                                <span>Mostrar senhas</span>
                            </label>
                        </div>
                        {feedback && (
                            <div className={`settings-feedback ${feedback.kind}`}>
                                <Icon name={feedback.kind === 'ok' ? 'check-circle' : 'alert-triangle'} size={12} />
                                {feedback.msg}
                            </div>
                        )}
                    </div>

                    <div className="share-section">
                        <div className="share-label">Resetar senha</div>
                        <div className="share-hint" style={{ marginBottom: 8 }}>
                            Esqueceu a senha? Restaure para a padrão de fábrica (qualquer pessoa no
                            time pode entrar com <code>upflux2026</code> e configurar a nova).
                        </div>
                        <button type="button" className="tbtn tbtn--outline" onClick={reset}>
                            <Icon name="refresh-cw" size={12} />
                            Restaurar senha padrão
                        </button>
                    </div>

                    <div className="share-section">
                        <div className="share-label">Sobre o Studio</div>
                        <ul className="settings-about">
                            <li><strong>Versão:</strong> {window.STUDIO_DATA.STUDIO_VERSION}</li>
                            <li><strong>Build:</strong> {window.STUDIO_DATA.STUDIO_BUILD_DATE}</li>
                            <li><strong>Demos no navegador:</strong> {JSON.parse(localStorage.getItem('studio_library_v1') || '[]').length}</li>
                            <li>
                                <strong>URL pública (após deploy):</strong>{' '}
                                <code>demo.upflux.ai</code>
                            </li>
                        </ul>
                    </div>
                </form>
                <div className="modal-foot">
                    <button type="button" className="tbtn" onClick={onClose}>Fechar</button>
                    <button type="submit" className="tbtn tbtn--primary" onClick={submit}>
                        <Icon name="check" size={12} />
                        Salvar nova senha
                    </button>
                </div>
            </div>
        </div>
    );
}

/* ==================================================================
   DEMO CARD
   ================================================================== */
function DemoCard({ demo, menuOpen, onToggleMenu, onOpen, onClone, onDelete }) {
    const STATUS_LABEL = {
        draft:  { label: 'Rascunho',     cls: 'st-draft' },
        ready:  { label: 'Pronta',       cls: 'st-ready' },
        shared: { label: 'Compartilhada', cls: 'st-shared' },
    };
    const st = STATUS_LABEL[demo.status] || STATUS_LABEL.draft;
    const versionMismatch = demo.version !== window.STUDIO_DATA.STUDIO_VERSION;

    return (
        <article className="lib-card" onClick={onOpen}>
            <div className="lib-card-cover" style={{ background: `linear-gradient(135deg, ${demo.accent}18, ${demo.accent}06)` }}>
                <div className="lib-card-cover-mono" style={{ color: demo.accent }}>
                    {demo.prospect.charAt(0).toUpperCase()}
                </div>
                <div className="lib-card-cover-pattern">
                    {/* Subtle decorative shapes */}
                    <svg width="180" height="64" viewBox="0 0 180 64" style={{ opacity: 0.35 }}>
                        <circle cx="20" cy="32" r="3" fill={demo.accent} />
                        <circle cx="40" cy="14" r="2" fill={demo.accent} opacity="0.6" />
                        <line x1="23" y1="32" x2="40" y2="16" stroke={demo.accent} strokeWidth="1.5" opacity="0.5" />
                        <circle cx="70" cy="32" r="2.5" fill={demo.accent} opacity="0.7" />
                        <line x1="42" y1="14" x2="68" y2="30" stroke={demo.accent} strokeWidth="1.5" opacity="0.5" />
                        <circle cx="110" cy="20" r="3" fill={demo.accent} />
                        <line x1="72" y1="32" x2="108" y2="22" stroke={demo.accent} strokeWidth="1.5" opacity="0.5" />
                        <circle cx="150" cy="44" r="2.5" fill={demo.accent} opacity="0.7" />
                        <line x1="112" y1="22" x2="148" y2="42" stroke={demo.accent} strokeWidth="1.5" opacity="0.5" />
                    </svg>
                </div>
            </div>
            <button
                className="lib-card-kebab"
                onClick={onToggleMenu}
                aria-label="Mais ações"
            >
                <span /><span /><span />
            </button>
            {menuOpen && (
                <div className="lib-card-menu" onClick={(e) => e.stopPropagation()}>
                    <button onClick={(e) => { e.stopPropagation(); onOpen(); }}>
                        <Icon name="edit-3" size={11} /> Abrir
                    </button>
                    <button onClick={(e) => { e.stopPropagation(); onClone(); }}>
                        <Icon name="layers" size={11} /> Clonar
                    </button>
                    <div className="lib-card-menu-divider" />
                    <button className="danger" onClick={(e) => { e.stopPropagation(); onDelete(); }}>
                        <Icon name="trash" size={11} /> Excluir
                    </button>
                </div>
            )}
            <div className="lib-card-body">
                <div className="lib-card-titlerow">
                    <h3 className="lib-card-title">{demo.name}</h3>
                    <span className={`lib-card-status ${st.cls}`}>{st.label}</span>
                </div>
                <div className="lib-card-meta">
                    <span className="lib-card-meta-row">
                        <Icon name="briefcase" size={11} />
                        {demo.industry}
                    </span>
                    <span className="lib-card-meta-row">
                        <Icon name="users" size={11} />
                        {demo.persona}
                    </span>
                </div>
                <div className="lib-card-hint">{demo.thumbHint}</div>
                <div className="lib-card-foot">
                    <span className="lib-card-avatar" title={demo.owner}>{demo.ownerInitials}</span>
                    <span className="lib-card-foot-text">
                        Editada em <strong>{demo.updatedAt}</strong>
                    </span>
                    {versionMismatch && (
                        <span className="lib-card-version-warn" title={`Esta demo foi criada na ${demo.version}, o Studio está em ${window.STUDIO_DATA.STUDIO_VERSION}`}>
                            <Icon name="alert-triangle" size={10} />
                            {demo.version}
                        </span>
                    )}
                    {demo.views > 0 && (
                        <span className="lib-card-views">
                            <Icon name="eye" size={11} />
                            {demo.views}
                        </span>
                    )}
                </div>
            </div>
        </article>
    );
}

/* ==================================================================
   NEW DEMO MODAL — blank or clone-from-template
   ================================================================== */
function NewDemoModal({ library, onClose, onCreate, onClone }) {
    const [name, setName] = React.useState('');
    const [mode, setMode] = React.useState('blank');  /* 'blank' | 'clone' */
    const [pickedId, setPickedId] = React.useState(library[0]?.id);
    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal" onClick={(e) => e.stopPropagation()}>
                <div className="modal-head">
                    <div>
                        <div className="modal-title">Nova demo</div>
                        <div className="modal-sub">
                            Comece em branco ou clone uma existente como ponto de partida.
                        </div>
                    </div>
                    <button className="modal-close" onClick={onClose}>
                        <Icon name="plus" size={16} style={{ transform: 'rotate(45deg)' }} />
                    </button>
                </div>
                <div className="modal-body">
                    <div className="newdemo-modes">
                        <button
                            className={`newdemo-mode${mode === 'blank' ? ' active' : ''}`}
                            onClick={() => setMode('blank')}
                        >
                            <span className="newdemo-mode-icon"><Icon name="plus" size={14} /></span>
                            <span>
                                <div className="newdemo-mode-title">Em branco</div>
                                <div className="newdemo-mode-sub">Começa do template Docol e personaliza tudo</div>
                            </span>
                        </button>
                        <button
                            className={`newdemo-mode${mode === 'clone' ? ' active' : ''}`}
                            onClick={() => setMode('clone')}
                        >
                            <span className="newdemo-mode-icon"><Icon name="layers" size={14} /></span>
                            <span>
                                <div className="newdemo-mode-title">Clonar existente</div>
                                <div className="newdemo-mode-sub">Mais rápido: parte de uma demo já feita</div>
                            </span>
                        </button>
                    </div>

                    {mode === 'blank' && (
                        <div className="share-section" style={{ marginTop: 14 }}>
                            <div className="share-label">Nome do prospect</div>
                            <input
                                autoFocus
                                className="f-input"
                                value={name}
                                onChange={(e) => setName(e.target.value)}
                                placeholder="Ex: Unimed BH, Magazine Luiza..."
                            />
                            <div className="share-hint">
                                Aparece no sidebar do Nous, nas saudações e no header da demo.
                            </div>
                        </div>
                    )}

                    {mode === 'clone' && (
                        <div className="share-section" style={{ marginTop: 14 }}>
                            <div className="share-label">Escolha a base</div>
                            <div className="newdemo-clone-list">
                                {library.map(d => (
                                    <button
                                        key={d.id}
                                        className={`newdemo-clone-item${pickedId === d.id ? ' active' : ''}`}
                                        onClick={() => setPickedId(d.id)}
                                    >
                                        <span className="newdemo-clone-mono" style={{ background: `${d.accent}18`, color: d.accent }}>
                                            {d.prospect.charAt(0).toUpperCase()}
                                        </span>
                                        <span className="newdemo-clone-info">
                                            <span className="newdemo-clone-name">{d.name}</span>
                                            <span className="newdemo-clone-meta">{d.industry} · {d.persona}</span>
                                        </span>
                                        {pickedId === d.id && <Icon name="check" size={13} style={{ color: 'var(--nous-purple)' }} />}
                                    </button>
                                ))}
                            </div>
                        </div>
                    )}
                </div>
                <div className="modal-foot">
                    <button className="tbtn" onClick={onClose}>Cancelar</button>
                    <button
                        className="tbtn tbtn--primary"
                        onClick={() => mode === 'blank' ? onCreate(name || 'Novo prospect') : onClone(pickedId)}
                    >
                        <Icon name="arrow-right" size={12} />
                        {mode === 'blank' ? 'Criar demo' : 'Clonar e abrir'}
                    </button>
                </div>
            </div>
        </div>
    );
}

Object.assign(window, { LoginScreen, LibraryScreen, DemoCard, NewDemoModal, SettingsModal, StandardAnswersAdmin, AgentsMediaAdmin, HotspotsAdmin, getStudioPassword, setStudioPassword });

/* ==================================================================
   STANDARD ANSWERS ADMIN — manage the mandatory P2P question bank
   that feeds the chat (by category) for every P2P demo.
   ================================================================== */
function StandardAnswersAdmin({ onClose }) {
    const SD = window.STUDIO_DATA;
    const [bank, setBank] = React.useState(() => SD.getStandardBank());
    const [editingKey, setEditingKey] = React.useState(null);
    const [savedFlash, setSavedFlash] = React.useState(false);

    const CATS = [
        { id: 'estrategico', label: 'Estratégico' },
        { id: 'gestao',      label: 'Gestão' },
        { id: 'operacional', label: 'Operacional' },
    ];

    const persist = (next) => {
        setBank(next);
        SD.saveStandardBank(next);
        setSavedFlash(true);
        setTimeout(() => setSavedFlash(false), 1600);
    };
    const update = (key, patch) => persist(bank.map(s => s.key === key ? { ...s, ...patch } : s));

    /* Read an attached .html file, store it in IndexedDB and point the
       entry's html at uploaded:<key>. Works fully client-side. */
    const attachHtml = async (key, file) => {
        if (!file) return;
        const text = await file.text();
        const idbKey = 'uploaded/' + key + '-' + Date.now().toString(36);
        await SD.idbPutHtml(idbKey, text);
        update(key, { html: 'uploaded:' + idbKey, htmlName: file.name });
    };
    const downloadUploaded = async (s) => {
        const idbKey = s.html.slice('uploaded:'.length);
        const text = await SD.idbGetHtml(idbKey);
        if (text == null) { alert('Arquivo não encontrado neste navegador.'); return; }
        const url = URL.createObjectURL(new Blob([text], { type: 'text/html' }));
        const a = document.createElement('a');
        a.href = url; a.download = s.htmlName || (s.key + '.html');
        document.body.appendChild(a); a.click(); a.remove();
        setTimeout(() => URL.revokeObjectURL(url), 1000);
    };
    const previewUploaded = async (s) => {
        const idbKey = s.html.slice('uploaded:'.length);
        const text = await SD.idbGetHtml(idbKey);
        if (text == null) { alert('Arquivo não encontrado neste navegador.'); return; }
        const url = URL.createObjectURL(new Blob([text], { type: 'text/html' }));
        window.open(url, '_blank');
        setTimeout(() => URL.revokeObjectURL(url), 60000);
    };
    const remove = (key) => {
        if (confirm('Remover esta resposta padrão de todos os ambientes P2P?')) {
            persist(bank.filter(s => s.key !== key));
            setEditingKey(null);
        }
    };
    const addNew = () => {
        const key = 'custom-' + Math.random().toString(36).slice(2, 7);
        const entry = {
            key, category: 'gestao',
            label: 'Nova pergunta padrão',
            summary: 'Resumo da resposta que aparece no chat antes do artefato.',
            html: '',
            title: 'Novo artefato',
            meta: ['Tempo real', 'Fonte: ERP'],
            height: 760,
            replaces: [],
        };
        persist([...bank, entry]);
        setEditingKey(key);
    };
    /* Attach an HTML file directly: creates a new entry, stores the file
       in IndexedDB, opens it in edit mode so the AE writes the question. */
    const uploadRef = React.useRef(null);
    const onTopUpload = async (e) => {
        const file = e.target.files && e.target.files[0];
        e.target.value = '';
        if (!file) return;
        const key = 'upload-' + Math.random().toString(36).slice(2, 7);
        const text = await file.text();
        const idbKey = 'uploaded/' + key + '-' + Date.now().toString(36);
        await SD.idbPutHtml(idbKey, text);
        const niceTitle = file.name.replace(/\.html?$/i, '').replace(/[-_]+/g, ' ').trim();
        const entry = {
            key, category: 'gestao',
            label: 'Nova pergunta — ' + niceTitle,
            summary: 'Descreva aqui, em 2-3 frases, o que esta resposta entrega. [Complementar com os números do cliente.]',
            html: 'uploaded:' + idbKey, htmlName: file.name,
            title: niceTitle || 'Artefato',
            meta: ['Tempo real', 'Fonte: ERP'],
            height: 780,
            replaces: [],
        };
        persist([...bank, entry]);
        setEditingKey(key);
    };
    const resetAll = () => {
        if (confirm('Restaurar a biblioteca de respostas padrão de fábrica? Suas edições serão perdidas.')) {
            SD.resetStandardBank();
            persist(SD.getStandardBank());
        }
    };

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal modal--wide answers-admin" onClick={(e) => e.stopPropagation()}>
                <div className="modal-head">
                    <div>
                        <div className="modal-title">Biblioteca de Respostas Padrão · P2P</div>
                        <div className="modal-sub">
                            Perguntas e respostas mínimas, obrigatórias em todo ambiente P2P. Alimentam o
                            chat por categoria. {savedFlash && <span style={{ color: 'var(--success)', fontWeight: 500 }}>· salvo</span>}
                        </div>
                    </div>
                    <div style={{ display: 'flex', gap: 8 }}>
                        <button className="tbtn" onClick={resetAll}>
                            <Icon name="refresh-cw" size={12} /> Restaurar padrão
                        </button>
                        <button className="tbtn" onClick={addNew}>
                            <Icon name="plus" size={12} /> Resposta em texto
                        </button>
                        <input ref={uploadRef} type="file" accept=".html,.htm,text/html" style={{ display: 'none' }} onChange={onTopUpload} />
                        <button className="tbtn tbtn--primary" onClick={() => uploadRef.current && uploadRef.current.click()}>
                            <Icon name="upload" size={12} /> Anexar HTML
                        </button>
                        <button className="modal-close" onClick={onClose}>
                            <Icon name="plus" size={16} style={{ transform: 'rotate(45deg)' }} />
                        </button>
                    </div>
                </div>
                <div className="modal-body answers-admin-body">
                    {CATS.map(cat => {
                        const items = bank.filter(s => s.category === cat.id);
                        return (
                            <div className="answers-cat" key={cat.id}>
                                <div className="answers-cat-head">
                                    <Icon name="sparkles" size={12} style={{ color: 'var(--nous-purple)' }} />
                                    {cat.label}
                                    <span className="answers-cat-count">{items.length}</span>
                                </div>
                                {items.map(s => (
                                    <div className={`answer-row${editingKey === s.key ? ' open' : ''}`} key={s.key}>
                                        <div className="answer-row-head" onClick={() => setEditingKey(editingKey === s.key ? null : s.key)}>
                                            <span className="answer-row-icon"><Icon name="file-text" size={13} /></span>
                                            <div className="answer-row-info">
                                                <div className="answer-row-label">{s.label}</div>
                                                <div className="answer-row-meta">
                                                    {s.html && s.html.startsWith('uploaded:')
                                                        ? '📎 ' + (s.htmlName || 'HTML anexado no navegador')
                                                        : (s.html && s.html.trim()
                                                            ? s.html
                                                            : '◦ Resposta em texto · sem artefato HTML')}
                                                </div>
                                            </div>
                                            <Icon name={editingKey === s.key ? 'chevron-down' : 'chevron-right'} size={14} style={{ color: 'var(--text-muted)' }} />
                                        </div>
                                        {editingKey === s.key && (
                                            <div className="answer-row-edit">
                                                <label className="ans-field">
                                                    <span>Pergunta (rótulo no chat)</span>
                                                    <input className="f-input" value={s.label} onChange={e => update(s.key, { label: e.target.value })} />
                                                </label>
                                                <div className="ans-field-grid">
                                                    <label className="ans-field">
                                                        <span>Categoria</span>
                                                        <select className="f-input" value={s.category} onChange={e => update(s.key, { category: e.target.value })}>
                                                            <option value="estrategico">Estratégico</option>
                                                            <option value="gestao">Gestão</option>
                                                            <option value="operacional">Operacional</option>
                                                        </select>
                                                    </label>
                                                    <div className="ans-field">
                                                        <span>Arquivo HTML da resposta <em style={{ color: 'var(--text-muted)', fontWeight: 400 }}>(anexe um .html, cole um caminho de assets/, ou deixe vazio p/ texto)</em></span>
                                                        <div className="ans-html-row">
                                                            <input
                                                                className="f-input f-input--mono"
                                                                value={s.html.startsWith('uploaded:') ? ('📎 ' + (s.htmlName || 'arquivo anexado')) : s.html}
                                                                readOnly={s.html.startsWith('uploaded:')}
                                                                onChange={e => update(s.key, { html: e.target.value })}
                                                                placeholder="assets/minha-resposta.html — ou anexe →"
                                                            />
                                                            <label className="ans-attach-btn">
                                                                <Icon name="upload" size={12} /> Anexar
                                                                <input type="file" accept=".html,.htm,text/html" style={{ display: 'none' }}
                                                                    onChange={e => { const f = e.target.files[0]; e.target.value = ''; attachHtml(s.key, f); }} />
                                                            </label>
                                                            {s.html.startsWith('uploaded:') && (
                                                                <button className="ans-attach-btn ans-attach-btn--ghost" onClick={() => update(s.key, { html: '', htmlName: undefined })} title="Remover anexo">
                                                                    <Icon name="plus" size={12} style={{ transform: 'rotate(45deg)' }} />
                                                                </button>
                                                            )}
                                                        </div>
                                                    </div>
                                                </div>
                                                <label className="ans-field">
                                                    <span>Resumo (texto no chat antes do artefato)</span>
                                                    <textarea className="f-input" rows={4} value={s.summary} onChange={e => update(s.key, { summary: e.target.value })} />
                                                </label>
                                                <div className="ans-field-grid">
                                                    <label className="ans-field">
                                                        <span>Título do artefato</span>
                                                        <input className="f-input" value={s.title || ''} onChange={e => update(s.key, { title: e.target.value })} />
                                                    </label>
                                                    <label className="ans-field">
                                                        <span>Chips meta (separados por vírgula)</span>
                                                        <input className="f-input" value={(s.meta || []).join(', ')} onChange={e => update(s.key, { meta: e.target.value.split(',').map(x => x.trim()).filter(Boolean) })} />
                                                    </label>
                                                </div>
                                                <div className="ans-field-grid">
                                                    <label className="ans-field">
                                                        <span>Altura do artefato (px)</span>
                                                        <input className="f-input" type="number" value={s.height || 760} onChange={e => update(s.key, { height: Number(e.target.value) || 760 })} />
                                                    </label>
                                                    <label className="ans-field">
                                                        <span>Substitui (rótulos antigos, vírgula)</span>
                                                        <input className="f-input f-input--mono" value={(s.replaces || []).join(', ')} onChange={e => update(s.key, { replaces: e.target.value.split(',').map(x => x.trim()).filter(Boolean) })} />
                                                    </label>
                                                </div>
                                                <div className="answer-row-actions">
                                                    <div style={{ display: 'flex', gap: 8 }}>
                                                        {s.html && s.html.startsWith('uploaded:') ? (
                                                            <>
                                                                <button className="tbtn" onClick={() => previewUploaded(s)}>
                                                                    <Icon name="eye" size={12} /> Pré-visualizar
                                                                </button>
                                                                <button className="tbtn" onClick={() => downloadUploaded(s)} title="Baixar para colocar em assets/ no servidor">
                                                                    <Icon name="arrow-down" size={12} /> Baixar p/ assets
                                                                </button>
                                                            </>
                                                        ) : s.html && s.html.trim() ? (
                                                            <a className="tbtn" href={s.html} target="_blank" rel="noopener">
                                                                <Icon name="eye" size={12} /> Pré-visualizar HTML
                                                            </a>
                                                        ) : <span className="ans-texthint">Resposta entregue só em texto no chat.</span>}
                                                    </div>
                                                    <button className="ans-remove" onClick={() => remove(s.key)}>
                                                        <Icon name="trash" size={12} /> Remover
                                                    </button>
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                ))}
                                {items.length === 0 && <div className="answers-empty">Sem respostas nesta categoria.</div>}
                            </div>
                        );
                    })}
                    <div className="answers-note">
                        <Icon name="sparkles" size={12} style={{ color: 'var(--nous-purple)', flexShrink: 0, marginTop: 1 }} />
                        <span>
                            Estas respostas entram automaticamente no chat de <strong>todos</strong> os ambientes P2P,
                            nas categorias indicadas. <strong>Anexar HTML</strong> guarda o arquivo neste navegador (funciona
                            já na demo, sem servidor); use <strong>Baixar p/ assets</strong> e coloque o arquivo em
                            <code style={{ fontFamily: 'var(--font-mono)' }}> assets/</code> no servidor para deixá-lo
                            permanente e visível em qualquer dispositivo. Os números podem ser ajustados por cliente no
                            modo edição, direto na tela.
                        </span>
                    </div>
                </div>
            </div>
        </div>
    );
}

/* ==================================================================
   AGENTS MEDIA ADMIN — manage each agent's interactive-demo HTML and
   single video once, for ALL P2P environments.
   ================================================================== */
function AgentsMediaAdmin({ onClose }) {
    const SD = window.STUDIO_DATA;
    const [bank, setBank] = React.useState(() => SD.getAgentMediaBank());
    const [flash, setFlash] = React.useState(false);

    const persist = (next) => {
        setBank(next);
        SD.saveAgentMediaBank(next);
        setFlash(true);
        setTimeout(() => setFlash(false), 1600);
    };
    const update = (id, patch) => persist(bank.map(b => b.id === id ? { ...b, ...patch } : b));

    const attach = async (id, file, kind) => {
        if (!file) return;
        const prefix = kind === 'video' ? 'uploadedvid:' : 'uploaded:';
        const idbKey = (kind === 'video' ? 'agentvid/' : 'agenthtml/') + id + '-' + Date.now().toString(36);
        if (kind === 'video') {
            await SD.idbPutBlob(idbKey, file);
            update(id, { demoVideo: prefix + idbKey, demoVideoName: file.name });
        } else {
            const text = await file.text();
            await SD.idbPutHtml(idbKey, text);
            update(id, { demoHtml: prefix + idbKey, demoHtmlName: file.name });
        }
    };
    const openUploaded = async (src) => {
        const isVid = src.startsWith('uploadedvid:');
        const key = src.replace(/^uploaded(vid)?:/, '');
        const val = await SD.idbGetBlob(key);
        if (val == null) { alert('Arquivo não encontrado neste navegador.'); return; }
        const blob = (val instanceof Blob) ? val : new Blob([val], { type: isVid ? 'video/mp4' : 'text/html' });
        const url = URL.createObjectURL(blob);
        window.open(url, '_blank');
        setTimeout(() => URL.revokeObjectURL(url), 60000);
    };
    const downloadUploaded = async (src, name) => {
        const isVid = src.startsWith('uploadedvid:');
        const key = src.replace(/^uploaded(vid)?:/, '');
        const val = await SD.idbGetBlob(key);
        if (val == null) { alert('Arquivo não encontrado neste navegador.'); return; }
        const blob = (val instanceof Blob) ? val : new Blob([val], { type: isVid ? 'video/mp4' : 'text/html' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url; a.download = name || (isVid ? 'video.mp4' : 'demo.html');
        document.body.appendChild(a); a.click(); a.remove();
        setTimeout(() => URL.revokeObjectURL(url), 1000);
    };
    const resetAll = () => {
        if (confirm('Restaurar a mídia dos agentes de fábrica? Anexos enviados serão desvinculados.')) {
            SD.resetAgentMediaBank();
            persist(SD.getAgentMediaBank());
        }
    };

    const isUp = (v) => v && /^uploaded(vid)?:/.test(v);

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal modal--wide answers-admin" onClick={(e) => e.stopPropagation()}>
                <div className="modal-head">
                    <div>
                        <div className="modal-title">Agentes · Demos &amp; Vídeos</div>
                        <div className="modal-sub">
                            Gerencie a demo interativa (HTML) e o vídeo de cada agente uma vez, para
                            todos os ambientes P2P. {flash && <span style={{ color: 'var(--success)', fontWeight: 500 }}>· salvo</span>}
                        </div>
                    </div>
                    <div style={{ display: 'flex', gap: 8 }}>
                        <button className="tbtn" onClick={resetAll}>
                            <Icon name="refresh-cw" size={12} /> Restaurar padrão
                        </button>
                        <button className="modal-close" onClick={onClose}>
                            <Icon name="plus" size={16} style={{ transform: 'rotate(45deg)' }} />
                        </button>
                    </div>
                </div>
                <div className="modal-body answers-admin-body">
                    {bank.map(ag => (
                        <div className="agent-media-card" key={ag.id}>
                            <div className="agent-media-head">
                                <span className="answer-row-icon"><Icon name="briefcase" size={14} /></span>
                                <div className="agent-media-name">{ag.name}</div>
                            </div>

                            {/* Interactive demo HTML */}
                            <div className="agent-media-block">
                                <div className="agent-media-block-label"><Icon name="zap" size={12} /> Demo interativa (HTML)</div>
                                <div className="ans-html-row">
                                    <input
                                        className="f-input f-input--mono"
                                        value={isUp(ag.demoHtml) ? ('📎 ' + (ag.demoHtmlName || 'arquivo anexado')) : (ag.demoHtml || '')}
                                        readOnly={isUp(ag.demoHtml)}
                                        placeholder="assets/minha-demo.html — ou anexe →"
                                        onChange={e => update(ag.id, { demoHtml: e.target.value })}
                                    />
                                    <label className="ans-attach-btn">
                                        <Icon name="upload" size={12} /> Anexar
                                        <input type="file" accept=".html,.htm,text/html" style={{ display: 'none' }}
                                            onChange={e => { const f = e.target.files[0]; e.target.value = ''; attach(ag.id, f, 'html'); }} />
                                    </label>
                                    {ag.demoHtml && (
                                        <button className="ans-attach-btn ans-attach-btn--ghost" title="Remover demo"
                                            onClick={() => update(ag.id, { demoHtml: '', demoHtmlName: '' })}>
                                            <Icon name="plus" size={12} style={{ transform: 'rotate(45deg)' }} />
                                        </button>
                                    )}
                                </div>
                                {isUp(ag.demoHtml) && (
                                    <div className="agent-media-actions">
                                        <button className="tbtn" onClick={() => openUploaded(ag.demoHtml)}><Icon name="eye" size={12} /> Pré-visualizar</button>
                                        <button className="tbtn" onClick={() => downloadUploaded(ag.demoHtml, ag.demoHtmlName)}><Icon name="arrow-down" size={12} /> Baixar p/ assets</button>
                                    </div>
                                )}
                            </div>

                            {/* Single video */}
                            <div className="agent-media-block">
                                <div className="agent-media-block-label"><Icon name="play" size={12} /> Vídeo (um por agente)</div>
                                <div className="ans-html-row">
                                    <input
                                        className="f-input f-input--mono"
                                        value={isUp(ag.demoVideo) ? ('🎬 ' + (ag.demoVideoName || 'vídeo anexado')) : (ag.demoVideo || '')}
                                        readOnly={isUp(ag.demoVideo)}
                                        placeholder="assets/video.mp4 ou Loom/Vimeo/YouTube — ou suba →"
                                        onChange={e => update(ag.id, { demoVideo: e.target.value })}
                                    />
                                    <label className="ans-attach-btn">
                                        <Icon name="upload" size={12} /> {isUp(ag.demoVideo) ? 'Substituir' : 'Subir'}
                                        <input type="file" accept="video/*" style={{ display: 'none' }}
                                            onChange={e => { const f = e.target.files[0]; e.target.value = ''; attach(ag.id, f, 'video'); }} />
                                    </label>
                                    {ag.demoVideo && (
                                        <button className="ans-attach-btn ans-attach-btn--ghost" title="Remover vídeo"
                                            onClick={() => update(ag.id, { demoVideo: '', demoVideoName: '' })}>
                                            <Icon name="plus" size={12} style={{ transform: 'rotate(45deg)' }} />
                                        </button>
                                    )}
                                </div>
                                {isUp(ag.demoVideo) && (
                                    <div className="agent-media-actions">
                                        <button className="tbtn" onClick={() => openUploaded(ag.demoVideo)}><Icon name="eye" size={12} /> Pré-visualizar</button>
                                        <button className="tbtn" onClick={() => downloadUploaded(ag.demoVideo, ag.demoVideoName)}><Icon name="arrow-down" size={12} /> Baixar p/ assets</button>
                                    </div>
                                )}
                            </div>
                        </div>
                    ))}
                    <div className="answers-note">
                        <Icon name="film" size={12} style={{ color: 'var(--nous-purple)', flexShrink: 0, marginTop: 1 }} />
                        <span>
                            <strong>Anexar/Subir</strong> guarda o arquivo neste navegador (funciona já na demo, sem
                            servidor) e vale para <strong>todos</strong> os ambientes. A demo interativa tem prioridade
                            sobre o vídeo. Para deixar permanente em qualquer dispositivo, use <strong>Baixar p/ assets</strong>,
                            coloque o arquivo em <code style={{ fontFamily: 'var(--font-mono)' }}>assets/</code> no servidor
                            e cole o caminho. Vídeo aceita MP4 (upload) ou link Loom/Vimeo/YouTube.
                        </span>
                    </div>
                </div>
            </div>
        </div>
    );
}

/* ==================================================================
   HOTSPOTS ADMIN — standard hotspots (one per main item) registered
   for every P2P environment; each env can personalize afterwards.
   ================================================================== */
function HotspotsAdmin({ onClose }) {
    const SD = window.STUDIO_DATA;
    const [bank, setBank] = React.useState(() => SD.getHotspotBank());
    const [openKey, setOpenKey] = React.useState(null);
    const [flash, setFlash] = React.useState(false);

    const SCREENS = [
        { id: 'chat', label: 'Chat' },
        { id: 'mining', label: 'Process Mining' },
        { id: 'agents', label: 'Agentes' },
        { id: 'roai', label: 'RoAI · Value Tracker' },
        { id: 'rotinas', label: 'Rotinas' },
        { id: 'achados', label: 'Achados' },
        { id: 'brain', label: 'Agentes de Conhecimento' },
        { id: 'consumo', label: 'Consumo & Cotas' },
    ];
    const KINDS = [
        { id: 'tooltip', label: 'Tooltip' },
        { id: 'cta', label: 'CTA' },
        { id: 'hyperlink', label: 'Hyperlink' },
        { id: 'video', label: 'Vídeo do AE' },
    ];
    const screenLabel = (id) => (SCREENS.find(s => s.id === id) || {}).label || id;

    const persist = (next) => {
        setBank(next);
        SD.saveHotspotBank(next);
        setFlash(true);
        setTimeout(() => setFlash(false), 1600);
    };
    const update = (key, patch) => persist(bank.map(h => h.stdKey === key ? { ...h, ...patch } : h));
    const remove = (key) => {
        if (confirm('Remover este hotspot padrão de todos os ambientes P2P?')) {
            persist(bank.filter(h => h.stdKey !== key));
            setOpenKey(null);
        }
    };
    const addNew = () => {
        const key = 'hs-' + Math.random().toString(36).slice(2, 7);
        persist([...bank, {
            stdKey: key, screen: 'chat', x: 0.5, y: 0.3, kind: 'tooltip',
            title: 'Novo hotspot', text: 'Explique o que é este item e para que serve.',
            link: '', cta: '', videoUrl: '', videoDuration: '',
        }]);
        setOpenKey(key);
    };
    const resetAll = () => {
        if (confirm('Restaurar os hotspots padrão de fábrica? Suas edições serão perdidas.')) {
            SD.resetHotspotBank();
            persist(SD.getHotspotBank());
        }
    };

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal modal--wide answers-admin" onClick={(e) => e.stopPropagation()}>
                <div className="modal-head">
                    <div>
                        <div className="modal-title">Hotspots padrão · P2P</div>
                        <div className="modal-sub">
                            Um hotspot por item principal, explicando o que é e para que serve. Entram em
                            todo ambiente P2P; cada um pode ser ajustado por ambiente depois.
                            {flash && <span style={{ color: 'var(--success)', fontWeight: 500 }}> · salvo</span>}
                        </div>
                    </div>
                    <div style={{ display: 'flex', gap: 8 }}>
                        <button className="tbtn" onClick={resetAll}>
                            <Icon name="refresh-cw" size={12} /> Restaurar padrão
                        </button>
                        <button className="tbtn tbtn--primary" onClick={addNew}>
                            <Icon name="plus" size={12} /> Novo hotspot
                        </button>
                        <button className="modal-close" onClick={onClose}>
                            <Icon name="plus" size={16} style={{ transform: 'rotate(45deg)' }} />
                        </button>
                    </div>
                </div>
                <div className="modal-body answers-admin-body">
                    {bank.map(h => (
                        <div className={`answer-row${openKey === h.stdKey ? ' open' : ''}`} key={h.stdKey}>
                            <div className="answer-row-head" onClick={() => setOpenKey(openKey === h.stdKey ? null : h.stdKey)}>
                                <span className="answer-row-icon"><Icon name="sparkles" size={13} /></span>
                                <div className="answer-row-info">
                                    <div className="answer-row-label">{h.title}</div>
                                    <div className="answer-row-meta">{screenLabel(h.screen)} · {(KINDS.find(k => k.id === h.kind) || {}).label || h.kind}</div>
                                </div>
                                <Icon name={openKey === h.stdKey ? 'chevron-down' : 'chevron-right'} size={14} style={{ color: 'var(--text-muted)' }} />
                            </div>
                            {openKey === h.stdKey && (
                                <div className="answer-row-edit">
                                    <label className="ans-field">
                                        <span>Título</span>
                                        <input className="f-input" value={h.title} onChange={e => update(h.stdKey, { title: e.target.value })} />
                                    </label>
                                    <label className="ans-field">
                                        <span>Texto (o que é / para que serve)</span>
                                        <textarea className="f-input" rows={4} value={h.text} onChange={e => update(h.stdKey, { text: e.target.value })} />
                                    </label>
                                    <div className="ans-field-grid">
                                        <label className="ans-field">
                                            <span>Tela</span>
                                            <select className="f-input" value={h.screen} onChange={e => update(h.stdKey, { screen: e.target.value })}>
                                                {SCREENS.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
                                            </select>
                                        </label>
                                        <label className="ans-field">
                                            <span>Tipo</span>
                                            <select className="f-input" value={h.kind} onChange={e => update(h.stdKey, { kind: e.target.value })}>
                                                {KINDS.map(k => <option key={k.id} value={k.id}>{k.label}</option>)}
                                            </select>
                                        </label>
                                    </div>
                                    <div className="ans-field-grid">
                                        <label className="ans-field">
                                            <span>Posição X ({Math.round((h.x || 0) * 100)}%)</span>
                                            <input type="range" min="0" max="1" step="0.01" value={h.x} onChange={e => update(h.stdKey, { x: Number(e.target.value) })} />
                                        </label>
                                        <label className="ans-field">
                                            <span>Posição Y ({Math.round((h.y || 0) * 100)}%)</span>
                                            <input type="range" min="0" max="1" step="0.01" value={h.y} onChange={e => update(h.stdKey, { y: Number(e.target.value) })} />
                                        </label>
                                    </div>
                                    {(h.kind === 'cta' || h.kind === 'hyperlink') && (
                                        <div className="ans-field-grid">
                                            <label className="ans-field">
                                                <span>Texto do botão/link</span>
                                                <input className="f-input" value={h.cta || ''} onChange={e => update(h.stdKey, { cta: e.target.value })} />
                                            </label>
                                            <label className="ans-field">
                                                <span>URL</span>
                                                <input className="f-input f-input--mono" value={h.link || ''} onChange={e => update(h.stdKey, { link: e.target.value })} />
                                            </label>
                                        </div>
                                    )}
                                    <div className="answer-row-actions">
                                        <span className="ans-texthint">Aparece em todos os ambientes que não personalizarem esta tela.</span>
                                        <button className="ans-remove" onClick={() => remove(h.stdKey)}>
                                            <Icon name="trash" size={12} /> Remover
                                        </button>
                                    </div>
                                </div>
                            )}
                        </div>
                    ))}
                    <div className="answers-note">
                        <Icon name="sparkles" size={12} style={{ color: 'var(--nous-purple)', flexShrink: 0, marginTop: 1 }} />
                        <span>
                            Estes hotspots são o <strong>padrão inicial</strong> de todo ambiente P2P, explicando cada
                            item principal. Dentro de cada ambiente (Nível 5 · Conteúdo guiado), o AE pode
                            <strong> ajustar ou personalizar</strong> os hotspots de uma tela — a versão do ambiente
                            substitui o padrão naquela tela.
                        </span>
                    </div>
                </div>
            </div>
        </div>
    );
}
