// evaluate.jsx — «قيّم فكرتك»: PoAS (Proof of Axiomatic Synthesis) scoring engine + digital record

const POAS_TIERS = [
  { min: 85, accent: 'mint',   sig: 'SIG-QUANTUM-SCALE',  label: { ar: "طفرة أكسيوماتيكية تحويلية", en: "Axiomatic Breakthrough" },
    note: { ar: "قدّمها فوراً كبراءة اختراع — الأثر يتجاوز نطاق الإدارة الواحدة.", en: "File it as a patent — impact goes beyond a single department." } },
  { min: 60, accent: 'purple', sig: 'SIG-HIGH-VELOCITY',  label: { ar: "ابتكار عالي القيمة", en: "High-Impact Innovation" },
    note: { ar: "جاهزة لنموذج أولي ومسار تبنٍّ داخل التجمع.", en: "Ready for a prototype and an adoption path in the cluster." } },
  { min: 35, accent: 'gold',   sig: 'SIG-LOCAL-BOUNDED',  label: { ar: "اختراع بنيوي محلي", en: "Structural Invention" },
    note: { ar: "أثر واضح محلياً — اعمل على خفض مقاومة النظام لرفع النتيجة.", en: "Clear local impact — reduce system friction to raise the score." } },
  { min: 0,  accent: 'rose',   sig: 'SIG-HIGH-FRICTION',  label: { ar: "تحسين تدريجي هامشي", en: "Incremental Optimization" },
    note: { ar: "حسّن الجدة أو قلّل التكلفة قبل التقديم الرسمي.", en: "Improve novelty or cut cost before formal submission." } },
];

const POAS_METRICS = [
  { id: 'deltaP', sym: 'ΔP', min: 1, max: 10, step: .1, def: 8.5,
    label: { ar: "الجدة البنيوية", en: "Structural novelty" },
    hint: { ar: "كم الفكرة مختلفة عن الحلول القائمة؟", en: "How different is it from existing solutions?" } },
  { id: 'phiNet', sym: 'Φnet', min: 1, max: 10, step: .1, def: 9,
    label: { ar: "سرعة الانتشار والتبنّي", en: "Adoption velocity" },
    hint: { ar: "كم يسهل تبنّيها من الفرق والمستفيدين؟", en: "How easily do teams and users adopt it?" } },
  { id: 'xiFric', sym: 'Ξfric', min: .1, max: 10, step: .1, def: 2.1, inverse: true,
    label: { ar: "مقاومة النظام والتكلفة", en: "System friction & cost" },
    hint: { ar: "كلما قلّت العوائق والتكلفة ارتفعت النتيجة.", en: "Lower barriers and cost raise the score." } },
  { id: 'omegaScale', sym: 'Ωscale', min: 1, max: 6, step: 1, def: 5, exp: true,
    label: { ar: "أُس التوسّع الحجمي", en: "Scale exponent" },
    hint: { ar: "عدد المستفيدين المحتملين (١٠ أُس س).", en: "Potential beneficiaries (10^x)." } },
];

function poasScore(v) {
  const raw = ((v.deltaP * v.phiNet) / v.xiFric) * Math.log(Math.pow(10, v.omegaScale));
  return Math.min(Math.max((raw / 420) * 100, 0), 100);
}
function poasTier(score) { return POAS_TIERS.find(x => score >= x.min) || POAS_TIERS[POAS_TIERS.length - 1]; }
function poasHash(title, v, score, sig) {
  const str = `${title || 'UNTITLED'}-${v.deltaP}-${v.phiNet}-${score}-${Date.now()}`;
  let h = 0;
  for (let i = 0; i < str.length; i++) { h = ((h << 5) - h) + str.charCodeAt(i); h |= 0; }
  const hex = Math.abs(h).toString(16).toUpperCase().padStart(8, '0');
  return `PoAS-v1 :: ${hex} :: INV:${v.deltaP}-INN:${v.phiNet} :: ${sig} :: SCORE:${score}`;
}

/* ---- fusion fingerprint: a deterministic ridge glyph drawn from the hash ---- */
function seedOf(str) { let h = 2166136261; for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 16777619); } return Math.abs(h); }
function FingerprintGlyph({ code, size = 92 }) {
  const seed = seedOf(code);
  let s = seed;
  const rnd = () => (s = (s * 1664525 + 1013904223) >>> 0, s / 4294967296);
  const ridges = [];
  for (let i = 0; i < 9; i++) {
    const r = 8 + i * 4.6;
    const start = rnd() * 360;
    const sweep = 110 + rnd() * 180;
    const a1 = (start * Math.PI) / 180, a2 = ((start + sweep) * Math.PI) / 180;
    const large = sweep > 180 ? 1 : 0;
    ridges.push(`M ${(50 + r * Math.cos(a1)).toFixed(2)} ${(50 + r * Math.sin(a1)).toFixed(2)} A ${r} ${r} 0 ${large} 1 ${(50 + r * Math.cos(a2)).toFixed(2)} ${(50 + r * Math.sin(a2)).toFixed(2)}`);
  }
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" aria-hidden="true" style={{ flex: 'none' }}>
      <circle cx="50" cy="50" r="48" fill="none" stroke="currentColor" strokeWidth="1" opacity=".25" />
      <g fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" opacity=".85">
        {ridges.map((d, i) => <path key={i} d={d} opacity={0.4 + (i % 4) * 0.2} />)}
      </g>
      <circle cx="50" cy="50" r="3.2" fill="currentColor" />
    </svg>
  );
}

