// pictograms.jsx — Positeam piktogram-rendszer.
// Blueprint keret (1px + registration tickek), konkrét ábrázoló vonalrajz, tracked
// uppercase felirat. Minden jelölés az adatbázisból vezetődik le; hoverben ott a
// magyarázat és az adat-alap. Ahol az összetevőlista részleges, mentességet NEM
// jelölünk — hiányos listából a hiány nem bizonyíték.
const { useState: usePgState, useRef: usePgRef } = React;

const PG_ART = {
  ferment: <g><path d="M11 5h10M13 5v4l-2.6 3.6V25a2 2 0 002 2h7.2a2 2 0 002-2V12.6L19 9V5" /><path d="M10.4 16h11.2" opacity=".6" /><circle cx="14" cy="21.5" r="1.5" /><circle cx="18.4" cy="19" r="1" /><circle cx="17" cy="24" r="1.9" /></g>,
  liposome: <g><circle cx="16" cy="16" r="10.5" /><circle cx="16" cy="16" r="7.4" opacity=".65" /><path d="M16 11.4c2.1 2.7 3.1 4.4 3.1 5.8a3.1 3.1 0 01-6.2 0c0-1.4 1-3.1 3.1-5.8z" /></g>,
  micron: <g><path d="M6.5 14.5h19" /><path d="M8.4 14.5c.5 5.8 3.6 8.9 7.6 8.9s7.1-3.1 7.6-8.9" /><path d="M16 23.4v3.2M11 26.6h10" /><path d="M21.5 4.4l-5.6 8.4M20.2 3.4l2.9 1.9" /><circle cx="12" cy="10" r=".9" opacity=".7" /><circle cx="24" cy="10.5" r=".9" opacity=".7" /><circle cx="19" cy="7" r=".7" opacity=".5" /></g>,
  retort: <g><path d="M12 5h6.5M13.4 5v4.6l-3.6 7.2a6.6 6.6 0 1013.2 0L19.4 9.6V5" /><path d="M22.4 16.2l5.6 3.4" /><path d="M28 27.2c-1.3 0-2.2-1-2.2-2.2 0-1.3 2.2-4 2.2-4s2.2 2.7 2.2 4c0 1.2-.9 2.2-2.2 2.2z" /></g>,
  glass: <g><path d="M10 5h12l-1.6 17.4a2.2 2.2 0 01-2.2 2H13.8a2.2 2.2 0 01-2.2-2L10 5z" /><path d="M10.9 13h10.2" opacity=".6" /><path d="M16 24.4v3.2M12 27.6h8" /></g>,
  spray: <g><path d="M12.6 12h6.8a2 2 0 012 2v11.4a2 2 0 01-2 2h-6.8a2 2 0 01-2-2V14a2 2 0 012-2z" /><path d="M13.4 12V8.6h5.2V12" /><path d="M18.6 9.6h3.4V7" /><path d="M25 5.6h2.6M25 8.4h3.6M25.6 11.4h2.2" opacity=".75" /></g>,
  jar: <g><path d="M8.6 13h14.8v11.6a2.4 2.4 0 01-2.4 2.4H11a2.4 2.4 0 01-2.4-2.4V13z" /><path d="M7 9h18v4H7z" /><path d="M11.4 5.6h9.2V9" opacity=".7" /></g>,
  layers: <g><path d="M16 5l10 4.2-10 4.2L6 9.2 16 5z" /><path d="M6 15l10 4.2L26 15" /><path d="M6 21l10 4.2L26 21" opacity=".7" /></g>,
  cluster: <g><circle cx="9" cy="9" r="2" /><circle cx="16" cy="9" r="2" /><circle cx="23" cy="9" r="2" /><circle cx="9" cy="16" r="2" /><circle cx="16" cy="16" r="2" /><circle cx="23" cy="16" r="2" /><circle cx="9" cy="23" r="2" opacity=".6" /><circle cx="16" cy="23" r="2" opacity=".6" /><circle cx="23" cy="23" r="2" opacity=".6" /></g>,
  scale: <g><path d="M16 5.4v17M9.6 27h12.8" /><path d="M16 22.4c-2.6 0-4.6 2-4.6 4.6h9.2c0-2.6-2-4.6-4.6-4.6z" opacity=".7" /><path d="M5 10.6h22" /><path d="M5 10.6L2.4 17a3.6 3.6 0 005.2 0L5 10.6z" /><path d="M27 10.6L24.4 17a3.6 3.6 0 005.2 0L27 10.6z" /></g>,
  drops: <g><path d="M10 19.6c-1.9 0-3.4-1.5-3.4-3.4 0-2 3.4-6.2 3.4-6.2s3.4 4.2 3.4 6.2c0 1.9-1.5 3.4-3.4 3.4z" /><path d="M22 15.6c-1.7 0-3-1.4-3-3 0-1.8 3-5.6 3-5.6s3 3.8 3 5.6c0 1.6-1.3 3-3 3z" opacity=".75" /><path d="M16 27c-1.5 0-2.7-1.2-2.7-2.7 0-1.6 2.7-5 2.7-5s2.7 3.4 2.7 5c0 1.5-1.2 2.7-2.7 2.7z" opacity=".55" /></g>,
  leaf: <g><path d="M16 27V12" /><path d="M16 15.4c0-5 3.4-9 9.4-10-.6 6.2-4 10-9.4 10z" /><path d="M16 21.4c0-4-2.8-7.2-7.6-8 .5 5 3.2 8 7.6 8z" opacity=".75" /></g>,
  doc: <g><path d="M8 4h11l5 5v19H8z" /><path d="M19 4v5h5" opacity=".7" /><path d="M11.6 14h9M11.6 18h9M11.6 22h6" opacity=".8" /></g>,
  seal: <g><circle cx="16" cy="14" r="8.4" /><circle cx="16" cy="14" r="5.4" opacity=".6" /><path d="M11.6 21.4L10 29l6-2.6 6 2.6-1.6-7.6" /></g>,
  target: <g><circle cx="16" cy="16" r="11" /><circle cx="16" cy="16" r="6.4" opacity=".7" /><circle cx="16" cy="16" r="1.8" /><path d="M16 2v5M16 25v5M2 16h5M25 16h5" opacity=".65" /></g>,
  sun: <g><circle cx="16" cy="16" r="6.6" /><path d="M16 3v4.4M16 24.6V29M3 16h4.4M24.6 16H29M7 7l3.1 3.1M21.9 21.9L25 25M25 7l-3.1 3.1M10.1 21.9L7 25" opacity=".8" /></g>,
  mouth: <g><path d="M5 16c3.6-4.6 7.3-6.9 11-6.9S23.4 11.4 27 16c-3.6 4.6-7.3 6.9-11 6.9S8.6 20.6 5 16z" /><path d="M8.6 16h14.8" opacity=".7" /><path d="M13 12.4l1.4 3.6-1.4 3.6M19 12.4l-1.4 3.6L19 19.6" opacity=".55" /></g>,
  molecule: <g><path d="M16 6l6.9 4v8L16 22l-6.9-4v-8L16 6z" /><path d="M16 6v6M22.9 10L16 14M9.1 10L16 14M16 14v8" opacity=".7" /><circle cx="16" cy="6" r="1.8" /><circle cx="22.9" cy="18" r="1.8" /><circle cx="9.1" cy="18" r="1.8" /></g>,
  siliconedrop: <g><path d="M16 26c-3.6 0-6.5-2.9-6.5-6.5C9.5 15.6 16 6 16 6s6.5 9.6 6.5 13.5c0 3.6-2.9 6.5-6.5 6.5z" /><path d="M13.4 19.6a2.6 2.6 0 002.6 2.6" opacity=".6" /></g>,
  barrel: <g><path d="M9.4 7h13.2c-.9 3-.9 15 0 18H9.4c.9-3 .9-15 0-18z" /><path d="M8.6 12.4h14.8M8.6 19.6h14.8" opacity=".7" /></g>,
  perfume: <g><path d="M11.4 13h9.2a1.8 1.8 0 011.8 1.8v11.4a1.8 1.8 0 01-1.8 1.8h-9.2a1.8 1.8 0 01-1.8-1.8V14.8a1.8 1.8 0 011.8-1.8z" /><path d="M13.4 13V9.4h5.2V13" /><path d="M14.6 6.4h2.8v3h-2.8z" opacity=".7" /><path d="M23.6 6.6l2.4-1.4M24.4 10h2.8M23.6 13.4l2.4 1.4" opacity=".6" /></g>,
  foam: <g><circle cx="10.6" cy="19.4" r="4.4" /><circle cx="19" cy="17" r="5.4" /><circle cx="24.4" cy="21.4" r="3.4" opacity=".75" /><path d="M5 27h22" opacity=".6" /></g>,
  chain: <g><rect x="4.6" y="12.6" width="10.4" height="6.8" rx="3.4" /><rect x="17" y="12.6" width="10.4" height="6.8" rx="3.4" /><path d="M13.4 16h5.2" opacity=".7" /></g>,
  wheat: <g><path d="M16 28V10" /><path d="M16 10c-2.4-1.4-3.6-3.6-3.6-6.4C15 4.8 16.2 7 16 10zM16 15c-2.8-.6-4.6-2.4-5.4-5.2 3 .4 4.9 2.1 5.4 5.2zM16 15c2.8-.6 4.6-2.4 5.4-5.2-3 .4-4.9 2.1-5.4 5.2zM16 20.4c-2.8-.6-4.6-2.4-5.4-5.2 3 .4 4.9 2.1 5.4 5.2zM16 20.4c2.8-.6 4.6-2.4 5.4-5.2-3 .4-4.9 2.1-5.4 5.2z" /></g>,
  milk: <g><path d="M11 12h10v15.4H11z" /><path d="M11 12l2.6-5.4h4.8L21 12" /><path d="M13.6 6.6V4h4.8v2.6" opacity=".7" /><path d="M11 18.4h10" opacity=".6" /></g>,
  nano: <g><circle cx="16" cy="16" r="2.4" /><circle cx="8" cy="10" r="1.6" opacity=".8" /><circle cx="24" cy="10" r="1.6" opacity=".8" /><circle cx="8" cy="22" r="1.6" opacity=".8" /><circle cx="24" cy="22" r="1.6" opacity=".8" /><circle cx="16" cy="6" r="1.2" opacity=".55" /><circle cx="16" cy="26" r="1.2" opacity=".55" /><circle cx="5" cy="16" r="1.2" opacity=".55" /><circle cx="27" cy="16" r="1.2" opacity=".55" /></g>,
  paint: <g><path d="M16 26.4c-3.4 0-6.2-2.8-6.2-6.2 0-3.7 6.2-13 6.2-13s6.2 9.3 6.2 13c0 3.4-2.8 6.2-6.2 6.2z" /><path d="M10.4 18.6c3.8 2.6 7.4 2.6 11.2 0" opacity=".65" /></g>,
};

