/* global React, window */
const { useEffect, useRef, useState } = React;

/* ---------- Reveal-on-scroll wrapper ---------- */
function Reveal({ children, delay = 0, as: As = 'div', ...rest }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      setShown(true); return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) { setShown(true); io.disconnect(); }
        });
      },
      { threshold: 0.15, rootMargin: '0px 0px -8% 0px' }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return (
    <As
      ref={ref}
      {...rest}
      className={`reveal ${shown ? 'in' : ''} ${rest.className || ''}`}
      style={{ transitionDelay: `${delay}ms`, ...(rest.style || {}) }}
    >
      {children}
    </As>
  );
}

/* ---------- Chip ---------- */
function Chip({ children, tone }) {
  return <span className={`chip ${tone || ''}`}>{children}</span>;
}

/* ---------- Section idx label ---------- */
function SectionIdx({ num, label }) {
  return (
    <div className="section-idx">
      <span className="num">{num}</span>
      <span>{label}</span>
    </div>
  );
}

/* ---------- Eyebrow ---------- */
function Eyebrow({ children, dark }) {
  return <div className={`eyebrow ${dark ? 'dark' : ''}`}>{children}</div>;
}

/* ---------- Slab visuals ---------- */
function SlabViz({ kind }) {
  if (kind === 'map') {
    return (
      <div className="slab-viz viz-map">
        <span className="node" style={{ left: 14, top: 16 }}>shopify</span>
        <span className="node" style={{ left: 100, top: 14 }}>hubspot</span>
        <span className="node" style={{ left: 178, top: 16 }}>github</span>
        <span className="node flag" style={{ right: 16, top: 14 }}>bottleneck</span>
        <span className="node" style={{ left: 24, bottom: 14 }}>slack</span>
        <span className="node" style={{ left: 110, bottom: 14 }}>notion</span>
        <span className="node" style={{ left: 200, bottom: 14 }}>vercel</span>
        <span className="wire" style={{ left: 24, top: 30, width: 240 }}></span>
        <span className="wire v" style={{ left: 124, top: 30 }}></span>
        <span className="wire" style={{ left: 24, bottom: 26, width: 240 }}></span>
      </div>
    );
  }
  if (kind === 'loop') {
    return (
      <div className="slab-viz viz-loop">
        <div className="step"><span className="blip"></span>Ask</div>
        <span className="arr"></span>
        <div className="step active"><span className="blip"></span>Review</div>
        <span className="arr"></span>
        <div className="step"><span className="blip"></span>Verify</div>
        <span className="arr"></span>
        <div className="step"><span className="blip"></span>Handoff</div>
      </div>
    );
  }
  if (kind === 'cli') {
    return (
      <div className="slab-viz viz-cli">
        <div><span className="prompt">$</span> claude-code inspect <span className="file">apps/checkout</span></div>
        <div><span className="prompt">$</span> gh pr view <span className="file">#1421</span> <span className="ok">→ ready</span></div>
        <div><span className="prompt">$</span> vercel deploy --scope=staging</div>
      </div>
    );
  }
  if (kind === 'stack') {
    return (
      <div className="slab-viz viz-stack">
        <span className="doc" style={{ left: 18, top: 12, transform: 'rotate(-3deg)' }}></span>
        <span className="doc" style={{ left: 34, top: 18, transform: 'rotate(1deg)' }}></span>
        <span className="doc" style={{ left: 50, top: 14, transform: 'rotate(-1deg)' }}></span>
        <span className="doc" style={{ left: 126, top: 16, transform: 'rotate(2deg)' }}></span>
        <span className="doc" style={{ left: 142, top: 12, transform: 'rotate(-2deg)' }}></span>
        <span className="core"></span>
      </div>
    );
  }
  if (kind === 'rail') {
    return (
      <div className="slab-viz viz-rail">
        <span className="track"></span>
        <span className="tick" style={{ left: 28 }}></span>
        <span className="tick" style={{ left: 80 }}></span>
        <span className="tick" style={{ left: 132 }}></span>
        <span className="tick" style={{ left: 184 }}></span>
        <span className="tick" style={{ left: 236 }}></span>
        <span className="gate" style={{ left: 110 }}>approve</span>
        <span className="scheduled" style={{ left: 20 }}>scheduled · 09:00</span>
      </div>
    );
  }
  if (kind === 'ship') {
    return (
      <div className="slab-viz viz-ship">
        <span className="arti">checkout-redirect.patch</span>
        <span className="arti">ga4-events.audit</span>
        <span className="arti">slack-approvals.flow</span>
        <span className="arti muted">retainer-q2.runbook</span>
        <span className="arti">support-kb.v1</span>
      </div>
    );
  }
  return null;
}

