const { useState, useEffect } = React;
const { Nav, MobileMenu, FloatingBar, Footer, ContactModal, FinalCTA, FOOTER_COLS, SOLUTIONS_NAV, t, tx, useLocale } = window.ATC;

/* Static product metadata. Only IDs and stat numeric/suffix values
   (which are brand-exempt per spec §6) live here. All user-facing
   text (tag/name/kicker/lede/feature titles/descriptions/stat labels)
   is resolved at render via t()/tx() in the App function. */
const SOLUTIONS_META = [
    { id: 'curio', kind: 'features' },
    { id: 'sentinel', kind: 'features' },
    { id: 'testcraft', kind: 'features' },
    { id: 'verify', kind: 'stats', stats: [
        { num: '10', suf: 'M+' },
        { num: '200', suf: '+' },
        { num: '95', suf: '%' },
        { num: '<1', suf: 's' }
    ]},
    { id: 'certiflow', kind: 'stats', stats: [
        { num: '92', suf: '%' },
        { num: '4.2', suf: 'min' },
        { num: '50', suf: '+' },
        { num: 'eKYC', suf: '' }
    ]},
    { id: 'docreference', kind: 'stats', stats: [
        { num: '99.4', suf: '%' },
        { num: '300', suf: '+' },
        { num: '24', suf: '×' },
        { num: 'AST', suf: '' }
    ]},
    { id: 'insightscore', kind: 'stats', stats: [
        { num: '100', suf: '%' },
        { num: '5', suf: '×' },
        { num: '0.04', suf: '' },
        { num: '5+', suf: '' }
    ]}
];

/* Section heading helper. The original JSX used <br /> to force a
   2-line break after the first 2 words for English layout. The i18n
   key holds a single-line string per locale; we split at the same
   2-word boundary so the visual matches the pre-i18n version. */
const splitHeading = (text) => {
    const words = text.split(' ');
    if (words.length <= 2) return text;
    return <>{words.slice(0, 2).join(' ')}<br />{words.slice(2).join(' ')}</>;
};

const ProductSection = ({ p, index, onDemoClick }) => {
    const Visual = window.ProductVisuals?.[p.id];
    const reverse = index % 2 === 1;
    return (
        <div id={p.id} className={`product-card reveal ${reverse ? 'reverse' : ''}`}>
            <div className="info">
                <div className="info-top">
                    <div className="product-tag">
                        <span className="accent">●</span> {p.tag}
                    </div>
                    <h3>{p.name}</h3>
                    <p className="lede">{p.lede}</p>
                    {p.features ?
                        <div className="proof feature-proof">
                            {p.features.map((f) =>
                                <div className="feature-stat" key={f.t}>
                                    <div className="t">{f.t}</div>
                                    <div className="d">{f.d}</div>
                                </div>
                            )}
                        </div> :
                        <div className="proof">
                            {p.stats.map((s) =>
                                <div className="proof-stat" key={s.lab}>
                                    <div className="num">{s.num}<span style={{ fontSize: '0.5em' }}>{s.suf}</span></div>
                                    <div className="lab">{s.lab}</div>
                                </div>
                            )}
                        </div>
                    }
                </div>
                <div className="info-bottom">
                    {p.primary.href === '#contact'
                        ? <button className="btn btn-primary" onClick={onDemoClick}>{p.primary.label}</button>
                        : <a className="btn btn-primary" href={p.primary.href}>{p.primary.label}</a>
                    }
                </div>
            </div>
            <div className="visual">
                {Visual ? <Visual /> : null}
            </div>
        </div>);
};

const ProductPortfolio = ({ id, eyebrow, heading, sub, products, onDemoClick }) => {
    return (
        <section id={id}>
            <div className="container">
                <div className="section-header reveal" style={{ gap: "48px" }}>
                    <div className="left">
                        <span className="eyebrow eyebrow-accent">{eyebrow}</span>
                        <h2>{heading}</h2>
                    </div>
                    <div className="right">{sub}</div>
                </div>
                <div className="products-stack">
                    {products.map((p, i) => <ProductSection p={p} index={i} key={p.id} onDemoClick={onDemoClick} />)}
                </div>
            </div>
        </section>);
};

function App() {
    const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
    const [showContact, setShowContact] = useState(false);

    /* Re-render on locale change so product cards, section header,
       and FinalCTA all refresh in the new language. */
    useLocale();

    const onDemoClick = () => setShowContact(true);

    useEffect(() => {
        const observer = new IntersectionObserver(
            (entries) => entries.forEach(e => e.target.classList.toggle('in', e.isIntersecting)),
            { threshold: 0.1 }
        );
        document.querySelectorAll('.reveal').forEach(el => observer.observe(el));

        return () => {
            observer.disconnect();
        };
    }, []);

    /* Pre-resolve all products in the active locale. tag/name/kicker
       are plain strings (t). lede is JSX with <hl> spans (tx).
       stat num/suf stay English (brand-exempt per spec §6). */
    const products = SOLUTIONS_META.map((meta) => {
        const p = {
            id: meta.id,
            tag: t(`products.${meta.id}.tag`),
            name: t(`products.${meta.id}.name`),
            kicker: t(`products.${meta.id}.kicker`),
            lede: tx(`products.${meta.id}.lede`),
            primary: { href: '#contact', label: t('common.getStarted') }
        };
        if (meta.kind === 'features') {
            p.features = [0, 1, 2, 3].map((i) => ({
                t: t(`products.${meta.id}.features.${i}.t`),
                d: t(`products.${meta.id}.features.${i}.d`)
            }));
        } else {
            p.stats = meta.stats.map((s, i) => ({
                num: s.num,
                suf: s.suf,
                lab: t(`products.${meta.id}.stats.${i}.lab`)
            }));
        }
        return p;
    });

    return (
        <>
            <Nav
                onDemoClick={onDemoClick}
                homeUrl="/"
                showProductsNav={true}
                activeSection="solutions"
            />

            <MobileMenu
                open={mobileMenuOpen}
                onClose={() => setMobileMenuOpen(false)}
                onDemoClick={() => { setMobileMenuOpen(false); setShowContact(true); }}
                products={SOLUTIONS_NAV}
                showHowItWorks={false}
                showCoverage={false}
                showFaq={false}
            />

            <ProductPortfolio
                id="solutions"
                eyebrow={t('solutionsPage.eyebrow')}
                heading={splitHeading(t('solutionsPage.heading'))}
                sub={t('solutionsPage.sub')}
                products={products}
                onDemoClick={onDemoClick}
            />

            <FinalCTA
                heading={t('solutionsPage.finalCta.heading')}
                accent={t('solutionsPage.finalCta.accent')}
                sub={t('solutionsPage.finalCta.sub')}
                actions={[
                    { label: t('solutionsPage.finalCta.bookDemo'), href: '#contact' },
                    { label: t('solutionsPage.finalCta.viewPlatforms'), href: '/platforms' }
                ]}
            />

            <Footer cols={FOOTER_COLS} />

            <ContactModal open={showContact} onClose={() => setShowContact(false)} />

            <FloatingBar
                onMenuClick={() => setMobileMenuOpen(true)}
                onDemoClick={onDemoClick}
            />
        </>
    );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
