const { useState: useStateArch } = React;

const AUTHORIZED = {
  'C-vitamin': 'Hozzájárul az immunrendszer normál működéséhez, a normál kollagénképződéshez és a fáradtság csökkentéséhez.',
  'C-vitamin (Na-aszkorbát)': 'Hozzájárul az immunrendszer normál működéséhez, a normál kollagénképződéshez és a fáradtság csökkentéséhez.',
  'C-vitamin (L-aszkorbinsav)': 'Hozzájárul az immunrendszer normál működéséhez, a normál kollagénképződéshez és a fáradtság csökkentéséhez.',
  'D3-vitamin': 'Hozzájárul az immunrendszer normál működéséhez és a csontok normál állapotának fenntartásához.',
  'E-vitamin': 'Hozzájárul a sejtek oxidatív stresszel szembeni védelméhez.',
  'A-vitamin': 'Hozzájárul az immunrendszer normál működéséhez és a normál látás fenntartásához.',
  'B6-vitamin': 'Hozzájárul a normál energiatermelő anyagcseréhez és az idegrendszer normál működéséhez.',
  'B12-vitamin': 'Hozzájárul a fáradtság és a kifáradás csökkentéséhez, valamint a normál idegrendszeri működéshez.',
  'Folsav': 'Hozzájárul a normál pszichológiai funkcióhoz és a fáradtság csökkentéséhez.',
  'Biotin': 'Hozzájárul a normál energiatermelő anyagcseréhez és a haj normál állapotának megőrzéséhez.',
  'Cink': 'Hozzájárul a sejtek oxidatív stresszel szembeni védelméhez és az immunrendszer normál működéséhez.',
  'Szelén': 'Hozzájárul a sejtek oxidatív stresszel szembeni védelméhez és az immunrendszer normál működéséhez.',
};

function ArchComp({ c }) {
  const [open, setOpen] = useStateArch(false);
  const hostRef = React.useRef(null);
  const pos = open ? popoverPos(hostRef.current) : null;
  const info = (window.INGREDIENTS || {})[c.t];
  const claim = AUTHORIZED[c.t];
  const has = !!(info || claim);
  return (
    <span ref={hostRef} style={{ position: 'relative', display: 'inline-flex', flexDirection: 'column' }}
      onMouseEnter={() => has && setOpen(true)} onMouseLeave={() => setOpen(false)}>
      <button onClick={() => has && setOpen((o) => !o)} style={{
        fontSize: 11, letterSpacing: '0.02em', color: c.k ? 'var(--accent)' : 'var(--fg-2)',
        border: `1px solid ${c.k ? 'rgba(201,168,106,0.4)' : 'var(--line-strong)'}`, padding: '6px 13px',
        background: open ? 'rgba(201,168,106,0.1)' : 'transparent', cursor: has ? 'pointer' : 'default',
        fontFamily: 'var(--font-sans)', whiteSpace: 'nowrap',
      }}>{c.t}{has && <span style={{ color: 'var(--accent)', marginLeft: 7, opacity: 0.7 }}>＋</span>}</button>
      {open && has && (
        <div style={{ position: 'absolute', top: '100%', left: (pos && pos.left) || 0, marginTop: 6, zIndex: 6, width: (pos && pos.width) || 290, padding: '12px 14px', border: '1px solid var(--line-gold)', background: 'var(--bg-panel)', boxShadow: '0 18px 40px -18px rgba(0,0,0,0.5)', textAlign: 'left' }}>
          {info && info.dose && <div className="ps-tick" style={{ color: 'var(--accent)', marginBottom: 6 }}>{info.dose}</div>}
          {info && <p className="ps-small" style={{ margin: 0, color: 'var(--fg-2)' }}>{info.note}</p>}
          {claim && (
            <div style={{ marginTop: info ? 10 : 0, paddingTop: info ? 10 : 0, borderTop: info ? '1px solid var(--line)' : 'none' }}>
              <div className="ps-tick" style={{ color: 'var(--accent)', marginBottom: 5, fontSize: 9 }}>ENGEDÉLYEZETT ÁLLÍTÁS</div>
              <p className="ps-small" style={{ margin: 0, color: 'var(--fg-2)' }}>{claim}</p>
            </div>
          )}
        </div>
      )}
    </span>
  );
}