/* ---------- Slab card ---------- */
function Slab({ data, open, onToggle }) {
  return (
    <div
      className="slab"
      data-open={open}
      onClick={onToggle}
      onMouseEnter={() => {}}
      role="button"
      tabIndex={0}
      onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onToggle(); } }}
    >
      <div className="slab-head">
        <span className="slab-num">SLAB {data.n}</span>
        <span className="slab-pip"></span>
      </div>
      <h3>{data.label}</h3>
      <p className="desc">{data.desc}</p>
      <SlabViz kind={data.viz} />
      <div className="chips">
        <div className="chip-row">
          {data.chips.slice(0, open ? data.chips.length : 6).map((c) => (
            <Chip key={c}>{c}</Chip>
          ))}
          {!open && data.chips.length > 6 && (
            <span className="chip" style={{ background: 'transparent', borderStyle: 'dashed', color: 'rgba(247,241,230,0.5)' }}>
              +{data.chips.length - 6} more
            </span>
          )}
        </div>
      </div>
    </div>
  );
}

/* ---------- Proof rail ---------- */
function ProofRail() {
  const [step, setStep] = useState(2);
  useEffect(() => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const id = setInterval(() => setStep((s) => (s + 1) % window.PROOF.length), 2200);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="proof-rail">
      <span className="label">Trust mechanism</span>
      <div className="proof-steps">
        {window.PROOF.map((p, i) => {
          const cls = ['proof-step'];
          if (i === step) cls.push('active');
          if (p === 'Approve') cls.push('approval');
          if (p === 'Verify') cls.push('verified');
          return (
            <React.Fragment key={p}>
              <span className={cls.join(' ')}>
                <span className="pip"></span>{p}
              </span>
              {i < window.PROOF.length - 1 && <span className="proof-arrow">→</span>}
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
}

/* ---------- Brand mark (inline SVG, reusable) ---------- */
function BrandMark({ size = 28 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 512 512" aria-label="Bastion AI mark">
      <defs>
        <linearGradient id="bm-g" x1="96" y1="72" x2="416" y2="440" gradientUnits="userSpaceOnUse">
          <stop offset="0" stopColor="#F7F1E6" />
          <stop offset="0.45" stopColor="#B8C0C7" />
          <stop offset="1" stopColor="#0C1117" />
        </linearGradient>
      </defs>
      <path d="M256 35 430 126v260L256 477 82 386V126L256 35Z" fill="#0C1117" />
      <path d="M256 61 407 140v232L256 451 105 372V140L256 61Z" fill="url(#bm-g)" opacity=".95" />
      <path d="M151 126h116c57 0 94 30 94 77 0 29-14 51-42 64 35 12 54 39 54 75 0 54-42 86-107 86H151V126Zm92 121c35 0 55-14 55-40 0-25-20-39-55-39h-38v79h38Zm11 139c39 0 61-16 61-45 0-28-22-44-61-44h-49v89h49Z" fill="#0C1117" />
      <path d="M186 149h66c45 0 73 23 73 59 0 29-18 49-48 57 40 6 66 31 66 70 0 43-33 70-87 70h-70V149Zm58 111c48 0 75-20 75-55 0-33-27-53-75-53h-55v108h55Zm10 142c54 0 86-25 86-67 0-41-32-65-86-65h-65v132h65Z" fill="none" stroke="#17D9E6" strokeWidth="8" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx="382" cy="143" r="10" fill="#32D583" />
      <circle cx="394" cy="369" r="10" fill="#32D583" />
      <circle cx="335" cy="311" r="9" fill="#F4B84A" />
    </svg>
  );
}

Object.assign(window, { Reveal, Chip, SectionIdx, Eyebrow, SlabViz, Slab, ProofRail, BrandMark });
