/* global React */
// Hero — animated "noise → signal" diagram

const { useEffect, useRef, useState } = React;

function BrandMark({ size = 22, color }) {
  // MECE mark — 4 quadrants (mutually exclusive, collectively exhaustive),
  // one filled = the signal you keep.
  return (
    <svg width={size} height={size} viewBox="0 0 22 22" fill="none"
         style={{ display: 'block' }}>
      <rect x="1" y="1" width="9" height="9" rx="2" fill={color || 'var(--signal)'} />
      <rect x="12" y="1" width="9" height="9" rx="2" stroke={color || 'var(--ink)'} strokeWidth="1.4" />
      <rect x="1" y="12" width="9" height="9" rx="2" stroke={color || 'var(--ink)'} strokeWidth="1.4" />
      <rect x="12" y="12" width="9" height="9" rx="2" stroke={color || 'var(--ink)'} strokeWidth="1.4" />
    </svg>
  );
}

// Animated noise→signal scatter. Dots start scattered, settle to a curve.
function SignalScatter() {
  const [phase, setPhase] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setPhase((p) => (p + 1) % 2), 3200);
    return () => clearInterval(id);
  }, []);

  // 60 deterministic dots
  const dots = React.useMemo(() => {
    const arr = [];
    for (let i = 0; i < 64; i++) {
      // pseudo-random seeded
      const s1 = Math.sin(i * 12.9898) * 43758.5453;
      const s2 = Math.sin(i * 78.233) * 43758.5453;
      const rx = (s1 - Math.floor(s1));
      const ry = (s2 - Math.floor(s2));
      arr.push({ id: i, rx, ry });
    }
    return arr;
  }, []);

  // Signal items (the 6 chosen)
  const signalIdx = [4, 13, 22, 31, 44, 55];

  return (
    <div className="scatter">
      <div className="grid-bg"></div>

      {/* Axis labels */}
      <div style={{
        position: 'absolute', top: 16, left: 18,
        fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.08em',
        textTransform: 'uppercase', color: 'var(--ink-3)'
      }}>relevance →</div>
      <div style={{
        position: 'absolute', bottom: 16, right: 18,
        fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.08em',
        textTransform: 'uppercase', color: 'var(--ink-3)'
      }}>↓ noise</div>

      {/* Source pill (top-left) */}
      <SourcePill x="4%" y="6%" label="digg:all" delay={0} />
      <SourcePill x="4%" y="22%" label="url:allowlist" delay={120} />
      <SourcePill x="4%" y="38%" label="gh:trending" delay={240} />

      {/* Output card (bottom-right) */}
      <OutputCard />

      {/* Dots */}
      {dots.map((d) => {
        const isSignal = signalIdx.includes(d.id);
        // Phase 0: scattered. Phase 1: signal dots fly to a column on the right.
        const x = phase === 0
          ? 20 + d.rx * 60
          : isSignal ? 72 : 20 + d.rx * 60 * (1 - 0.3);
        const y = phase === 0
          ? 14 + d.ry * 72
          : isSignal ? 18 + (signalIdx.indexOf(d.id) * 11) : 14 + d.ry * 72;
        const opacity = phase === 1 && !isSignal ? 0.2 : (isSignal ? 1 : 0.55);
        return (
          <div
            key={d.id}
            className={`dot ${isSignal ? 'signal' : ''} ${isSignal && phase === 1 ? 'large' : ''}`}
            style={{
              left: `${x}%`, top: `${y}%`, opacity,
              transitionDelay: `${(d.id % 12) * 30}ms`,
            }}
          />
        );
      })}

      {/* Beam between source and output */}
      <svg style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }} viewBox="0 0 400 400" preserveAspectRatio="none">
        <defs>
          <linearGradient id="beam" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="var(--signal)" stopOpacity="0" />
            <stop offset="40%" stopColor="var(--signal)" stopOpacity="0.5" />
            <stop offset="100%" stopColor="var(--signal)" stopOpacity="0" />
          </linearGradient>
        </defs>
        {phase === 1 && (
          <path
            d="M 70 60 Q 200 200, 290 230"
            stroke="url(#beam)" strokeWidth="1.5" fill="none"
            strokeDasharray="3 5"
            style={{ animation: 'dash 1.5s linear infinite' }}
          />
        )}
      </svg>

      <style>{`
        @keyframes dash {
          to { stroke-dashoffset: -16; }
        }
      `}</style>
    </div>
  );
}