// Családszínek. Nem termékenként egy szín (attól csupa zold lett), hanem
// jelentéscsoportonként — a világos bone háttérhez sötétített tónusokban.
const PG_FAM_TONE = {
  tech: '#8A6D2E', route: '#2F6E5A', struct: '#4A5A7A', notif: '#3D6B3A',
  free: '#4E6B34', complex: '#7D4A75', synergy: '#8E5A2F', dose: '#56537A',
};

// Fokmérő-szakaszok: alsó / középső / felső harmad külön színnel — innen jön a
// sávfelirat színe is.
const PG_STEPS = [
  [0.4, '#8C8574'], [0.7, '#9A7A1E'], [1.01, '#3D6B3A'],
];
function pgStepTone(v) {
  for (let i = 0; i < PG_STEPS.length; i++) { if (v < PG_STEPS[i][0]) return PG_STEPS[i][1] }
  return PG_STEPS[PG_STEPS.length - 1][1];
}

// Sávos fokozat — nem százalék, hanem elhelyezés a skálán.
const PG_BANDS = [
  [0.2, 'MINIMÁLIS'], [0.4, 'ALACSONY'], [0.6, 'KÖZEPES'], [0.8, 'JELENTŐS'], [1.01, 'KIEMELKEDŐ'],
];
function pgBand(v) {
  for (let i = 0; i < PG_BANDS.length; i++) { if (v < PG_BANDS[i][0]) return PG_BANDS[i][1] }
  return PG_BANDS[PG_BANDS.length - 1][1];
}

