// ingredient-ledger.jsx — az Excel adatbázisra (window.PS_DB) épülő összetevő-főkönyv,
// hover-kártyák (állítás + érdekesség + forrás), technológia-jelölés és termék-metaadatok.
const { useState: useLS, useRef: useLR, useEffect: useLE } = React;

const PS_STATUS_NOTE = {
  EU_AUTHORISED: 'ENGEDÉLYEZETT UNIÓS ÁLLÍTÁS',
  BOTANICAL_ON_HOLD_MATCHED: 'FÜGGŐBEN LÉVŐ UNIÓS ÁLLÍTÁS',
  BOTANICAL_ON_HOLD_REVIEW: 'FÜGGŐBEN LÉVŐ TÉTEL · EGYEZÉS ELLENŐRZÉS ALATT',
  COSMETIC_FUNCTION: 'KOZMETIKAI ÖSSZETEVŐ-FUNKCIÓ',
  COSMETIC_LABEL_REVIEW: 'ILLATÖSSZETEVŐ · JELÖLÉSKÖTELES',
};

function SourceLink({ label, url }) {
  if (!label) return null;
  if (!url) return <span style={{ color: 'var(--fg-3)' }}>{label}</span>;
  return (
    <a href={url} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--gold-deep)', borderBottom: '1px solid rgba(198,168,104,0.42)' }}>
      {label}<span aria-hidden="true" style={{ fontSize: '0.82em', marginLeft: 4, opacity: 0.7 }}>↗</span>
    </a>
  );
}

function IngSources({ ing }) {
  const pairs = [];
  if (ing.cs) pairs.push([ing.cs, ing.cu]);
  if (ing.fs && ing.fs !== ing.cs) pairs.push([ing.fs, ing.fu]);
  if (!pairs.length) return null;
  return (
    <div style={{ marginTop: 12, paddingTop: 10, borderTop: '1px solid var(--line)' }}>
      <div className="ps-tick" style={{ color: 'var(--fg-3)', marginBottom: 6 }}>FORRÁS</div>
      <div className="ps-small" style={{ display: 'flex', flexDirection: 'column', gap: 4, lineHeight: 1.5 }}>
        {pairs.map((p, i) => <SourceLink key={i} label={p[0]} url={p[1]} />)}
      </div>
    </div>
  );
}

// A hover/nyitott kártya tartalma. Egy helyen dől el, mit mutatunk — a lista, a
// rétegrajz és a technológia-panel is ezt használja.
function IngCard({ ing, wide }) {
  if (!ing) return null;
  const note = PS_STATUS_NOTE[ing.status];
  const techs = (ing.tech || []).map((id) => (window.PS_TECH || {})[id]).filter(Boolean);
  return (
    <div style={{ textAlign: 'left' }}>
      {ing.amount && <div className="ps-tick" style={{ color: 'var(--gold-deep)', marginBottom: 8 }}>{ing.amount}</div>}
      {ing.inci && <div className="ps-tick" style={{ color: 'var(--fg-3)', marginBottom: 10, textTransform: 'none', letterSpacing: '0.06em', fontStyle: 'italic' }}>{ing.inci}</div>}
      {ing.claim && <p className="ps-small" style={{ margin: '0 0 10px', color: 'var(--fg-bright)', lineHeight: 1.62 }}>{ing.claim}</p>}
      {ing.fact && <p className="ps-small" style={{ margin: 0, color: 'var(--fg-2)', lineHeight: 1.62 }}>{ing.fact}</p>}
      {note && (
        <div className="ps-tick" style={{ marginTop: 12, color: ing.onHold ? 'var(--fg-3)' : 'var(--gold-deep)', display: 'flex', gap: 8, alignItems: 'baseline', flexWrap: 'wrap' }}>
          <span style={{ opacity: 0.6 }}>·</span><span>{note}</span>
        </div>
      )}
      {wide && techs.length > 0 && (
        <div className="ps-tick" style={{ marginTop: 10, color: 'var(--fg-3)' }}>TECHNOLÓGIA · {techs.map((t) => t.name).join(' · ')}</div>
      )}
      <IngSources ing={ing} />
    </div>
  );
}

// ——— Összetevő-főkönyv: minden összetevő, sorrendben, lenyitható részletekkel ———
function IngRow({ ing, n, open, onToggle }) {
  return (
    <div className={'ps-ledger-row' + (open ? ' open' : '')}>
      <button onClick={onToggle} className="ps-ledger-head" aria-expanded={open}>
        <span className="ps-ledger-n">{String(n).padStart(2, '0')}</span>
        <span className="ps-ledger-name">
          {ing.n}
          {ing.inci && <em className="ps-ledger-inci">{ing.inci}</em>}
        </span>
        <span className="ps-ledger-amt">{ing.amount || ''}</span>
        <span className="ps-ledger-plus" aria-hidden="true">{open ? '−' : '＋'}</span>
      </button>
      {open && <div className="ps-ledger-body"><IngCard ing={ing} wide /></div>}
    </div>
  );
}