function SourcePill({ x, y, label, delay }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      background: 'var(--paper)',
      border: '1px solid var(--line)',
      borderRadius: 999,
      padding: '6px 12px 6px 8px',
      fontFamily: 'var(--mono)', fontSize: 11,
      color: 'var(--ink-2)',
      display: 'flex', alignItems: 'center', gap: 6,
      animation: `float-up .6s ${delay}ms backwards ease-out`,
      boxShadow: '0 2px 8px -4px rgba(17,16,14,0.15)',
    }}>
      <span style={{
        width: 8, height: 8, borderRadius: '50%',
        background: 'var(--signal-deep)',
        boxShadow: '0 0 0 3px color-mix(in oklab, var(--signal) 40%, transparent)',
      }}></span>
      {label}
    </div>
  );
}

function OutputCard() {
  return (
    <div style={{
      position: 'absolute', right: '4%', bottom: '6%',
      background: 'var(--ink)', color: 'var(--paper)',
      borderRadius: 12, padding: 14, width: 200,
      boxShadow: '0 20px 40px -16px rgba(17,16,14,0.45)',
      fontFamily: 'var(--mono)', fontSize: 11,
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 10,
      }}>
        <span style={{ color: 'var(--signal)', letterSpacing: '0.05em' }}>your.feed.rss</span>
        <span style={{
          width: 6, height: 6, borderRadius: '50%',
          background: 'var(--signal)',
          boxShadow: '0 0 0 4px color-mix(in oklab, var(--signal) 30%, transparent)',
          animation: 'pulse 1.6s infinite',
        }}></span>
      </div>
      {['Claude 4.7 agent eval', 'tokio 1.40 perf wins', 'replit ships shells'].map((t, i) => (
        <div key={i} style={{
          padding: '6px 0',
          borderTop: i ? '1px dashed rgba(232,227,214,0.15)' : 'none',
          fontSize: 11, opacity: 0.9,
        }}>
          <span style={{ color: 'var(--muted)' }}>0.{92 - i*3}</span>  {t}
        </div>
      ))}
      <style>{`
        @keyframes pulse {
          0%,100% { box-shadow: 0 0 0 4px color-mix(in oklab, var(--signal) 30%, transparent); }
          50%     { box-shadow: 0 0 0 8px color-mix(in oklab, var(--signal) 10%, transparent); }
        }
      `}</style>
    </div>
  );
}

function Hero() {
  return (
    <section className="hero">
      <div className="container">
        <div className="hero-grid">
          <div className="hero-left">
            <span className="eyebrow">Personalized RSS · Signed by default</span>
            <h1 className="h-display">
              Your feed,<br/>
              with <em>receipts</em>.
            </h1>
            <p className="lede">
              Standard RSS can only tell you what published. MECE crawls the niches
              you actually read, ranks every item against your rubric, and ships a private RSS
              or JSON feed with <span style={{color:'var(--trust)', fontStyle:'italic', fontFamily:'var(--serif)'}}>signed receipts</span> so
              you can audit exactly what the model did on your dime.
            </p>
            <div className="hero-cta-row">
              <button className="btn btn-signal">
                Start free · 1 niche
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                  <path d="M3 7h8m0 0L7.5 3.5M11 7l-3.5 3.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
                </svg>
              </button>
              <a href="App.html" className="btn btn-ghost">
                Open the reader →
              </a>
            </div>

            <div className="hero-stat-row">
              <div className="hero-stat">
                <div className="hero-stat-num">12<em>·</em>4k</div>
                <div className="hero-stat-label">items ranked / hr</div>
              </div>
              <div className="hero-stat">
                <div className="hero-stat-num">$<em>0</em>.00</div>
                <div className="hero-stat-label">surprise overages, ever</div>
              </div>
              <div className="hero-stat">
                <div className="hero-stat-num">100<em>%</em></div>
                <div className="hero-stat-label">jobs signed Ed25519</div>
              </div>
            </div>
          </div>

          <div className="hero-right">
            <SignalScatter />
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Hero, BrandMark });