function PgIcon({ art, size = 40, cross }) {
  return (
    <svg viewBox="0 0 32 32" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" style={{ display: 'block', overflow: 'visible' }}>
      {PG_ART[art] || PG_ART.cluster}
      {cross && <path d="M4.5 27.5L27.5 4.5" strokeWidth="1.4" />}
    </svg>
  );
}

// Fokmérő: három színszakasz + mutató. Nem állít, csak skálán elhelyez.
function PgGauge({ value = 0.5, size = 40 }) {
  const val = Math.min(1, Math.max(0, value));
  const cx = 16, cy = 21, r = 12;
  const pt = (t, rad) => [cx + Math.cos(Math.PI * (1 - t)) * rad, cy - Math.sin(Math.PI * (1 - t)) * rad];
  const arc = (from, to, rad) => {
    const [x1, y1] = pt(from, rad), [x2, y2] = pt(to, rad);
    return `M${x1.toFixed(2)} ${y1.toFixed(2)}A${rad} ${rad} 0 0 1 ${x2.toFixed(2)} ${y2.toFixed(2)}`;
  };
  const [nx, ny] = pt(val, r - 2.5);
  const segs = [[0, 0.32, PG_STEPS[0][1]], [0.34, 0.64, PG_STEPS[1][1]], [0.66, 1, PG_STEPS[2][1]]];
  return (
    <svg viewBox="0 0 32 32" width={size} height={size} fill="none" strokeLinecap="round" aria-hidden="true" style={{ display: 'block' }}>
      {segs.map((s, i) => {
        const lit = val >= s[0];
        return <path key={i} d={arc(s[0], s[1], r)} stroke={s[2]} strokeWidth={lit ? 3.4 : 2.4} opacity={lit ? 1 : 0.24} />;
      })}
      {[0, 0.25, 0.5, 0.75, 1].map((t, i) => {
        const [ax, ay] = pt(t, r + 1.8), [bx, by] = pt(t, r + 3.8);
        return <path key={i} d={`M${ax.toFixed(2)} ${ay.toFixed(2)}L${bx.toFixed(2)} ${by.toFixed(2)}`} stroke="currentColor" strokeWidth="1" opacity=".4" />;
      })}
      <path d={`M${cx} ${cy}L${nx.toFixed(2)} ${ny.toFixed(2)}`} stroke="currentColor" strokeWidth="1.4" />
      <circle cx={cx} cy={cy} r="2" fill="currentColor" />
    </svg>
  );
}