function IngredientLedger({ product, title }) {
  const [open, setOpen] = useLS(null);
  const db = product && product.db;
  const list = (db && db.ing) || [];
  if (!list.length) return null;
  const quantified = list.filter((i) => i.amount).length;
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 20, flexWrap: 'wrap', marginBottom: 16 }}>
        <Eyebrow gold>{title || 'ÖSSZETEVŐ-FŐKÖNYV'}</Eyebrow>
        <div className="ps-tick" style={{ color: 'var(--fg-3)' }}>
          {list.length} ÖSSZETEVŐ{quantified > 0 ? ` · ${quantified} MENNYISÉGGEL` : ''}
        </div>
      </div>
      <p className="ps-small" style={{ margin: '0 0 18px', color: 'var(--fg-3)', maxWidth: 560 }}>
        Nyisd le bármelyiket — ami tudható róla, ott van, a forrásával együtt.
      </p>
      <div className="ps-ledger">
        {list.map((ing, i) => (
          <IngRow key={ing.n + i} ing={ing} n={i + 1} open={open === i} onToggle={() => setOpen(open === i ? null : i)} />
        ))}
      </div>
    </div>
  );
}

// ——— Technológia ———
function TechDetail({ t, scope, basis }) {
  return (
    <div style={{ textAlign: 'left', borderLeft: '1px solid var(--line-gold)', paddingLeft: 18 }}>
      {scope && <div className="ps-tick" style={{ color: 'var(--gold-deep)', marginBottom: 10 }}>ALKALMAZÁSI KÖR · {scope}</div>}
      <p className="ps-body" style={{ margin: '0 0 12px', color: 'var(--fg-bright)' }}>{t.hover}</p>
      {t.fact && <p className="ps-small" style={{ margin: '0 0 12px', color: 'var(--fg-2)' }}>{t.fact}</p>}
      {basis && <p className="ps-small" style={{ margin: '0 0 12px', color: 'var(--fg-3)', fontStyle: 'italic' }}>{basis}</p>}
      {t.limit && (
        <p className="ps-small" style={{ margin: 0, color: 'var(--fg-3)', paddingTop: 10, borderTop: '1px solid var(--line)' }}>{t.limit}</p>
      )}
    </div>
  );
}

// A termékkép alatti technológia-jelölés: címke + kattintható panel.
// onRequest esetén nem itt nyitunk panelt (a kiemelt termék keretében nincs rá hely) —
// a kattintás a részletes adatlap technológia-szakaszára visz.
function TechStrip({ product, center, compact, onRequest }) {
  const [open, setOpen] = useLS(null);
  const db = product && product.db;
  const rel = (db && db.tech) || [];
  if (!rel.length) return null;
  return (
    <div style={{ marginTop: compact ? 10 : 18 }}>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, justifyContent: center ? 'center' : 'flex-start', alignItems: 'center' }}>
        <span className="ps-tick" style={{ color: 'var(--fg-3)' }}>TECHNOLÓGIA</span>
        {rel.map((r) => (
          <button key={r.tid} className={'ps-techchip' + (open === r.tid ? ' on' : '')}
            onClick={() => (onRequest ? onRequest(r.tid) : setOpen(open === r.tid ? null : r.tid))}>
            {r.name}<span aria-hidden="true" style={{ marginLeft: 8, opacity: 0.7 }}>{onRequest ? '→' : open === r.tid ? '−' : '＋'}</span>
          </button>
        ))}
      </div>
      {!onRequest && open && (window.PS_TECH || {})[open] && (
        <div style={{ marginTop: 16, maxWidth: 620, marginLeft: center ? 'auto' : 0, marginRight: center ? 'auto' : 0 }}>
          {(() => { const r = rel.find((x) => x.tid === open); return <TechDetail t={window.PS_TECH[open]} scope={r && r.scope} basis={r && r.basis} />; })()}
        </div>
      )}
    </div>
  );
}

// ——— Termék-metaadatok + teljes INCI ———
function ProductMeta({ product }) {
  const [inci, setInci] = useLS(false);
  const db = product && product.db;
  if (!db || !db.name) return null;
  const cells = [
    ['TERMÉKTÍPUS', db.type],
    ['KISZERELÉS', db.size],
    ['AJÁNLOTT HASZNÁLAT', db.dose],
    ['NOTIFIKÁCIÓ', db.notif],
  ].filter((c) => c[1]);
  return (
    <div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 1, background: 'var(--line)', border: '1px solid var(--line-strong)' }}>
        {cells.map((c, i) => (
          <div key={i} style={{ flex: '1 1 160px', padding: '14px 18px', background: 'var(--bg-panel)' }}>
            <div className="ps-tick" style={{ color: 'var(--fg-3)', marginBottom: 7 }}>{c[0]}</div>
            <div className="ps-small" style={{ color: 'var(--fg-bright)', lineHeight: 1.45 }}>{c[1]}</div>
          </div>
        ))}
      </div>
      {db.warn && (
        <p className="ps-small" style={{ margin: '18px 0 0', color: 'var(--fg-3)', whiteSpace: 'pre-line', borderLeft: '1px solid var(--line-gold)', paddingLeft: 16 }}>{db.warn}</p>
      )}
      {db.inci && (
        <div style={{ marginTop: 22 }}>
          <button onClick={() => setInci((o) => !o)} className="ps-inci-toggle">
            TELJES ÖSSZETEVŐ-LISTA {db.completeness ? `· ${db.completeness}` : ''}
            <span aria-hidden="true" style={{ marginLeft: 10 }}>{inci ? '−' : '＋'}</span>
          </button>
          {inci && (
            <p className="ps-small" style={{ margin: '14px 0 0', color: 'var(--fg-2)', whiteSpace: 'pre-line', lineHeight: 1.7 }}>{db.inci}</p>
          )}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { IngCard, IngSources, SourceLink, IngredientLedger, IngRow, TechStrip, TechDetail, ProductMeta, PS_STATUS_NOTE });
