// grading.jsx — interactive two-axis ingredient grading matrix
// Plottable 2D field (efficacy × microbiome) with hand-illustrated ingredient marks.

const { useState: useGState, useRef: useGRef, useEffect: useGEffect } = React;

const INGREDIENTS = [
  { name: 'Niacinamide',     eff: 0.92, bio:  0.45, cat: 'cell-signalling', hue: '#7FB3A0', summary: 'Strong evidence for barrier support via ceramide synthesis upregulation. Neutral-supportive on biome at cosmetic concentrations.' },
  { name: 'Retinaldehyde',   eff: 0.95, bio:  0.05, cat: 'retinoid',         hue: '#E8C896', summary: 'Top-tier efficacy for photoageing. Biome impact context-dependent — introduce slowly to preserve barrier.' },
  { name: 'Squalane',        eff: 0.65, bio:  0.7,  cat: 'occlusive',        hue: '#B8D4C2', summary: 'Mimics native sebum. Biome-supportive emollient, gentle even on compromised barriers.' },
  { name: 'Ceramide NP',     eff: 0.85, bio:  0.55, cat: 'lipid',            hue: '#D9E8C9', summary: 'Replenishes structural lipids in the stratum corneum. Supports both barrier integrity and biome stability.' },
  { name: 'Salicylic acid',  eff: 0.85, bio: -0.15, cat: 'BHA',              hue: '#E8C896', summary: 'Lipid-soluble exfoliant; high efficacy for comedonal concerns. Mildly disruptive at high concentrations or frequency.' },
  { name: 'Glycolic acid',   eff: 0.78, bio: -0.4,  cat: 'AHA',              hue: '#F0DCD0', summary: 'Effective surface renewal. Can lower skin pH and acutely shift the biome — moderate use only.' },
  { name: 'Hyaluronic acid', eff: 0.45, bio:  0.6,  cat: 'humectant',        hue: '#D9E8C9', summary: 'Humectant with modest efficacy on hydration. Biome-neutral and well-tolerated.' },
  { name: 'Panthenol',       eff: 0.6,  bio:  0.6,  cat: 'soothing',         hue: '#B8D4C2', summary: 'Pro-vitamin B5. Calms redness and supports barrier repair. Gentle on biome.' },
  { name: 'SLS',             eff: 0.35, bio: -0.85, cat: 'surfactant',       hue: '#E8A89C', summary: 'Effective foaming surfactant but strips lipids and acutely depletes biome diversity. Avoid in leave-on formats.' },
  { name: 'Fragrance mix',   eff:-0.1,  bio: -0.6,  cat: 'sensitiser',       hue: '#E8B8C5', summary: 'No efficacy benefit and a common cause of sensitisation. Worth watching if your barrier feels fragile.' },
  { name: 'Methylisothiazolinone', eff:-0.2, bio:-0.75, cat: 'preservative', hue: '#E8A89C', summary: 'A potent preservative and equally potent allergen. Specifically problematic in leave-on products.' },
  { name: 'Snail mucin',     eff: 0.5,  bio:  0.4,  cat: 'multi',            hue: '#D9E8C9', summary: 'Mixed glycoprotein matrix; modest efficacy on hydration and recovery, biome-supportive in healthy users.' },
  { name: 'Vitamin C (LAA)', eff: 0.82, bio:  0.15, cat: 'antioxidant',      hue: '#E8C896', summary: 'Tier-1 antioxidant when stabilised. Handling matters: low pH formulations can briefly disrupt the acid mantle.' },
  { name: 'Centella',        eff: 0.55, bio:  0.5,  cat: 'botanical',        hue: '#B8D4C2', summary: 'Triterpene-rich extract supporting wound healing pathways. Generally biome-friendly.' },
];