function Pictogram({ pg, size = 40 }) {
  const [box, setBox] = usePgState(null);
  const hostRef = usePgRef(null);
  const open = !!box;
  const tone = pg.gauge != null ? pgStepTone(pg.gauge) : (PG_FAM_TONE[pg.fam] || 'var(--gold-deep)');

  // A kiemelt termék keretének `overflow:hidden`-je bármilyen belső popovert levág,
  // ezért a magyarázat portalon, fix pozicionálással kerül a body-ra.
  const place = () => {
    const el = hostRef.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    const vw = window.innerWidth, vh = window.innerHeight;
    const w = Math.min(320, vw - 24);
    const est = 210;
    const below = vh - r.bottom > est || r.top < est;
    setBox({
      left: Math.max(12, Math.min(r.left, vw - w - 12)),
      width: w,
      below,
      top: below ? Math.round(r.bottom + 8) : null,
      bottom: below ? null : Math.round(vh - r.top + 8),
    });
  };

  React.useEffect(() => {
    if (!open) return;
    const close = () => setBox(null);
    window.addEventListener('scroll', close, { passive: true, capture: true });
    window.addEventListener('resize', close);
    return () => {
      window.removeEventListener('scroll', close, { capture: true });
      window.removeEventListener('resize', close);
    };
  }, [open]);

  const card = open && ReactDOM.createPortal(
    <div className="ps-pg-tip" style={{ left: box.left, width: box.width, top: box.top != null ? box.top : undefined, bottom: box.bottom != null ? box.bottom : undefined, borderColor: tone || undefined }}>
      <div className="ps-tick" style={{ color: tone || 'var(--gold-deep)', marginBottom: 8, fontWeight: 600 }}>{pg.title}</div>
      <p className="ps-small" style={{ margin: '0 0 10px', color: 'var(--fg-bright)', lineHeight: 1.6 }}>{pg.explain}</p>
      {pg.basis && <p className="ps-small" style={{ margin: 0, paddingTop: 9, borderTop: '1px solid var(--line)', color: 'var(--fg-3)', lineHeight: 1.55 }}>{pg.basis}</p>}
    </div>,
    document.body
  );

  return (
    <div ref={hostRef} className={'ps-pg' + (open ? ' on' : '')} style={{ '--pg-tone': tone }} onMouseEnter={place} onMouseLeave={() => setBox(null)}>
      <button className="ps-pg-btn" onClick={() => (open ? setBox(null) : place())} aria-expanded={open}>
        <span className="ps-pg-frame" style={{ width: size + 16, height: size + 16 }}>
          {pg.gauge != null ? <PgGauge value={pg.gauge} size={size} /> : <PgIcon art={pg.art} size={size} cross={pg.cross} />}
        </span>
        <span className="ps-pg-label">
          {pg.band && <em className="ps-pg-band">{pg.band}</em>}
          {pg.value && <em className="ps-pg-value">{pg.value}</em>}
          {pg.label}
        </span>
      </button>
      {card}
    </div>
  );
}

