/* Products page — two levels driven by the ?p=<slug> query parameter:
   • no slug  → calm overview catalogue (grouped cards, no iframes).
   • ?p=slug  → product detail (hero + live interactive demo rows + copy).
   Plain <a> links do full navigations, so the browser handles history, scroll
   and shareable/indexable URLs natively (no client-side router). A product may
   ship 1..N interactive HTML presentations; each becomes its own demo row. */

/* Fixed design viewport for the scaled live preview — presentations are built
   full-screen, so we render at this width and CSS-scale down to fit the column. */
const PROD_BASE_W = 1440;
const PROD_BASE_H = 900;

/* Merge structural product data (window.PRODUCTS) with localized copy (i18n). */
function useProductCopy(product) {
  const { L, lang } = useLang();
  const all = (L && L.products) || {};
  const copy = (product && all[product.slug]) || {};
  return {
    lang: lang || 'en',
    ui: all._ui || {},
    tagline: copy.tagline || (product && product.tagline) || '',
    bullets: copy.bullets || (product && product.bullets) || [],
    summary: copy.summary || copy.tagline || (product && product.tagline) || '',
    sections: copy.sections || [],
    demos: copy.demos || [],
  };
}

/* The "HTML side" of a row — tabs + scaled live wide-format preview. */
function ProductMedia({ presentations, selected, onSelect, onExpand, productName }) {
  const frameRef = React.useRef(null);
  const scaleRef = React.useRef(null);
  const [loaded, setLoaded] = React.useState(false);
  const [previewReady, setPreviewReady] = React.useState(false);
  const active = presentations[selected] || presentations[0];
  const openActive = React.useCallback(() => {
    if (active) onExpand(active);
  }, [active, onExpand]);
  const onPreviewKeyDown = React.useCallback((e) => {
    if (e.key !== 'Enter' && e.key !== ' ') return;
    e.preventDefault();
    openActive();
  }, [openActive]);

  // Lazy: only mount the iframe once the frame is near the viewport.
  React.useEffect(() => {
    if (loaded) return;
    const el = frameRef.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { setLoaded(true); io.disconnect(); } });
    }, { rootMargin: '400px' });
    io.observe(el);
    return () => io.disconnect();
  }, [loaded]);

  // Scale the full-size preview down to the column width on desktop and mobile.
  // This keeps each demo in a 1440×900 wide viewport instead of letting it reflow
  // into a phone layout inside the iframe.
  React.useLayoutEffect(() => {
    if (!loaded) return;
    const outer = frameRef.current;
    const scaler = scaleRef.current;
    if (!outer || !scaler) return;
    const apply = () => {
      const w = outer.clientWidth;
      const scale = w / PROD_BASE_W;
      scaler.style.transform = `scale(${scale})`;
      outer.style.height = `${PROD_BASE_H * scale}px`;
      setPreviewReady(true);
    };
    apply();
    const ro = new ResizeObserver(apply);
    ro.observe(outer);
    return () => ro.disconnect();
  }, [loaded]);

  return (
    <div className="prod-media">
      {presentations.length > 1 && (
        <div className="prod-tabs" role="tablist" aria-label={`${productName} demos`}>
          {presentations.map((p, i) => (
            <button
              key={p.url}
              type="button"
              role="tab"
              aria-selected={i === selected}
              className={`prod-tab mono ${i === selected ? 'is-active' : ''}`}
              onClick={() => onSelect(i)}
            >
              {p.label}
            </button>
          ))}
        </div>
      )}

      <div
        className="prod-frame prod-frame--live"
        ref={frameRef}
        role="button"
        tabIndex={0}
        aria-label={`Open ${productName} ${active.label || 'demo'} fullscreen`}
        onClick={openActive}
        onKeyDown={onPreviewKeyDown}
      >
        {loaded ? (
          <div
            className="prod-frame-scale"
            ref={scaleRef}
            style={{ width:PROD_BASE_W, height:PROD_BASE_H, opacity:previewReady ? 1 : 0 }}
          >
            <iframe
              key={active.url}
              src={active.url}
              title={`${productName} — ${active.label}`}
              loading="lazy"
              style={{ width:PROD_BASE_W, height:PROD_BASE_H, border:'none' }}
            />
          </div>
        ) : (
          <div className="prod-frame-shimmer" aria-hidden="true" />
        )}
      </div>
    </div>
  );
}