function QRBlock({ value, size = 132, onReady }) {
  const ref = React.useRef(null);
  const [ok, setOk] = React.useState(true);
  React.useEffect(() => {
    if (!window.QR || !ref.current) { setOk(false); return; }
    try {
      window.QR.canvas(ref.current, value, { width: size, margin: 2, color: { dark: '#04201a', light: '#ffffff' } });
      setOk(true);
      if (onReady) onReady(ref.current.toDataURL('image/png'));
    } catch (e) { setOk(false); }
  }, [value, size]);
  return (
    <div style={{ background: '#fff', padding: 8, borderRadius: 'var(--r-sm)', border: '1px solid var(--line)', display: 'grid', placeItems: 'center', minWidth: size + 16, minHeight: size + 16 }}>
      <canvas ref={ref} style={{ display: ok ? 'block' : 'none' }} />
      {!ok && <span style={{ color: '#04201a', fontSize: 12, textAlign: 'center', padding: 8 }}>QR</span>}
    </div>
  );
}

function EvaluatePage({ go, t, L, store, auth, embedded }) {
  const toast = useToast();
  const [title, setTitle] = React.useState('');
  const [v, setV] = React.useState(() => POAS_METRICS.reduce((a, m) => (a[m.id] = m.def, a), {}));
  const [record, setRecord] = React.useState(null);
  const qrRef = React.useRef(null);
  const set = (k, val) => { setV(s => ({ ...s, [k]: val })); setRecord(null); };

  const score = poasScore(v);
  const shown = score.toFixed(1);
  const tier = poasTier(score);
  const hash = React.useMemo(() => poasHash(title, v, shown, tier.sig), [title, v, shown, tier.sig]);

  const register = () => {
    const ref = 'POAS-' + new Date().getFullYear() + '-' + Math.floor(100 + Math.random() * 900);
    const rec = {
      ref, kind: 'poas', title: title.trim() || L({ ar: '(بدون عنوان)', en: '(untitled)' }),
      score: shown, classification: L(tier.label), signature: tier.sig, hash,
      metrics: { ...v }, submittedAt: new Date().toISOString(), status: 'review',
    };
    if (store && store.addSubmission) store.addSubmission('ideas', rec);
    setRecord(rec);
    toast(t('poas_saved'));
  };

  return (
    <div>
      {!embedded && <PageHeader go={go} t={t} eyebrow={t('poas_eyebrow')} title={t('poas_title')} sub={t('poas_sub')} icon="target" />}
      <section className={embedded ? '' : 'section tight'} style={embedded ? { display: 'contents' } : undefined}>
        <div className={embedded ? '' : 'wrap'} style={embedded ? { display: 'grid', gridTemplateColumns: 'minmax(0,1fr)', gap: 22, width: '100%', minWidth: 0 } : { maxWidth: 940, display: 'grid', gap: 22 }}>
          {embedded && (
            <div className="card card-pad" style={{ background: 'color-mix(in srgb, var(--gold) 8%, transparent)', borderColor: 'color-mix(in srgb, var(--gold) 26%, transparent)' }}>
              <div className="eyebrow" style={{ color: 'var(--gold)' }}><Icon.target s={15} /> {t('poas_title')}</div>
              <p className="muted" style={{ fontSize: 13.5, marginTop: 8, lineHeight: 1.7 }}>{t('poas_locked')}</p>
            </div>
          )}
          <div className="card card-pad" style={{ padding: 30, display: 'grid', gap: 22 }}>
            <Field label={t('poas_concept')} required>
              <input className="input" value={title} onChange={e => { setTitle(e.target.value); setRecord(null); }} placeholder={L({ ar: 'مثال: مسار فرز ذكي يقلّل زمن الانتظار في الطوارئ', en: 'e.g. Smart triage pathway cutting ER waiting time' })} />
            </Field>
            <div className="grid g2" style={{ gap: 22 }}>
              {POAS_METRICS.map(m => (
                <div key={m.id} className="field">
                  <label style={{ display: 'flex', justifyContent: 'space-between', gap: 10 }}>
                    <span>{L(m.label)} <span className="muted" style={{ fontWeight: 400 }} dir="ltr">({m.sym})</span></span>
                    <span style={{ color: 'var(--accent)', fontWeight: 700 }} dir="ltr">{m.exp ? '10^' + v[m.id] : Number(v[m.id]).toFixed(1)}</span>
                  </label>
                  <input type="range" className="poas-range" min={m.min} max={m.max} step={m.step} value={v[m.id]}
                    onChange={e => set(m.id, parseFloat(e.target.value))} />
                  <span className="help">{L(m.hint)}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="card card-pad center" style={{ padding: 34, background: `color-mix(in srgb, var(--${tier.accent}) 9%, transparent)`, borderColor: `color-mix(in srgb, var(--${tier.accent}) 32%, transparent)` }}>
            <div className="eyebrow" style={{ justifyContent: 'center' }}><Icon.target s={15} /> {t('poas_index')}</div>
            <div style={{ fontSize: 'clamp(52px, 9vw, 78px)', fontWeight: 800, lineHeight: 1, margin: '14px 0 6px', color: `var(--${tier.accent})`, fontFamily: 'Space Grotesk, monospace' }}>{shown}</div>
            <div className="poas-meter"><span style={{ width: shown + '%', background: `var(--${tier.accent})` }} /></div>
            <div className={"badge " + tier.accent} style={{ marginTop: 18, fontSize: 14, padding: '8px 16px' }}>{L(tier.label)}</div>
            <p className="muted" style={{ fontSize: 14.5, marginTop: 12, lineHeight: 1.7, maxWidth: 520, marginInline: 'auto' }}>{L(tier.note)}</p>
            <div className="poas-fusion">
              <QRBlock value={hash} size={132} onReady={(d) => { qrRef.current = d; }} />
              <div style={{ flex: 1, minWidth: 220, textAlign: 'start' }}>
                <div className="eyebrow" style={{ margin: 0 }}><Icon.shield s={14} /> {t('poas_fusion')}</div>
                <div style={{ display: 'flex', gap: 14, alignItems: 'center', marginTop: 10 }}>
                  <span style={{ color: `var(--${tier.accent})` }}><FingerprintGlyph code={hash} size={82} /></span>
                  <div style={{ minWidth: 0 }}>
                    <div className="poas-hash" dir="ltr">{hash}</div>
                    <div className="muted" style={{ fontSize: 12.5, marginTop: 8, lineHeight: 1.6 }}>{t('poas_fusion_d')}</div>
                  </div>
                </div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 20, flexWrap: 'wrap' }}>
              <button className="btn btn-primary btn-lg" disabled={!title.trim()} onClick={register}><Icon.shield s={18} /> {t('poas_register')}</button>
              <button className="btn btn-ghost" onClick={() => { copyText(hash); toast(t('copied')); }}><Icon.hash s={16} /> {t('poas_copy')}</button>
            </div>
            {record && (
              <div className="card" style={{ padding: 18, marginTop: 20, textAlign: 'start', display: 'grid', gap: 8 }}>
                <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
                  <span className="av" style={{ width: 32, height: 32, background: 'var(--accent)' }}><Icon.check s={16} /></span>
                  <b style={{ fontSize: 15.5 }}>{t('poas_saved')}</b>
                  <span className="chip on" style={{ marginInlineStart: 'auto' }}><Icon.hash s={13} /> {record.ref}</span>
                </div>
                <p className="muted" style={{ fontSize: 13.5, lineHeight: 1.7 }}>{t('poas_saved_d')}</p>
                <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                  <button className="btn btn-primary btn-sm" onClick={() => window.printPoasRecord(record, qrRef.current)}><Icon.book s={15} /> {t('poas_print')}</button>
                  <button className="btn btn-ghost btn-sm" onClick={() => go('idea')}><Icon.bulb s={15} /> {t('nav_idea')}</button>
                </div>
              </div>
            )}
          </div>

          <PriorArtPanel t={t} L={L} record={record || { title: title.trim(), hash, ref: '—', score: shown }} text={title} store={store} auth={auth} />

          <div className="card card-pad">
            <div className="eyebrow"><Icon.layers s={15} /> {t('poas_formula_t')}</div>
            <div className="poas-formula" dir="ltr">S<sub>PoAS</sub> = ((ΔP × Φnet) ÷ Ξfric) × ln(Ωscale)</div>
            <p className="muted" style={{ fontSize: 14, marginTop: 12, lineHeight: 1.75 }}>{t('poas_formula_d')}</p>
          </div>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { EvaluatePage, FingerprintGlyph, QRBlock, poasScore, poasTier, poasHash, POAS_TIERS, POAS_METRICS });