const PG_GROUPS = [
  { id: 'g1', title: 'A FORMULA MÉRTÉKE', fams: ['complex', 'synergy'] },
  { id: 'g2', title: 'AZ ELJÁRÁS ÉS A HASZNÁLAT', fams: ['tech', 'route', 'notif'] },
  { id: 'g3', title: 'A FORMULA SZERKEZETE', fams: ['struct'] },
  { id: 'g4', title: 'AMIT NEM TARTALMAZ', fams: ['free'] },
];

function PictogramSet({ product, layout }) {
  const list = (window.PS_BUILD_PICTOGRAMS ? window.PS_BUILD_PICTOGRAMS(product && product.id) : []) || [];
  if (!list.length) return null;
  const groups = PG_GROUPS.map((g) => ({ g, items: list.filter((p) => g.fams.indexOf(p.fam) >= 0) })).filter((x) => x.items.length);
  return (
    <div className={'ps-pgset ' + (layout || 'row')}>
      {groups.map(({ g, items }) => (
        <section key={g.id} className="ps-pggroup">
          <h4 className="ps-pggroup-h">{g.title}</h4>
          <div className="ps-pggrid">
            {items.map((pg) => <Pictogram key={pg.id} pg={pg} size={layout === 'col' ? 36 : 42} />)}
          </div>
        </section>
      ))}
      <p className="ps-pg-foot">＊ A grafikai jelölések tájékoztató jellegűek — mindegyik a termék összetevő-adatlapjából vezethető le. Vidd rá a kurzort a magyarázatért.</p>
    </div>
  );
}

Object.assign(window, { Pictogram, PictogramSet, PgIcon, PgGauge, PG_ART, PG_FAM_TONE, PG_GROUPS, pgBand, pgStepTone });