function popoverPos(el) {
  if (!el) return { left: 0 };
  const r = el.getBoundingClientRect();
  const w = Math.min(300, window.innerWidth - 24);
  let left = 0;
  if (r.left + w > window.innerWidth - 12) left = Math.min(0, window.innerWidth - 12 - w - r.left);
  if (r.left + left < 12) left = 12 - r.left;
  return { left, width: w };
}

const TECH_ALIAS = { 'Erjesztett': 'Fermentáció', 'Fermentáció': 'Fermentáció', 'Liposzómás': 'Liposzóma', 'Liposzóma': 'Liposzóma', 'Tradicionális kivonatolás': 'Tradicionális kivonatolás' };

function TechValue({ label }) {
  const [open, setOpen] = useStateArch(false);
  const hostRef = React.useRef(null);
  const pos = open ? popoverPos(hostRef.current) : null;
  const key = TECH_ALIAS[label];
  const info = key ? (window.INGREDIENTS || {})[key] : null;
  if (!info) return <div className="ps-h3" style={{ margin: 0, fontStyle: 'italic', fontSize: '1rem' }}>{label}</div>;
  return (
    <div ref={hostRef} style={{ position: 'relative' }} onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>
      <button onClick={() => setOpen((o) => !o)} className="ps-h3" style={{ margin: 0, fontStyle: 'italic', fontSize: '1rem', background: 'transparent', border: 'none', padding: 0, cursor: 'pointer', color: open ? 'var(--accent)' : 'inherit', borderBottom: '1px dotted var(--line-gold)', textAlign: 'left' }}>
        {label}<span style={{ color: 'var(--accent)', marginLeft: 7, fontSize: 11, opacity: 0.75 }}>＋</span>
      </button>
      {open && (
        <div style={{ position: 'absolute', top: '100%', left: (pos && pos.left) || 0, marginTop: 8, zIndex: 8, width: (pos && pos.width) || 300, padding: '12px 14px', border: '1px solid var(--line-gold)', background: 'var(--bg-panel)', boxShadow: '0 18px 40px -18px rgba(0,0,0,0.5)', textAlign: 'left' }}>
          {info.dose && <div className="ps-tick" style={{ color: 'var(--accent)', marginBottom: 6 }}>{info.dose}</div>}
          <p className="ps-small" style={{ margin: 0, color: 'var(--fg-2)' }}>{info.note}</p>
        </div>
      )}
    </div>
  );
}

