/* Ava Solutions — components (v1 yellow restored + correct 4-dot logo) */
const { useEffect, useRef } = React;

/* ---------- Shared product catalogue ----------------------------------------
   Single source of truth, consumed by the footer, the home-page teaser and the
   products page. Each product can ship 1..N interactive HTML presentations; tabs
   appear on the products page only when a product has more than one.

   Product catalogue for AVA CRM / AVA ERP / AVA POS / KOSHI / AVA Assistant / TOROS.
   Taglines and bullets are English copy; linked presentation HTML files live under
   /presentations/<slug>/. */
const PRODUCTS = [
  {
    slug: 'ava-crm',
    category: 'sales',
    name: 'AVA CRM',
    tags: 'Guests / Reservations / Loyalty',
    tagline: 'Guest management, reservations and loyalty: unified customer database, segmentation, visit history and automated campaigns.',
    bullets: ['Guest database', 'Reservations', 'Loyalty program'],
    presentations: [
      { label: 'Reservations', url: '/presentations/ava-platform-horeca/ava-crm/reservations.html' },
      { label: 'Views', url: '/presentations/ava-platform-horeca/ava-crm/views.html' },
      { label: 'Analytics', url: '/presentations/ava-platform-horeca/ava-crm/analytics.html' },
    ],
  },
  {
    slug: 'ava-erp',
    category: 'finance',
    name: 'AVA ERP',
    tags: 'Inventory / Recipes / Procurement',
    tagline: 'Kitchen, inventory and procurement under control: recipe cards, write-offs, real-time stock levels and automated supplier orders.',
    bullets: ['Recipes & tech cards', 'Inventory management', 'Procurement'],
    presentations: [
      { label: 'Requests', url: '/presentations/ava-platform-horeca/ava-erp/requests.html' },
      { label: 'Approval', url: '/presentations/ava-platform-horeca/ava-erp/approval.html' },
      { label: 'Receiving', url: '/presentations/ava-platform-horeca/ava-erp/receiving.html' },
      { label: 'Warehouse', url: '/presentations/ava-platform-horeca/ava-erp/warehouse.html' },
      { label: 'Nomenclature', url: '/presentations/ava-platform-horeca/ava-erp/nomenclature.html' },
    ],
  },
  {
    slug: 'ava-pos',
    category: 'team',
    name: 'AVA POS',
    tags: 'Checkout / Orders / Floor',
    tagline: 'Checkout and floor: order taking, payments, table and shift management — fast, reliable, offline-ready.',
    bullets: ['Order taking', 'Table management', 'Shift reporting'],
    presentations: [
      { label: 'Order → Kitchen', url: '/presentations/ava-platform-horeca/ava-pos/order-{lang}.html' },
      { label: 'Bill & payment', url: '/presentations/ava-platform-horeca/ava-pos/payment-{lang}.html' },
      { label: 'Orders & floor', url: '/presentations/ava-platform-horeca/ava-pos/orders-{lang}.html' },
    ],
  },
  {
    slug: 'koshi',
    category: 'finance',
    name: 'KOSHI',
    tags: 'Financial / P&L / Cashflow',
    tagline: 'Financial accounting system: cash flows, P&L, budgets and real-time reporting.',
    bullets: ['Cash flows', 'P&L & budgets', 'Reporting'],
    presentations: [
      { label: 'Dashboard', url: '/presentations/koshi/dashboard.html' },
      { label: 'Transactions', url: '/presentations/koshi/transactions.html' },
      { label: 'Categories', url: '/presentations/koshi/categories.html' },
      { label: 'Budgets', url: '/presentations/koshi/budgets.html' },
    ],
  },
  {
    slug: 'ava-assistant',
    category: 'sales',
    name: 'AVA Assistant',
    tags: 'AI / Support / 24/7',
    tagline: 'Client-facing AI assistant: closes customer questions with professional answers, 24/7, and never misses a lead.',
    bullets: ['Professional answers', 'Available 24/7', 'No missed leads'],
    presentations: [
      { label: 'AI + human handoff', url: '/presentations/ava-assistant/demo-{lang}.html' },
      { label: 'Knowledge → Sandbox', url: '/presentations/ava-assistant/demo-knowledge-{lang}.html' },
      { label: 'Guest 360 / CRM', url: '/presentations/ava-assistant/demo-crm-{lang}.html' },
    ],
  },
  {
    slug: 'toros',
    category: 'ai',
    comingSoon: true,
    name: 'TOROS',
    tags: 'AI Agent / Automation / Control',
    tagline: 'AI agent that integrates on top of existing platforms or merges with ours — analysis, control and action.',
    bullets: ['Integrates on top', 'Merges with platforms', 'Analysis · control · action'],
    presentations: [
      { label: 'Demo', url: '/presentations/toros/index.html', poster: '/presentations/toros/poster.webp' },
    ],
  },
  {
    slug: 'teamhub',
    category: 'team',
    name: 'TeamHub',
    tags: 'HR / Onboarding / Training',
    tagline: 'HR platform for onboarding, training and testing — with a self-serve portal for every employee and a control console for HR.',
    bullets: ['Onboarding & training', 'Testing & knowledge base', 'HR control console'],
    presentations: [
      { label: 'Admin Console', url: '/presentations/teamhub/admin.html' },
      { label: 'Onboarding', url: '/presentations/teamhub/onboarding.html' },
      { label: 'Workspace', url: '/presentations/teamhub/workspace.html' },
    ],
  },
  {
    slug: 'solo-track',
    category: 'team',
    name: 'Solo Track',
    tags: 'Orders / Logistics / Pipeline',
    tagline: 'An operating system for complex orders — from request to final handover. Always know where each order stands, who owns the next step and what is still open.',
    bullets: ['End-to-end order pipeline', 'Documents, payments & suppliers', 'Logistics & handover'],
    presentations: [
      { label: 'Overview', url: '/presentations/solo-track/overview.html' },
      { label: 'Order Lifecycle', url: '/presentations/solo-track/order.html' },
      { label: 'Logistics', url: '/presentations/solo-track/logistics.html' },
      { label: 'Full Suite', url: '/presentations/solo-track/suite.html' },
    ],
  },
  {
    slug: 'oncheck',
    category: 'team',
    name: 'OnCheck',
    tags: 'Checklists / Standards / Tasks',
    tagline: 'A flexible system for automating daily checks, routine tasks and standards compliance — so the whole team knows what to do, when, and to what standard.',
    bullets: ['Custom checklists & standards', 'Tasks, media & data capture', 'Real-time results & reports'],
    presentations: [
      { label: 'Live Demo', url: '/presentations/oncheck/demo-{lang}.html' },
    ],
  },
  {
    slug: 'doit-ok',
    category: 'team',
    comingSoon: true,
    name: 'doit.ok',
    tags: 'Tasks / Board / Team',
    tagline: 'Team task manager where every task is a thread — discussion, files, subtasks and full history in one place.',
    bullets: ['Task = thread', 'Kanban board & assignees', 'Time tracking → cost'],
    // Coming soon: no live HTML demo yet — drawn SVG concept renders instead of
    // iframe presentations. ProductDetail renders these as images (see products.jsx).
    renders: [
      { label: 'Task flow', url: '/presentations/doit-ok/flow.svg' },
      { label: 'Team board', url: '/presentations/doit-ok/board.svg' },
      { label: 'Task = thread', url: '/presentations/doit-ok/thread.svg' },
    ],
  },
];
window.PRODUCTS = PRODUCTS;