function Grading({ motion = true }) {
  const [hovered, setHovered] = useGState(null);
  const [active, setActive] = useGState(0); // Niacinamide

  return (
    <section id="grading" className="section" style={{ position: 'relative' }}>
      <div className="container">
        <div style={{
          display: 'flex', alignItems: 'baseline', gap: 16,
          marginBottom: 'clamp(28px, 4vh, 48px)',
        }}>
          <span className="eyebrow">§ 03 · Two-axis grading</span>
          <span style={{ flex: 1, height: 1, background: 'var(--rule)' }} />
          <span className="lab">efficacy · microbiome · independent</span>
        </div>

        <div className="grading-head" style={{
          display: 'grid', gridTemplateColumns: '1.1fr 0.9fr',
          gap: 'clamp(24px, 4vw, 56px)', alignItems: 'end',
        }}>
          <h2 className="display-3 text-balance" style={{ margin: 0 }}>
            Not every <span className="serif-italic" style={{ color: 'var(--moss-deep)' }}>"effective"</span>
            {' '}ingredient is a friend to your biome.
          </h2>
          <p className="body-l text-pretty" style={{ margin: 0 }}>
            We grade two things independently: how well it does what it claims,
            and how kindly it behaves toward the microorganisms already on your face.
            <em style={{ fontFamily: 'var(--font-display)', color: 'var(--moss-deep)' }}> Strong efficacy doesn't earn a pass on disruption.</em>
          </p>
        </div>
      </div>

      <div className="container" style={{ marginTop: 'clamp(60px, 8vh, 100px)' }}>
        <div className="grading-grid" style={{
          display: 'grid',
          gridTemplateColumns: '1.4fr 1fr',
          gap: 'clamp(32px, 4vw, 56px)',
          alignItems: 'stretch',
        }}>
          {/* MATRIX */}
          <div className="glass" style={{
            position: 'relative',
            padding: '36px 36px 32px',
            borderRadius: 28,
            overflow: 'hidden',
            minHeight: 540,
          }}>
            <div style={{
              position: 'absolute', inset: 36,
              pointerEvents: 'none',
            }}>
              {/* axes labels */}
              <div className="lab" style={{ position: 'absolute', top: -8, left: 0, color: 'var(--moss-deep)' }}>microbiome →</div>
              <div className="lab" style={{ position: 'absolute', bottom: -8, left: 0, color: 'var(--ink-faint)' }}>← disruptive  ·  supportive →</div>
              <div className="lab" style={{
                position: 'absolute', bottom: 0, right: -8, color: 'var(--moss-deep)',
                transformOrigin: 'right bottom', transform: 'rotate(-90deg) translateY(100%)',
              }}>↑ efficacy</div>
            </div>

            <Matrix
              ingredients={INGREDIENTS}
              hovered={hovered}
              active={active}
              setHovered={setHovered}
              setActive={setActive}
              motion={motion}
            />
          </div>

          {/* DETAIL CARD */}
          <DetailCard ingredient={INGREDIENTS[active]} motion={motion} />
        </div>

        {/* legend tiles */}
        <div style={{
          marginTop: 32,
          display: 'flex', gap: 12, flexWrap: 'wrap',
          justifyContent: 'center',
        }}>
          {[
            { label: 'tier 1 · gold-standard', col: '#7FB3A0' },
            { label: 'tier 2 · good evidence', col: '#D9E8C9' },
            { label: 'tier 3 · limited evidence', col: '#E8C896' },
            { label: 'tier 4 · marketing claim', col: '#F0DCD0' },
            { label: 'supportive · biome-friendly', col: '#B8D4C2' },
            { label: 'disruptive · use with care', col: '#E8A89C' },
          ].map(t => (
            <span key={t.label} className="chip" style={{ background: 'rgba(255,255,255,0.7)' }}>
              <span style={{ width: 9, height: 9, borderRadius: '50%', background: t.col, display: 'inline-block' }} />
              {t.label}
            </span>
          ))}
        </div>
      </div>

      <style>{`
        @media (max-width: 1100px) {
          .grading-head, .grading-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
}

/* ── 2D plot ──────────────────────────────────────────────── */
function Matrix({ ingredients, hovered, active, setHovered, setActive, motion }) {
  // Plot area in % of svg viewbox (480×440)
  const W = 480, H = 440;
  const padL = 50, padR = 24, padT = 24, padB = 38;
  const innerW = W - padL - padR;
  const innerH = H - padT - padB;

  const xOf = (bio) => padL + ((bio + 1) / 2) * innerW;     // bio is -1..1
  const yOf = (eff) => padT + (1 - (eff + 1) / 2) * innerH; // eff -1..1

  return (
    <div style={{ position: 'relative', width: '100%', height: 480 }}>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" style={{ overflow: 'visible' }}>
        <defs>
          <radialGradient id="quadGood" cx="100%" cy="0%" r="120%">
            <stop offset="0%" stopColor="#B8D4C2" stopOpacity="0.55" />
            <stop offset="100%" stopColor="#7FB3A0" stopOpacity="0" />
          </radialGradient>
          <radialGradient id="quadBad" cx="0%" cy="100%" r="120%">
            <stop offset="0%" stopColor="#E8A89C" stopOpacity="0.35" />
            <stop offset="100%" stopColor="#E8A89C" stopOpacity="0" />
          </radialGradient>
        </defs>

        {/* quadrant background tints */}
        <rect x={xOf(0)}    y={padT}     width={innerW/2} height={innerH/2} fill="url(#quadGood)" />
        <rect x={padL}      y={yOf(0)}   width={innerW/2} height={innerH/2} fill="url(#quadBad)" />

        {/* gridlines */}
        {[-0.5, 0, 0.5].map((v) => (
          <line key={'h'+v} x1={padL} x2={padL+innerW} y1={yOf(v)} y2={yOf(v)} stroke="rgba(61,107,87,0.12)" strokeDasharray={v === 0 ? '0' : '2 5'} strokeWidth={v === 0 ? 1 : 0.75} />
        ))}
        {[-0.5, 0, 0.5].map((v) => (
          <line key={'v'+v} y1={padT} y2={padT+innerH} x1={xOf(v)} x2={xOf(v)} stroke="rgba(61,107,87,0.12)" strokeDasharray={v === 0 ? '0' : '2 5'} strokeWidth={v === 0 ? 1 : 0.75} />
        ))}

        {/* quadrant labels */}
        <text x={padL + innerW - 8} y={padT + 16} textAnchor="end" fontSize="9" fontFamily="JetBrains Mono" letterSpacing="0.12em" fill="#3D6B57" opacity="0.6">EFFECTIVE · SUPPORTIVE</text>
        <text x={padL + 8}            y={padT + 16} textAnchor="start" fontSize="9" fontFamily="JetBrains Mono" letterSpacing="0.12em" fill="#3D6B57" opacity="0.5">EFFECTIVE · DISRUPTIVE</text>
        <text x={padL + 8}            y={padT + innerH - 6} textAnchor="start" fontSize="9" fontFamily="JetBrains Mono" letterSpacing="0.12em" fill="#A85A5A" opacity="0.6">INEFFECTIVE · DISRUPTIVE</text>
        <text x={padL + innerW - 8}   y={padT + innerH - 6} textAnchor="end" fontSize="9" fontFamily="JetBrains Mono" letterSpacing="0.12em" fill="#3D6B57" opacity="0.45">INEFFECTIVE · SUPPORTIVE</text>

        {/* ingredient points */}
        {ingredients.map((it, i) => {
          const isActive = i === active;
          const isHover = i === hovered;
          const r = isActive ? 14 : (isHover ? 12 : 9);
          return (
            <g key={it.name}
              transform={`translate(${xOf(it.bio)}, ${yOf(it.eff)})`}
              style={{
                cursor: 'pointer',
                transition: 'transform .5s cubic-bezier(.16,.84,.32,1)',
              }}
              onMouseEnter={() => setHovered(i)}
              onMouseLeave={() => setHovered(null)}
              onClick={() => setActive(i)}
            >
              {/* halo */}
              <circle r={r * 2} fill={it.hue} opacity={isActive ? 0.3 : (isHover ? 0.2 : 0.1)}
                style={{ transition: 'all .35s ease', animation: motion && isActive ? 'breathe 3s ease-in-out infinite' : 'none', transformOrigin: 'center' }} />
              <circle r={r} fill="#FFFFFF" stroke={it.hue} strokeWidth="1.4" />
              <circle r={r * 0.55} fill={it.hue} />
              {/* tiny inner spot — hand-illustrated touch */}
              <circle r={r * 0.18} fill="#FFFFFF" opacity="0.7" cx={-r*0.15} cy={-r*0.15} />

              {/* label */}
              <text y={r + 14} textAnchor="middle" fontSize={isActive ? 12 : 10}
                fontFamily="var(--font-display)"
                fill={isActive ? '#1B2823' : '#5b6663'}
                fontStyle={isActive ? 'italic' : 'normal'}
                style={{ transition: 'all .35s ease' }}>
                {it.name}
              </text>
            </g>
          );
        })}
      </svg>
    </div>
  );
}

/* ── Detail card ──────────────────────────────────────────── */
function DetailCard({ ingredient, motion }) {
  const { name, eff, bio, cat, hue, summary } = ingredient;
  const effLabel = eff > 0.8 ? 'Tier 1' : eff > 0.5 ? 'Tier 2' : eff > 0.2 ? 'Tier 3' : 'Tier 4';
  const bioLabel = bio > 0.4 ? 'Supportive' : bio > -0.1 ? 'Neutral' : bio > -0.5 ? 'Mildly disruptive' : 'Disruptive';
  const bioCol  = bio > 0 ? '#3D6B57' : bio > -0.3 ? '#7a5e2a' : '#A85A5A';

  return (
    <div className="glass" style={{
      position: 'relative',
      padding: 32,
      borderRadius: 28,
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
      animation: motion ? 'fade-up 0.5s cubic-bezier(.16,.84,.32,1)' : 'none',
    }} key={name}>
      <div className="lab" style={{ color: 'var(--moss-deep)' }}>library detail · ingredient</div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 18, marginTop: 14 }}>
        {/* hand-illustrated mark */}
        <div style={{ position: 'relative', width: 84, height: 84, flexShrink: 0 }}>
          <svg viewBox="0 0 100 100" width="84" height="84">
            <defs>
              <radialGradient id={`detail-${name.replace(/[^a-z]/gi, '')}`} cx="35%" cy="30%" r="80%">
                <stop offset="0%" stopColor="#FFFFFF" stopOpacity="1" />
                <stop offset="60%" stopColor={hue} stopOpacity="0.55" />
                <stop offset="100%" stopColor={hue} stopOpacity="0.9" />
              </radialGradient>
            </defs>
            <circle cx="50" cy="50" r="46" fill={`url(#detail-${name.replace(/[^a-z]/gi, '')})`} />
            {/* tiny botanical / molecular doodle */}
            <g stroke="#1B2823" strokeWidth="0.9" fill="none" opacity="0.65" strokeLinecap="round">
              <circle cx="38" cy="44" r="3" />
              <circle cx="52" cy="56" r="3" />
              <circle cx="62" cy="40" r="3" />
              <path d="M 41 44 L 49 54" />
              <path d="M 55 56 L 59 42" />
              <path d="M 52 56 L 62 60" />
              <circle cx="64" cy="62" r="2.5" />
            </g>
            {/* highlight */}
            <ellipse cx="38" cy="32" rx="12" ry="6" fill="rgba(255,255,255,0.55)" transform="rotate(-30 38 32)" />
          </svg>
        </div>

        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="lab" style={{ color: 'var(--ink-muted)' }}>{cat}</div>
          <h3 style={{
            fontFamily: 'var(--font-display)',
            fontWeight: 400,
            fontSize: 36, lineHeight: 1.02,
            letterSpacing: '-0.02em',
            margin: '2px 0 0',
            color: 'var(--ink)',
          }}>{name}</h3>
        </div>
      </div>

      {/* grades */}
      <div style={{
        marginTop: 24,
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14,
      }}>
        <div style={{
          padding: '14px 16px',
          borderRadius: 16,
          background: 'rgba(255,255,255,0.5)',
          border: '0.5px solid rgba(127,179,160,0.25)',
        }}>
          <div className="lab" style={{ color: 'var(--moss-deep)' }}>Efficacy</div>
          <div style={{
            fontFamily: 'var(--font-display)', fontStyle: 'italic',
            fontSize: 28, color: 'var(--ink)', lineHeight: 1.1, marginTop: 2,
          }}>{effLabel}</div>
          <Bar value={(eff + 1) / 2} col="#5A9985" />
        </div>
        <div style={{
          padding: '14px 16px',
          borderRadius: 16,
          background: 'rgba(255,255,255,0.5)',
          border: '0.5px solid rgba(127,179,160,0.25)',
        }}>
          <div className="lab" style={{ color: 'var(--moss-deep)' }}>Microbiome</div>
          <div style={{
            fontFamily: 'var(--font-display)', fontStyle: 'italic',
            fontSize: 28, color: bioCol, lineHeight: 1.1, marginTop: 2,
          }}>{bioLabel}</div>
          <Bar value={(bio + 1) / 2} col={bioCol} />
        </div>
      </div>

      <p className="body-m text-pretty" style={{ marginTop: 22 }}>{summary}</p>

      <div style={{
        marginTop: 'auto', paddingTop: 20,
        borderTop: '1px solid var(--rule)',
        display: 'flex', justifyContent: 'space-between',
        fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.12em',
        textTransform: 'uppercase', color: 'var(--ink-muted)',
      }}>
        <span>Educational · not medical advice</span>
        <span>Citations in-app</span>
      </div>

      <style>{`
        @keyframes fade-up { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
      `}</style>
    </div>
  );
}

function Bar({ value, col }) {
  return (
    <div style={{
      marginTop: 10, height: 4, borderRadius: 2,
      background: 'rgba(127,179,160,0.18)', overflow: 'hidden',
    }}>
      <div style={{
        width: `${Math.max(6, value * 100)}%`,
        height: '100%', background: col, borderRadius: 2,
        transition: 'width .6s cubic-bezier(.16,.84,.32,1)',
      }} />
    </div>
  );
}

Object.assign(window, { Grading });