function LayeredArchitecture({ archKey, product }) {
  const p = (window.PRODUCTS_ARCH || {})[archKey];
  if (!p) return null;
  const named = new Set();
  p.layers.forEach((L) => L.comps.forEach((c) => named.add(c.t.toLowerCase())));
  const extras = ((product && product.ingredients) || []).filter((n) => !named.has(String(n).toLowerCase()));
  return (
    <div style={{ padding: 'var(--sp-7) var(--gutter)', borderTop: '1px solid var(--line)', background: 'var(--bg-deep)' }}>
      <div style={{ maxWidth: 820, margin: '0 auto' }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 1, background: 'var(--line)', border: '1px solid var(--line-strong)', marginBottom: 'var(--sp-7)' }}>
          {p.designation.map((d, i) => (
            <div key={i} style={{ flex: '1 1 120px', padding: '14px 18px', background: 'var(--bg-panel)' }}>
              <div className="ps-tick" style={{ color: 'var(--fg-3)', marginBottom: 6 }}>{d[0]}</div>
              <TechValue label={d[1]} />
            </div>
          ))}
        </div>
        <div style={{ textAlign: 'center', marginBottom: 'var(--sp-7)', border: '1px solid var(--line)', padding: 'var(--sp-6)', background: 'linear-gradient(180deg, rgba(201,168,106,0.06), transparent)' }}>
          <Eyebrow gold style={{ justifyContent: 'center', marginBottom: 12 }}>{p.exLabel}</Eyebrow>
          <p className="ps-h3" style={{ margin: 0, fontStyle: 'italic', fontWeight: 400 }} dangerouslySetInnerHTML={{ __html: p.exText }} />
        </div>
        <div>
          {p.layers.map((L, i) => (
            <div key={i} style={{ borderTop: '1px solid var(--line)', padding: 'var(--sp-6) 0', display: 'grid', gridTemplateColumns: '140px 1fr', gap: 28 }} className="ps-arch-layer">
              <div>
                <div className="ps-h2" style={{ margin: '0 0 8px', fontStyle: 'italic', color: 'var(--accent)', opacity: 0.75 }}>{['i', 'ii', 'iii', 'iv', 'v'][i]}</div>
                <div className="ps-tick" style={{ color: 'var(--accent)', marginBottom: 8 }}>{L.role}</div>
                <p className="ps-small" style={{ margin: 0, color: 'var(--fg-3)' }}>{L.fn}</p>
              </div>
              <div>
                <h4 className="ps-h3" style={{ margin: '0 0 14px' }}>{L.title}</h4>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 16 }}>
                  {L.comps.map((c, j) => <ArchComp key={j} c={c} />)}
                </div>
                <p className="ps-body" style={{ margin: 0, color: 'var(--fg-2)', fontStyle: 'italic', borderLeft: '1px solid var(--line-gold)', paddingLeft: 16 }} dangerouslySetInnerHTML={{ __html: L.syn }} />
              </div>
            </div>
          ))}
          {extras.length > 0 && (
            <div style={{ borderTop: '1px solid var(--line)', padding: 'var(--sp-6) 0', display: 'grid', gridTemplateColumns: '140px 1fr', gap: 28 }} className="ps-arch-layer">
              <div>
                <div className="ps-tick" style={{ color: 'var(--fg-3)', marginBottom: 8 }}>TOVÁBBI ÖSSZETEVŐK</div>
                <p className="ps-small" style={{ margin: 0, color: 'var(--fg-3)' }}>Amik a rétegek mellett a formulában szerepelnek.</p>
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {extras.map((n, j) => <ArchComp key={j} c={{ t: n }} />)}
              </div>
            </div>
          )}
        </div>
        <div style={{ marginTop: 'var(--sp-8)', textAlign: 'center', border: '1px solid var(--line-strong)', padding: 'var(--sp-7)', background: 'linear-gradient(180deg, rgba(201,168,106,0.06), transparent)' }}>
          <Eyebrow gold style={{ justifyContent: 'center', marginBottom: 14 }}>A TECHNOLÓGIA</Eyebrow>
          <p className="ps-h3" style={{ margin: '0 0 14px', fontStyle: 'italic', fontWeight: 400 }} dangerouslySetInnerHTML={{ __html: p.ksText }} />
          {(p.tech || []).length > 0 && (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, justifyContent: 'center', margin: '18px 0' }}>
              {p.tech.map((t, j) => <ArchComp key={j} c={{ t, k: 1 }} />)}
            </div>
          )}
          <p className="ps-small" style={{ margin: '0 auto', maxWidth: 520, color: 'var(--fg-3)' }}>{p.ksSub}</p>
        </div>
        {p.meta && <p className="ps-small" style={{ marginTop: 'var(--sp-6)', textAlign: 'center', color: 'var(--fg-faint)' }}>{p.meta}</p>}
      </div>
    </div>
  );
}

function ProductDetails({ product }) {
  if (!product || product.soon) return null;
  if (product.archKey && (window.PRODUCTS_ARCH || {})[product.archKey]) {
    return <LayeredArchitecture archKey={product.archKey} product={product} />;
  }
  return <DetailsPanel product={product} />;
}

Object.assign(window, { LayeredArchitecture, ProductDetails, AUTHORIZED });