/* ---------- Logo: uses the uploaded brand SVG (avasol_logo.svg), inlined via
   window.__AVASOL_LOGO__ so it inherits `currentColor` for light/dark variants. */
function Logo({ onDark = false, size = 28, style = {} }) {
  const data = (typeof window !== 'undefined' && window.__AVASOL_LOGO__) || null;
  if (!data) return <span style={{ display:'inline-block', height:size }} aria-label="Ava Solutions" />;
  // Native viewBox is 0 0 1907 793 → aspect ~2.405. Size prop = rendered height.
  const width = Math.round(size * (1907 / 793));
  // onDark forces cream inline; default leaves color to CSS cascade so
  // parent containers (e.g. .ticker.scrolled) can recolor via currentColor.
  const colorStyle = onDark ? { color: 'var(--cream)' } : {};
  return (
    <svg
      viewBox={data.viewBox}
      height={size}
      width={width}
      fill="currentColor"
      style={{ display:'inline-block', verticalAlign:'middle', ...colorStyle, ...style }}
      aria-label="Ava Solutions"
      dangerouslySetInnerHTML={{ __html: data.inner }}
    />
  );
}
/* Back-compat: LogoMark now just renders the integrated Logo at the requested size */
const LogoMark = Logo;

/* Sphere */
function Sphere({ variant = 'yellow', size = 240, style = {}, marble, parallax = 0 }) {
  const ref = useRef(null);
  useEffect(() => {
    if (!parallax) return;
    let raf;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        if (!ref.current) return;
        const rect = ref.current.getBoundingClientRect();
        const vh = window.innerHeight;
        const progress = (rect.top + rect.height/2 - vh/2) / vh;
        ref.current.style.setProperty('--py', `${-progress * parallax * 40}px`);
      });
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [parallax]);

  const marbleSize = marble?.size ?? size * 0.34;
  return (
    <div ref={ref} className={`sphere sphere--${variant}`}
      style={{ width:size, height:size, ...style, transform:`${style.transform||''} translateY(var(--py,0px))` }}>
      {marble && <span className="marble" style={{ width:marbleSize, height:marbleSize, left: marble.x ?? '22%', top: marble.y ?? '58%' }} />}
    </div>
  );
}