function PresentationModal({ presentation, productName, onClose }) {
  const viewportRef = React.useRef(null);
  const scaleRef = React.useRef(null);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [onClose]);

  React.useEffect(() => {
    const viewport = viewportRef.current;
    const scaler = scaleRef.current;
    if (!viewport || !scaler) return;
    const apply = () => {
      const scale = Math.min(viewport.clientWidth / PROD_BASE_W, viewport.clientHeight / PROD_BASE_H);
      scaler.style.transform = `scale(${scale})`;
    };
    apply();
    const ro = new ResizeObserver(apply);
    ro.observe(viewport);
    window.addEventListener('resize', apply);
    return () => { ro.disconnect(); window.removeEventListener('resize', apply); };
  }, []);

  return (
    <div className="prod-modal" role="dialog" aria-modal="true" aria-label={`${productName} demo`}>
      <button className="prod-modal__backdrop" type="button" aria-label="Close demo" onClick={onClose} />
      <div className="prod-modal__panel">
        <div className="prod-modal__bar">
          <span className="mono">{productName}{presentation.label ? ` · ${presentation.label}` : ''}</span>
          <button className="prod-modal__close" type="button" aria-label="Close" onClick={onClose}>×</button>
        </div>
        <div
          className="prod-modal__viewport"
          ref={viewportRef}
          style={{ flex:1, minHeight:0, overflow:'hidden', background:'#080808', display:'flex', alignItems:'center', justifyContent:'center' }}
        >
          <div
            className="prod-modal__scale"
            ref={scaleRef}
            style={{ width:PROD_BASE_W, height:PROD_BASE_H, flex:'0 0 auto', transformOrigin:'center center' }}
          >
            <iframe
              src={presentation.url}
              title={`${productName} — ${presentation.label} (wide screen)`}
              className="prod-modal__frame"
              style={{ display:'block', width:PROD_BASE_W, height:PROD_BASE_H, border:'none', background:'#fff' }}
            />
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- Overview (catalogue) ------------------------------------------- */

function ProductCard({ globalIndex, product }) {
  const { ui, tagline, bullets } = useProductCopy(product);
  return (
    <a className="prod-card" href={`/products.html?p=${product.slug}`}>
      <div className="prod-card-top">
        <span className="mono prod-card-num">{String(globalIndex + 1).padStart(2, '0')}</span>
        {product.comingSoon
          ? <span className="mono prod-card-badge">{ui.comingSoon || 'Coming soon'}</span>
          : <span className="prod-card-arrow" aria-hidden="true">→</span>}
      </div>
      <h3 className="display display-sm prod-card-name">{product.name}</h3>
      <p className="body prod-card-tagline">{tagline}</p>
      {bullets.length > 0 && (
        <ul className="prod-card-bullets">
          {bullets.map((b, i) => <li key={i} className="mono">{b}</li>)}
        </ul>
      )}
      <span className="mono prod-card-explore">{ui.explore} →</span>
    </a>
  );
}

function ProductsOverview({ products }) {
  const { L } = useLang();
  const ui = ((L && L.products) || {})._ui || {};
  const ov = ui.overview || {};
  const indexOf = (p) => products.indexOf(p);
  const groups = ov.groups || {};
  // Display order of categories; any unknown category falls to the end.
  const order = ['sales', 'finance', 'team', 'ai'];
  const seen = [];
  products.forEach((p) => { if (seen.indexOf(p.category) === -1) seen.push(p.category); });
  const cats = order.filter((c) => seen.indexOf(c) !== -1)
    .concat(seen.filter((c) => order.indexOf(c) === -1));

  return (
    <div className="prod-overview black-on-cream">
      <section style={{ padding:'150px 0 24px' }}>
        <div className="wrap">
          <div className="page-chapter"><span>{ov.eyebrow}</span><span>{ov.eyebrowRight}</span></div>
          <Reveal>
            <h1 className="display display-lg" style={{ marginTop:48, maxWidth:'14ch' }}>
              {ov.title && ov.title.pre}
              <span className="prod-accent">{ov.title && ov.title.accent}</span>
            </h1>
          </Reveal>
          <Reveal delay={120} className="body-lg text-wrap-pretty" style={{ marginTop:28, maxWidth:620, color:'var(--muted)' }}>
            {ov.intro}
          </Reveal>
        </div>
      </section>

      {cats.map((cat, gi) => {
        const items = products.filter((p) => p.category === cat);
        if (items.length === 0) return null;
        const g = groups[cat] || {};
        return (
          <section key={cat} className="prod-group" style={{ padding: gi === 0 ? '48px 0 0' : '72px 0 0' }}>
            <div className="wrap">
              <div className="prod-group-head">
                <h2 className="display display-sm">{g.title || cat}</h2>
                {g.note && <p className="body prod-group-note" style={{ color:'var(--muted)' }}>{g.note}</p>}
              </div>
              <div className="prod-card-grid">
                {items.map((p, i) => (
                  <Reveal key={p.slug} delay={i * 60}>
                    <ProductCard globalIndex={indexOf(p)} product={p} />
                  </Reveal>
                ))}
              </div>
            </div>
          </section>
        );
      })}
      <div style={{ paddingBottom:120 }} />
    </div>
  );
}

/* ---------- Detail (single product) ---------------------------------------- */

/* One demo row — caption on one side, the live scaled preview on the other. */
function DemoRow({ index, presentation, demo, productName, onExpand }) {
  const reversed = index % 2 === 1;
  const label = (demo && demo.label) || presentation.label || `Demo ${index + 1}`;
  return (
    <section className={`prod-row ${reversed ? 'prod-row--reversed' : ''}`}>
      <div className="wrap">
        <div className="prod-row-grid">
          <div className="prod-copy">
            <Reveal>
              <div className="mono prod-copy-num">{String(index + 1).padStart(2, '0')}</div>
              <h3 className="display display-sm" style={{ marginTop:12 }}>{label}</h3>
              {demo && demo.caption && (
                <p className="body-lg text-wrap-pretty" style={{ marginTop:16, maxWidth:460, color:'var(--muted)' }}>{demo.caption}</p>
              )}
              <button type="button" className="btn btn--dark" onClick={() => onExpand(presentation)} style={{ marginTop:26 }}>
                <span>Open demo</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>
              </button>
            </Reveal>
          </div>
          <div className="prod-media-col">
            <Reveal delay={120}>
              <ProductMedia
                presentations={[presentation]}
                selected={0}
                onSelect={() => {}}
                onExpand={onExpand}
                productName={productName}
              />
            </Reveal>
          </div>
        </div>
      </div>
    </section>
  );
}

/* One render row — a drawn (non-HTML) concept image instead of a live iframe.
   Used for coming-soon products that ship illustrative SVG renders (window
   product.renders) rather than interactive presentations. The image is a plain
   <img> (animated SVGs still play in <img>); clicking opens it full size. */
function RenderRow({ index, render, label, caption, productName, ui }) {
  const reversed = index % 2 === 1;
  return (
    <section className={`prod-row ${reversed ? 'prod-row--reversed' : ''}`}>
      <div className="wrap">
        <div className="prod-row-grid">
          <div className="prod-copy">
            <Reveal>
              <div className="mono prod-copy-num">{String(index + 1).padStart(2, '0')}</div>
              <h3 className="display display-sm" style={{ marginTop:12 }}>{label}</h3>
              {caption && (
                <p className="body-lg text-wrap-pretty" style={{ marginTop:16, maxWidth:460, color:'var(--muted)' }}>{caption}</p>
              )}
              <a className="mono prod-render-link" href={render.url} target="_blank" rel="noopener" style={{ marginTop:24 }}>
                {(ui && ui.viewRender) || 'Open full size'} ↗
              </a>
            </Reveal>
          </div>
          <div className="prod-media-col">
            <Reveal delay={120}>
              <a
                className="prod-frame prod-frame--render"
                href={render.url}
                target="_blank"
                rel="noopener"
                aria-label={`${productName} — ${label}`}
              >
                <img src={render.url} alt={`${productName} — ${label}`} loading="lazy" />
              </a>
            </Reveal>
          </div>
        </div>
      </div>
    </section>
  );
}

function ProductDetail({ products, product, onExpand }) {
  const { ui, summary, bullets, sections, demos, lang } = useProductCopy(product);
  // Resolve any {lang} placeholder in demo URLs so a product can ship a
  // language-matched demo (e.g. OnCheck: demo-en.html / demo-ru.html).
  const presentations = (product.presentations || []).map((p) => (
    p.url && p.url.indexOf('{lang}') !== -1
      ? { ...p, url: p.url.replace('{lang}', lang) }
      : p
  ));
  const idx = products.indexOf(product);
  const prev = products[(idx - 1 + products.length) % products.length];
  const next = products[(idx + 1) % products.length];

  // Per-product <title> + meta description for sharing / SEO.
  React.useEffect(() => {
    if (typeof document === 'undefined') return;
    document.title = `${product.name} — Ava Solutions`;
    let m = document.querySelector('meta[name="description"]');
    if (!m) { m = document.createElement('meta'); m.setAttribute('name', 'description'); document.head.appendChild(m); }
    if (summary) m.setAttribute('content', summary);
  }, [product.name, summary]);

  return (
    <div className="prod-detail black-on-cream">
      <section className="prod-detail-hero" style={{ padding:'140px 0 48px' }}>
        <div className="wrap">
          <a className="mono prod-detail-back" href="/products.html">← {ui.back}</a>
          {product.comingSoon && (
            <Reveal><span className="mono prod-detail-soon">{ui.comingSoon || 'Coming soon'}</span></Reveal>
          )}
          <Reveal>
            <h1 className="display display-md" style={{ marginTop:28, maxWidth:'16ch' }}>{product.name}</h1>
          </Reveal>
          <Reveal delay={100} className="body-lg text-wrap-pretty" style={{ marginTop:24, maxWidth:640, color:'var(--muted)' }}>
            {summary}
          </Reveal>
          {ui.aiAssistant && product.slug !== 'ava-assistant' && !product.renders && (
            <Reveal delay={130}>
              <div className="prod-ai-note">
                <span className="prod-ai-note-icon" aria-hidden="true">✦</span>
                <p className="body">{ui.aiAssistant}<sup>*</sup></p>
              </div>
            </Reveal>
          )}
          {bullets.length > 0 && (
            <Reveal delay={160}>
              <ul className="prod-copy-bullets" style={{ marginTop:24 }}>
                {bullets.map((b, i) => <li key={i} className="mono">{b}</li>)}
              </ul>
            </Reveal>
          )}
        </div>
      </section>

      {product.renders && product.renders.length > 0 ? (
        <div className="prod-detail-demos">
          <div className="wrap">
            <div className="page-chapter"><span>{ui.rendersTitle || 'Preview'}</span><span>{String(product.renders.length).padStart(2, '0')}</span></div>
            {ui.rendersNote && (
              <p className="mono prod-render-note" style={{ marginTop:14, color:'var(--muted)' }}>{ui.rendersNote}</p>
            )}
          </div>
          {product.renders.map((r, i) => (
            <RenderRow
              key={r.url}
              index={i}
              render={r}
              label={(demos[i] && demos[i].label) || r.label}
              caption={demos[i] && demos[i].caption}
              productName={product.name}
              ui={ui}
            />
          ))}
        </div>
      ) : presentations.length > 0 && (
        <div className="prod-detail-demos">
          <div className="wrap">
            <div className="page-chapter"><span>{ui.demosTitle}</span><span>{String(presentations.length).padStart(2, '0')}</span></div>
          </div>
          {presentations.map((p, i) => (
            <DemoRow key={p.url} index={i} presentation={p} demo={demos[i]} productName={product.name} onExpand={onExpand} />
          ))}
        </div>
      )}

      {sections.length > 0 && (
        <section className="prod-detail-sections" style={{ padding:'24px 0 96px' }}>
          <div className="wrap">
            <div className="prod-section-grid">
              {sections.map((s, i) => (
                <Reveal key={i} delay={i * 80} className="prod-section">
                  <h3 className="display display-sm">{s.title}</h3>
                  <p className="body-lg text-wrap-pretty" style={{ marginTop:14, color:'var(--muted)' }}>{s.body}</p>
                </Reveal>
              ))}
            </div>
          </div>
        </section>
      )}

      {ui.aiNote && (
        <section className="prod-detail-foot" style={{ padding:'0 0 72px' }}>
          <div className="wrap">
            <p className="mono prod-foot-note" style={{ color:'var(--muted)' }}><sup>*</sup> {ui.aiNote}</p>
          </div>
        </section>
      )}

      <section className="prod-detail-cta cream-on-black" style={{ padding:'96px 0' }}>
        <div className="wrap">
          <div className="prod-nav">
            <a className="mono prod-nav-link" href={`/products.html?p=${prev.slug}`}>← {ui.prev} · {prev.name}</a>
            <a className="mono prod-nav-link" href="/products.html">{ui.back}</a>
            <a className="mono prod-nav-link prod-nav-link--next" href={`/products.html?p=${next.slug}`}>{ui.next} · {next.name} →</a>
          </div>
          {ui.cta && (
            <div className="prod-cta-block">
              <h2 className="display display-sm" style={{ maxWidth:'18ch' }}>{ui.cta.line}</h2>
              <a className="btn btn--yellow" href="/#contact" style={{ marginTop:28 }}>
                <span>{ui.cta.button}</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>
            </div>
          )}
        </div>
      </section>
    </div>
  );
}

function ProductsPage() {
  const [expanded, setExpanded] = React.useState(null); // { presentation, productName }
  const products = window.PRODUCTS || [];

  const slug = React.useMemo(() => {
    try { return new URLSearchParams(window.location.search).get('p'); } catch { return null; }
  }, []);
  const product = products.find((p) => p.slug === slug) || null;

  const openExpand = React.useCallback((presentation, productName) => {
    setExpanded({ presentation, productName });
  }, []);

  return (
    <>
      {product
        ? <ProductDetail products={products} product={product} onExpand={(p) => openExpand(p, product.name)} />
        : <ProductsOverview products={products} />}
      {expanded && (
        <PresentationModal
          presentation={expanded.presentation}
          productName={expanded.productName}
          onClose={() => setExpanded(null)}
        />
      )}
    </>
  );
}

window.ProductsPage = ProductsPage;
