/* ====================================================================
   ProspectSplash — entry screen shown when a prospect opens a shared
   demo link. Lets them choose how to explore the personalized Nous.
   GuidedTour — the functional 5-step walkthrough launched from Card B.
   Both read the demo's config (prospect name, empresa, AE) — no
   placeholders. Uses the Nous design system tokens.
   ==================================================================== */

function splashFirstName(full) {
    return String(full || '').trim().split(/\s+/)[0] || '';
}

function ProspectSplash({ state, onExplore, onTour }) {
    const empresa = (state.vars && String(state.vars.empresa || '').trim()) || state.cosmetic.company;
    const prospect = (state.cosmetic && state.cosmetic.prospectContact)
        || (state.vars && state.vars.persona_nome) || '';
    const prospectFirst = splashFirstName(prospect);
    const ae = (state.vars && String(state.vars.ae_nome || '').trim()) || '';
    const aeFirst = splashFirstName(ae);
    /* "Andrey te leva…" / "Felipe te leva…"; if the owner is UpFlux itself,
       phrase it without a personal name. */
    const guideLead = (!aeFirst || /^upflux$/i.test(aeFirst))
        ? 'A UpFlux te leva pelos 5 momentos chave'
        : `${aeFirst} te leva pelos 5 momentos chave`;

    return (
        <div className="splash-root">
            <div className="splash-dotgrid" aria-hidden="true" />
            <div className="splash-inner">
                <div className="splash-brand">
                    <img src="assets/logo-nous-horizontal.png" alt="UpFlux Nous" className="splash-logo" />
                </div>

                <header className="splash-head">
                    <h1 className="splash-title">
                        {prospectFirst ? `Bem-vindo, ${prospectFirst}` : 'Bem-vindo'}
                    </h1>
                    <p className="splash-sub">
                        Você está prestes a explorar o Nous personalizado para <strong>{empresa}</strong>.
                        Como prefere começar?
                    </p>
                </header>

                <div className="splash-cards">
                    <button className="splash-card" onClick={onExplore}>
                        <span className="splash-card-icon">
                            <Icon name="compass" size={22} />
                        </span>
                        <span className="splash-card-body">
                            <span className="splash-card-name">Explorar livremente</span>
                            <span className="splash-card-tag">Navegue como se já estivesse usando</span>
                            <span className="splash-card-subtag">Mais rápido para quem já conhece process intelligence</span>
                        </span>
                        <span className="splash-cta splash-cta--primary">
                            Começar
                            <Icon name="arrow-right" size={15} />
                        </span>
                    </button>

                    <button className="splash-card" onClick={onTour}>
                        <span className="splash-card-icon">
                            <Icon name="route" size={22} />
                        </span>
                        <span className="splash-card-body">
                            <span className="splash-card-name">Tour guiado</span>
                            <span className="splash-card-tag">{guideLead}</span>
                            <span className="splash-card-subtag splash-card-subtag--meta">
                                <Icon name="clock" size={13} />
                                Ideal para primeira interação · ~7 minutos
                            </span>
                        </span>
                        <span className="splash-cta splash-cta--outline">
                            Iniciar tour
                            <Icon name="arrow-right" size={15} />
                        </span>
                    </button>
                </div>

                <footer className="splash-foot">
                    Demo · dados simulados baseados no perfil de {empresa}
                </footer>
            </div>
        </div>
    );
}

/* ---- Guided tour: walks the 5 key moments of the Nous --------------
   Navigates the live preview behind a floating step card. Copy is
   pulled from the global standard-hotspot bank so it stays consistent
   and editable in the Studio. */
const TOUR_STEPS = [
    { screen: 'chat',    fallbackTitle: 'Converse com seus dados',     fallbackText: 'Pergunte em linguagem natural e receba a resposta já analisada, com tabelas e gráficos.' },
    { screen: 'mining',  fallbackTitle: 'Veja o processo real',         fallbackText: 'O Process Mining reconstrói o processo a partir do ERP e revela variantes, gargalos e tempos de cada etapa.' },
    { screen: 'agents',  fallbackTitle: 'Agentes trabalhando por você', fallbackText: 'Agentes autônomos executam tarefas do P2P sozinhos e só chamam o humano quando passa da alçada.' },
    { screen: 'rotinas', fallbackTitle: 'Análises no automático',       fallbackText: 'Rotinas agendadas rodam sozinhas no horário definido, garantindo acompanhamento sem ninguém precisar lembrar.' },
    { screen: 'roai',    fallbackTitle: 'O retorno em R$',              fallbackText: 'O Value Tracker mostra, mês a mês, quanto a IA gerou em economia, eficiência e compliance, com a fórmula de cada alavanca.' },
];

function GuidedTour({ state, setState, onExit }) {
    const [step, setStep] = React.useState(0);
    const total = TOUR_STEPS.length;

    /* Pull richer copy from the standard hotspot bank when available. */
    const bank = (window.STUDIO_DATA.getHotspotBank ? window.STUDIO_DATA.getHotspotBank() : []) || [];
    const steps = TOUR_STEPS.map(s => {
        const b = bank.find(h => h.screen === s.screen);
        return { screen: s.screen, title: b ? b.title : s.fallbackTitle, text: b ? b.text : s.fallbackText };
    });

    /* Navigate the preview to the current step's screen. */
    React.useEffect(() => {
        const scr = steps[step].screen;
        setState(s => ({ ...s, activeScreen: scr, openHotspotId: null }));
        const body = document.querySelector('.browser-body');
        if (body) body.scrollTo({ top: 0, behavior: 'smooth' });
    }, [step]);

    const next = () => { if (step < total - 1) setStep(step + 1); else onExit(); };
    const prev = () => { if (step > 0) setStep(step - 1); };

    const cur = steps[step];
    return (
        <div className="tour-layer">
            <div className="tour-card" role="dialog" aria-label="Tour guiado">
                <div className="tour-card-top">
                    <span className="tour-step-badge">Momento {step + 1} de {total}</span>
                    <button className="tour-exit" onClick={onExit}>
                        Sair do tour
                        <Icon name="plus" size={13} style={{ transform: 'rotate(45deg)' }} />
                    </button>
                </div>
                <h3 className="tour-card-title">{cur.title}</h3>
                <p className="tour-card-text">{cur.text}</p>
                <div className="tour-progress">
                    {steps.map((s, i) => (
                        <button
                            key={i}
                            className={`tour-dot${i === step ? ' active' : ''}${i < step ? ' done' : ''}`}
                            onClick={() => setStep(i)}
                            aria-label={`Ir para o momento ${i + 1}`}
                        />
                    ))}
                </div>
                <div className="tour-actions">
                    <button className="tbtn tbtn--ghost" onClick={prev} disabled={step === 0}>
                        <Icon name="chevron-left" size={13} />
                        Anterior
                    </button>
                    <button className="tbtn tbtn--primary tour-next" onClick={next}>
                        {step < total - 1 ? 'Próximo' : 'Concluir'}
                        <Icon name={step < total - 1 ? 'arrow-right' : 'arrow-up-right'} size={14} />
                    </button>
                </div>
            </div>
        </div>
    );
}

Object.assign(window, { ProspectSplash, GuidedTour });