/* Top ticker */
function TopTicker({ active = 1 }) {
  const ref = useRef(null);
  useEffect(() => {
    const onScroll = () => { if (!ref.current) return; ref.current.classList.toggle('scrolled', window.scrollY > 40); };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const slogans = [
    'ENJOY YOUR LIFE WITH A SOLUTION','НАСОЛОДЖУЙТЕСЬ ЖИТТЯМ З РІШЕННЯМ','ソリューションで人生を楽しもう',
    'DISFRUTA LA VIDA CON UNA SOLUCIÓN','솔루션과 함께 인생을 즐기세요','PROFITEZ DE LA VIE AVEC UNE SOLUTION',
    'GENIESSE DAS LEBEN MIT EINER LÖSUNG','VIVI LA VITA CON UNA SOLUZIONE',
  ];
  const track = [...slogans, ...slogans];
  return (
    <header className="ticker" ref={ref}>
      <div className="ticker-inner">
        <a href="/#top"><Logo size={40} /></a>
        <div className="ticker-marquee">
          <div className="ticker-track">{track.map((s,i)=><span key={i}>{s} ·</span>)}</div>
        </div>
        <nav className="ticker-nav">
          <a href="/#top" className={active===1?'active':''}>01</a>
          <a href="/#foundation" className={active===2?'active':''}>02</a>
          <a href="/#approach" className={active===3?'active':''}>03</a>
          <a href="/#how" className={active===4?'active':''}>04</a>
          <a href="/#ownership" className={active===5?'active':''}>05</a>
          <a href="/#philosophy" className={active===6?'active':''}>06</a>
          <a href="/#contact" className={active===7?'active':''}>07</a>
        </nav>
        <LangToggle />
      </div>
    </header>
  );
}

/* Simple fade-in reveal (no motion) */
let __revealCounter = 0;
function Reveal({ children, delay=0, as:Tag='div', className='', style={}, ...rest }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) { el.style.opacity = 1; return; }
    const io = new IntersectionObserver(es => es.forEach(e => { if (e.isIntersecting) { el.style.opacity = 1; io.unobserve(el); } }), { threshold:.12 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return <Tag ref={ref} className={className} style={{ opacity:0, transition:`opacity .8s ease ${delay}ms`, ...style }} {...rest}>{children}</Tag>;
}

function CTAButton({ children, variant='dark', href='#contact' }) {
  return (
    <a href={href} className={`btn btn--${variant}`}>
      <span>{children}</span>
      <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M2 8h12M9 3l5 5-5 5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="square"/></svg>
    </a>
  );
}

/* Mid-page conversion band — sits between Cases (#cases) and ProductsTeaser.
   Yellow accent so it pops between the black Cases block and the cream teaser.
   No section number (an insert, like the proof-bar). */
function MidCta() {
  const { L } = useLang();
  const t = L.ctaBlocks.mid;
  return (
    <section className="midcta" aria-label={t.aria}>
      <div className="wrap midcta__inner">
        <Reveal>
          <h2 className="display display-md midcta__title">{t.title}</h2>
        </Reveal>
        <Reveal delay={100} className="midcta__sub body-lg">{t.sub}</Reveal>
        <Reveal delay={160} className="midcta__actions">
          <CTAButton variant="dark" href="#contact">{t.button}</CTAButton>
          <a href="#contact" className="midcta__micro mono">{t.micro}</a>
        </Reveal>
      </div>
    </section>
  );
}

/* Shared footer — used by the home page (Page5) and the products page. */
function Footer() {
  const { L } = useLang();
  const f = L.footer;
  return (
    <footer className="cream-on-black" style={{ padding:'0 0 clamp(96px,16vw,120px)' }}>
      <div className="wrap">
        <div className="footer-grid">
          <div>
            <Logo onDark size={48} />
            <div className="body" style={{ marginTop:14, opacity:.6, maxWidth:300 }}>{f.tagline}</div>
            <div className="mono" style={{ marginTop:22, opacity:.5 }}>© 2026 · Ava Solutions</div>
          </div>
          <div>
            <div className="mono" style={{ opacity:.5, marginBottom:12 }}>{f.products}</div>
            <ul style={{ listStyle:'none', display:'flex', flexDirection:'column', gap:6, fontSize:14 }}>
              {PRODUCTS.map(p=>(
                <li key={p.slug}><a href={`/products.html?p=${p.slug}`} style={{ color:'var(--cream)', textDecoration:'none' }}>{p.name}</a></li>
              ))}
              <li style={{ marginTop:4 }}><a href="/products.html" className="mono" style={{ opacity:.5, color:'var(--cream)', textDecoration:'none' }}>{f.allProducts}</a></li>
            </ul>
          </div>
          <div>
            <div className="mono" style={{ opacity:.5, marginBottom:12 }}>{f.build}</div>
            <ul style={{ listStyle:'none', display:'flex', flexDirection:'column', gap:6, fontSize:14 }}>
              {f.buildItems.map(p=><li key={p}>{p}</li>)}
            </ul>
          </div>
          <div>
            <div className="mono" style={{ opacity:.5, marginBottom:12 }}>{f.industries}</div>
            <ul style={{ listStyle:'none', display:'flex', flexDirection:'column', gap:6, fontSize:14 }}>
              {f.industryItems.map(p=><li key={p}>{p}</li>)}
            </ul>
          </div>
          <div>
            <div className="mono" style={{ opacity:.5, marginBottom:12 }}>{f.contact}</div>
            <ul style={{ listStyle:'none', display:'flex', flexDirection:'column', gap:8, fontSize:14 }}>
              <li style={{ display:'flex', flexDirection:'column', gap:2 }}>
                <span className="mono" style={{ opacity:.5, fontSize:11 }}>{f.emailLabel}</span>
                <a href="mailto:hello@avasolutions.studio" style={{ color:'var(--cream)', textDecoration:'none' }}>hello@avasolutions.studio</a>
              </li>
              <li style={{ display:'flex', flexDirection:'column', gap:2 }}>
                <span className="mono" style={{ opacity:.5, fontSize:11 }}>{f.tgLabel}</span>
                <a href="https://t.me/Toros_AvaSol_bot" onClick={(e)=>{ e.preventDefault(); window.avaOpenTelegram?.('footer_contact'); }} style={{ color:'var(--cream)', textDecoration:'none' }}>Toros</a>
              </li>
              <li style={{ opacity:.6 }}>{f.locations}</li>
            </ul>
          </div>
        </div>
        <div className="mono footer-nda">{f.nda}</div>
      </div>
    </footer>
  );
}

/* Home-page teaser band → links into the dedicated products page.
   Cream background (black text) so it doesn't form a black seam with the
   black Contact section that follows it. */
function ProductsTeaser() {
  const { L } = useLang();
  const t = L.teaser;
  return (
    <section id="products-teaser" className="prod-teaser black-on-cream" style={{ padding:'120px 0' }}>
      <div className="wrap">
        <div className="page-chapter"><span>{t.chapter.left}</span><span>{t.chapter.right}</span></div>
        <a href="/products.html" className="prod-teaser-link">
          <Reveal>
            <h2 className="display display-xl" style={{ marginTop:64, maxWidth:'14ch' }}>
              {t.title.pre}<br/><span style={{ display:'inline-block', background:'var(--yellow)', color:'var(--black)', padding:'0 18px 6px' }}>{t.title.accent}</span>
            </h2>
          </Reveal>
        </a>
        <div className="prod-teaser-list" style={{ marginTop:56 }}>
          {PRODUCTS.map((p,i)=>{
            const tags = (t.tags && t.tags[p.slug]) || p.tags;
            return (
            <Reveal key={p.slug} delay={i*60}>
              <a href={`/products.html?p=${p.slug}`} className="prod-teaser-row">
                <div className="mono prod-teaser-num">{String(i+1).padStart(2,'0')}</div>
                <div className="display display-sm prod-teaser-name">{p.name}</div>
                {tags && <div className="mono prod-teaser-tags">{tags}</div>}
              </a>
            </Reveal>
          );})}
        </div>
        <Reveal delay={PRODUCTS.length*60+60}>
          <div className="prod-teaser-ctarow">
            <a href="/products.html" className="prod-teaser-cta mono" style={{ display:'inline-block' }}>{t.cta}</a>
            <CTAButton variant="dark" href="#contact">{t.cta2}</CTAButton>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { Logo, LogoMark, Sphere, TopTicker, Reveal, CTAButton, MidCta, Footer, ProductsTeaser });
