// brain-svg.jsx — Beautiful 2D SVG brain with three visual variants.
// All variants share the same anatomically-inspired path data.

const { motion: bm } = window.framerMotion || {};

/* ─────────────────────────────────────────────────────────────────
   ANATOMICAL PATH DATA
   The brain is drawn in a 400×320 viewBox, facing left (lateral view).
   These paths are hand-tuned to read as a real brain silhouette:
   - Outer cerebrum: rounded with frontal bulge (left), occipital
     bulge (right), temporal lobe dipping bottom-front.
   - Central sulcus + lateral fissure: the iconic curving folds.
   - Cerebellum: smaller bumpy mass tucked under back-right.
   - Brainstem: short stub descending from cerebellum area.
   ───────────────────────────────────────────────────────────────── */

const BRAIN_VIEW = "0 0 400 280";

// Lateral-view brain (facing left). Anatomically tuned silhouette:
// - Frontal lobe bulges forward at top-left
// - Top of cerebrum is high and rounded (parietal crown)
// - Occipital pole pokes back-right
// - Temporal lobe dips down-forward at bottom
// - Cerebellum tucks UNDER the occipital pole at bottom-right
// Lateral-view brain — distinctive kidney-bean / boxing-glove silhouette.
// Built so the silhouette reads "brain" at a glance:
// - Frontal pole pushed forward at top-left
// - Tall rounded crown
// - Occipital pole projects back-right
// - Temporal lobe HOOKS forward-down at bottom-front (the key brain tell)
// - Underside has a CONCAVE bite where the brainstem/midbrain would sit
const CEREBRUM_OUTLINE =
  "M 95 95 " +                               // top of frontal pole
  "C 80 80, 75 60, 95 50 " +                 // up & forward
  "C 115 38, 145 30, 175 30 " +              // top of frontal lobe
  "C 215 28, 260 38, 295 58 " +              // top-front rounding
  "C 325 75, 348 105, 352 140 " +            // crown -> top of parietal
  "C 354 168, 348 192, 332 208 " +           // parietal -> occipital descent
  "C 320 220, 305 226, 290 222 " +           // occipital pole bulge
  "C 282 232, 268 238, 252 234 " +           // tuck under occipital
  "C 245 230, 242 222, 245 212 " +           // CONCAVE underside (the brain "bite")
  "C 235 218, 222 220, 208 218 " +           // bottom of temporal area
  "C 195 215, 185 208, 178 198 " +           // start of temporal hook
  "C 170 188, 160 180, 145 178 " +           // temporal hook curving forward
  "C 125 175, 108 168, 98 155 " +            // descent of frontal/temporal
  "C 88 145, 85 130, 90 115 " +              // back up front
  "C 92 105, 93 100, 95 95 Z";               // close at frontal pole

// Lateral (Sylvian) fissure — the most iconic interior groove,
// curves diagonally up-back, separating temporal from parietal.
const SULCUS_LATERAL =
  "M 110 150 C 145 142, 190 138, 235 140 C 270 142, 295 148, 318 155";
// Central sulcus — diagonal up the side, separating frontal from parietal
const SULCUS_CENTRAL =
  "M 175 50 C 180 75, 188 100, 195 130 C 200 145, 205 155, 215 160";
// Pre-central sulcus
const SULCUS_PRECENTRAL =
  "M 145 50 C 150 75, 158 100, 165 130 C 168 142, 172 150, 178 156";
// Post-central sulcus
const SULCUS_POSTCENTRAL =
  "M 215 45 C 220 70, 225 100, 230 125 C 233 138, 238 148, 245 152";
// Parieto-occipital sulcus
const SULCUS_PARIETOOCC =
  "M 280 60 C 290 90, 300 120, 305 145";
// Frontal lobe sulci
const SULCUS_FRONT_1 =
  "M 80 110 C 105 100, 130 95, 155 95";
const SULCUS_FRONT_2 =
  "M 85 130 C 110 120, 135 117, 162 118";
// Temporal lobe gyri
const SULCUS_TEMPORAL_1 =
  "M 115 180 C 145 175, 180 175, 215 180";
const SULCUS_TEMPORAL_2 =
  "M 130 200 C 160 195, 195 197, 220 202";
// Occipital arcs
const SULCUS_OCC_1 =
  "M 295 95 C 320 110, 335 130, 342 155";
const SULCUS_OCC_2 =
  "M 290 195 C 305 185, 318 170, 325 155";

// Cerebellum: integrated under occipital pole, slightly nestled into the bite.
const CEREBELLUM_OUTLINE =
  "M 252 234 " +
  "C 270 240, 295 246, 312 240 " +
  "C 322 235, 325 222, 318 215 " +
  "C 308 210, 295 215, 285 220 " +
  "C 275 224, 262 226, 252 224 Z";

// Cerebellum folia (the characteristic parallel ridges).
const CEREBELLUM_FOLIA = [
  "M 260 224 C 278 224, 298 228, 314 228",
  "M 262 232 C 280 234, 300 236, 314 234",
  "M 268 240 C 282 242, 298 243, 308 240",
];

// Brainstem — small descending stub from underneath.
const BRAINSTEM_OUTLINE =
  "M 248 232 C 246 244, 248 254, 254 258 " +
  "C 262 260, 268 256, 268 248 " +
  "C 268 240, 262 232, 258 230 Z";

/* ─────────────────────────────────────────────────────────────────
   NODE POSITIONS for the constellation variant.
   Hand-placed inside the brain silhouette, clustered by region.
   ───────────────────────────────────────────────────────────────── */

const NODES = [
  // Frontal lobe (cluster 0)
  { x: 85, y: 105, r: 0 }, { x: 100, y: 125, r: 0 }, { x: 115, y: 95, r: 0 },
  { x: 125, y: 140, r: 0 }, { x: 140, y: 105, r: 0 }, { x: 105, y: 155, r: 0 },
  { x: 130, y: 75, r: 0 }, { x: 150, y: 135, r: 0 },
  // Parietal (cluster 1)
  { x: 175, y: 80, r: 1 }, { x: 195, y: 105, r: 1 }, { x: 210, y: 70, r: 1 },
  { x: 230, y: 88, r: 1 }, { x: 215, y: 125, r: 1 }, { x: 245, y: 108, r: 1 },
  // Occipital (cluster 2)
  { x: 280, y: 100, r: 2 }, { x: 300, y: 130, r: 2 }, { x: 320, y: 155, r: 2 },
  { x: 300, y: 175, r: 2 }, { x: 275, y: 165, r: 2 }, { x: 315, y: 185, r: 2 },
  // Temporal (cluster 3)
  { x: 125, y: 185, r: 3 }, { x: 150, y: 200, r: 3 }, { x: 175, y: 192, r: 3 },
  { x: 200, y: 205, r: 3 }, { x: 100, y: 175, r: 3 }, { x: 160, y: 175, r: 3 },
  // Cerebellum (cluster 4)
  { x: 260, y: 230, r: 4 }, { x: 280, y: 240, r: 4 }, { x: 300, y: 232, r: 4 },
  { x: 285, y: 248, r: 4 }, { x: 265, y: 245, r: 4 },
];

// Edges: hand-curated to create flowing curves through the brain.
const EDGES = [
  [0,1],[1,2],[2,3],[1,4],[4,5],[3,5],[6,2],[6,4],[7,4],[7,8],
  [8,9],[9,10],[10,11],[11,12],[12,13],[9,13],[13,14],[14,15],
  [15,16],[16,17],[17,18],[18,15],[14,16],[19,17],[19,18],
  [5,20],[20,21],[21,22],[22,23],[23,18],[3,20],[7,22],[11,21],
  [24,20],[24,25],[25,21],[26,27],[27,28],[28,29],[29,30],[30,26],
  [23,27],[18,28],
];

/* ─────────────────────────────────────────────────────────────────
   VARIANT A — Anatomical line art with traveling pulses
   ───────────────────────────────────────────────────────────────── */

function BrainAnatomical() {
  // Lines that pulses travel along. Each gets a unique animation phase.
  const pulseLines = [
    { d: SULCUS_LATERAL, dur: 3.2, delay: 0.0 },
    { d: SULCUS_CENTRAL, dur: 4.1, delay: 0.6 },
    { d: SULCUS_PRECENTRAL, dur: 3.6, delay: 1.2 },
    { d: SULCUS_PARIETOOCC, dur: 3.8, delay: 1.8 },
    { d: SULCUS_FRONT_1, dur: 4.4, delay: 0.4 },
    { d: SULCUS_FRONT_2, dur: 3.9, delay: 2.1 },
    { d: SULCUS_TEMPORAL_1, dur: 4.0, delay: 0.9 },
    { d: SULCUS_TEMPORAL_2, dur: 3.5, delay: 1.6 },
    { d: SULCUS_OCC_1, dur: 4.3, delay: 0.2 },
    { d: SULCUS_OCC_2, dur: 3.7, delay: 2.5 },
  ];

  return (
    <svg viewBox={BRAIN_VIEW} className="bsvg bsvg--anatomical" aria-hidden="true">
      <defs>
        <radialGradient id="bsvgInnerGlow" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.18"/>
          <stop offset="60%" stopColor="var(--accent)" stopOpacity="0.04"/>
          <stop offset="100%" stopColor="var(--accent)" stopOpacity="0"/>
        </radialGradient>
        <linearGradient id="bsvgPulseGrad" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" stopColor="var(--accent)" stopOpacity="0"/>
          <stop offset="50%" stopColor="#ffffff" stopOpacity="1"/>
          <stop offset="100%" stopColor="var(--accent)" stopOpacity="0"/>
        </linearGradient>
        <filter id="bsvgGlow" x="-30%" y="-30%" width="160%" height="160%">
          <feGaussianBlur stdDeviation="2.5" result="b"/>
          <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
        </filter>
        <filter id="bsvgSoftGlow" x="-50%" y="-50%" width="200%" height="200%">
          <feGaussianBlur stdDeviation="6"/>
        </filter>
      </defs>

      {/* Soft inner volumetric glow */}
      <path d={CEREBRUM_OUTLINE} fill="url(#bsvgInnerGlow)"/>
      <path d={CEREBELLUM_OUTLINE} fill="url(#bsvgInnerGlow)"/>

      {/* Diffuse halo behind */}
      <ellipse cx="200" cy="160" rx="180" ry="130"
        fill="var(--accent)" opacity="0.06" filter="url(#bsvgSoftGlow)"/>

      {/* Outer outlines */}
      <path d={CEREBRUM_OUTLINE} fill="none"
        stroke="var(--accent)" strokeWidth="1.4" strokeOpacity="0.85"
        filter="url(#bsvgGlow)"/>
      <path d={CEREBELLUM_OUTLINE} fill="none"
        stroke="var(--accent)" strokeWidth="1.2" strokeOpacity="0.75"
        filter="url(#bsvgGlow)"/>
      <path d={BRAINSTEM_OUTLINE} fill="none"
        stroke="var(--accent)" strokeWidth="1.0" strokeOpacity="0.6"/>

      {/* Internal sulci — softer */}
      <g stroke="var(--accent)" fill="none" strokeOpacity="0.45" strokeWidth="0.9">
        <path d={SULCUS_LATERAL}/>
        <path d={SULCUS_CENTRAL}/>
        <path d={SULCUS_PRECENTRAL}/>
        <path d={SULCUS_PARIETOOCC}/>
        <path d={SULCUS_FRONT_1}/>
        <path d={SULCUS_FRONT_2}/>
        <path d={SULCUS_TEMPORAL_1}/>
        <path d={SULCUS_TEMPORAL_2}/>
        <path d={SULCUS_OCC_1}/>
        <path d={SULCUS_OCC_2}/>
      </g>

      {/* Cerebellum folia */}
      <g stroke="var(--accent)" fill="none" strokeOpacity="0.55" strokeWidth="0.7">
        {CEREBELLUM_FOLIA.map((d, i) => <path key={i} d={d}/>)}
      </g>

      {/* Traveling pulses — bright dashes that race along the sulci */}
      <g style={{ mixBlendMode: "screen" }}>
        {pulseLines.map((p, i) => (
          <path key={i} d={p.d} fill="none"
            stroke="#ffffff" strokeWidth="2.2"
            strokeDasharray="14 220"
            strokeLinecap="round"
            filter="url(#bsvgGlow)">
            <animate attributeName="stroke-dashoffset"
              from="234" to="0"
              dur={`${p.dur}s`} begin={`${-p.delay}s`}
              repeatCount="indefinite"/>
          </path>
        ))}
        {/* Counter-direction pulses on a few lines */}
        {[pulseLines[0], pulseLines[3], pulseLines[6]].map((p, i) => (
          <path key={`r${i}`} d={p.d} fill="none"
            stroke="var(--accent-2)" strokeWidth="1.6"
            strokeDasharray="8 240" strokeLinecap="round"
            filter="url(#bsvgGlow)">
            <animate attributeName="stroke-dashoffset"
              from="0" to="248"
              dur={`${p.dur * 1.3}s`} begin={`${-p.delay * 0.5}s`}
              repeatCount="indefinite"/>
          </path>
        ))}
      </g>

      {/* Firing spots — small bright dots that pulse on at random spots */}
      <g style={{ mixBlendMode: "screen" }}>
        {[
          [120, 140], [200, 100], [280, 130], [305, 180], [165, 195],
          [240, 110], [115, 175], [275, 270], [85, 120], [250, 220],
        ].map(([x, y], i) => (
          <circle key={i} cx={x} cy={y} r="2" fill="#fff" filter="url(#bsvgGlow)">
            <animate attributeName="r"
              values="0;3;0" dur={`${1.8 + (i % 3) * 0.4}s`}
              begin={`${-i * 0.35}s`} repeatCount="indefinite"/>
            <animate attributeName="opacity"
              values="0;1;0" dur={`${1.8 + (i % 3) * 0.4}s`}
              begin={`${-i * 0.35}s`} repeatCount="indefinite"/>
          </circle>
        ))}
      </g>
    </svg>
  );
}

/* ─────────────────────────────────────────────────────────────────
   VARIANT B — Neural constellation
   Brain emerges from glowing nodes + edges only.
   ───────────────────────────────────────────────────────────────── */

function BrainConstellation() {
  // Compute path strings for each edge as a curved line.
  const edgePaths = React.useMemo(() => {
    return EDGES.map(([a, b]) => {
      const A = NODES[a], B = NODES[b];
      const mx = (A.x + B.x) / 2, my = (A.y + B.y) / 2;
      const dx = B.x - A.x, dy = B.y - A.y;
      const len = Math.hypot(dx, dy);
      // Perpendicular offset for curve
      const off = len * 0.12;
      const cx = mx + (-dy / len) * off;
      const cy = my + (dx / len) * off;
      return `M ${A.x} ${A.y} Q ${cx} ${cy} ${B.x} ${B.y}`;
    });
  }, []);

  return (
    <svg viewBox={BRAIN_VIEW} className="bsvg bsvg--constellation" aria-hidden="true">
      <defs>
        <radialGradient id="bsvgcInnerGlow" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.16"/>
          <stop offset="100%" stopColor="var(--accent)" stopOpacity="0"/>
        </radialGradient>
        <radialGradient id="bsvgcNode" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="#ffffff" stopOpacity="1"/>
          <stop offset="40%" stopColor="var(--accent)" stopOpacity="0.9"/>
          <stop offset="100%" stopColor="var(--accent)" stopOpacity="0"/>
        </radialGradient>
        <filter id="bsvgcGlow" x="-50%" y="-50%" width="200%" height="200%">
          <feGaussianBlur stdDeviation="2"/>
          <feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge>
        </filter>
        <filter id="bsvgcSoftGlow" x="-50%" y="-50%" width="200%" height="200%">
          <feGaussianBlur stdDeviation="8"/>
        </filter>
      </defs>

      {/* Diffuse silhouette glow — hints at the brain shape */}
      <path d={CEREBRUM_OUTLINE} fill="url(#bsvgcInnerGlow)" filter="url(#bsvgcSoftGlow)"/>
      <path d={CEREBELLUM_OUTLINE} fill="url(#bsvgcInnerGlow)" filter="url(#bsvgcSoftGlow)"/>

      {/* Edges */}
      <g style={{ mixBlendMode: "screen" }}>
        {edgePaths.map((d, i) => (
          <g key={i}>
            <path d={d} fill="none" stroke="var(--accent)"
              strokeWidth="0.6" strokeOpacity="0.35"/>
            {/* traveling pulse */}
            <path d={d} fill="none" stroke="#ffffff"
              strokeWidth="1.6" strokeDasharray="3 60"
              strokeLinecap="round" filter="url(#bsvgcGlow)">
              <animate attributeName="stroke-dashoffset"
                from="63" to="0"
                dur={`${2 + (i % 5) * 0.6}s`}
                begin={`${-(i * 0.13)}s`}
                repeatCount="indefinite"/>
            </path>
          </g>
        ))}
      </g>

      {/* Nodes */}
      <g style={{ mixBlendMode: "screen" }}>
        {NODES.map((n, i) => {
          const cycle = 1.6 + (i % 5) * 0.3;
          return (
            <g key={i}>
              {/* Halo */}
              <circle cx={n.x} cy={n.y} r="9" fill="url(#bsvgcNode)" opacity="0.5">
                <animate attributeName="r" values="6;12;6" dur={`${cycle}s`}
                  begin={`${-i * 0.18}s`} repeatCount="indefinite"/>
                <animate attributeName="opacity" values="0.3;0.8;0.3" dur={`${cycle}s`}
                  begin={`${-i * 0.18}s`} repeatCount="indefinite"/>
              </circle>
              {/* Core */}
              <circle cx={n.x} cy={n.y} r="1.6" fill="#ffffff" filter="url(#bsvgcGlow)">
                <animate attributeName="r" values="1.2;2.4;1.2" dur={`${cycle}s`}
                  begin={`${-i * 0.18}s`} repeatCount="indefinite"/>
              </circle>
            </g>
          );
        })}
      </g>
    </svg>
  );
}

/* ─────────────────────────────────────────────────────────────────
   VARIANT C — Wireframe + glow hybrid
   Clean SVG silhouette with soft volumetric inside, key arcs on top.
   ───────────────────────────────────────────────────────────────── */

function BrainWireframe() {
  const arcs = [SULCUS_LATERAL, SULCUS_CENTRAL, SULCUS_PARIETOOCC, SULCUS_OCC_1];

  return (
    <svg viewBox={BRAIN_VIEW} className="bsvg bsvg--wireframe" aria-hidden="true">
      <defs>
        <radialGradient id="bsvgwFill" cx="40%" cy="40%" r="70%">
          <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.32"/>
          <stop offset="40%" stopColor="var(--accent)" stopOpacity="0.12"/>
          <stop offset="100%" stopColor="var(--accent)" stopOpacity="0"/>
        </radialGradient>
        <radialGradient id="bsvgwAcc2" cx="70%" cy="70%" r="50%">
          <stop offset="0%" stopColor="var(--accent-2)" stopOpacity="0.25"/>
          <stop offset="100%" stopColor="var(--accent-2)" stopOpacity="0"/>
        </radialGradient>
        <filter id="bsvgwGlow" x="-30%" y="-30%" width="160%" height="160%">
          <feGaussianBlur stdDeviation="2"/>
          <feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge>
        </filter>
        <filter id="bsvgwSoft" x="-50%" y="-50%" width="200%" height="200%">
          <feGaussianBlur stdDeviation="10"/>
        </filter>
      </defs>

      {/* Volumetric fills */}
      <path d={CEREBRUM_OUTLINE} fill="url(#bsvgwFill)"/>
      <path d={CEREBRUM_OUTLINE} fill="url(#bsvgwAcc2)"/>
      <path d={CEREBELLUM_OUTLINE} fill="url(#bsvgwFill)"/>
      <ellipse cx="200" cy="170" rx="170" ry="120"
        fill="var(--accent)" opacity="0.05" filter="url(#bsvgwSoft)"/>

      {/* Crisp wireframe outlines */}
      <path d={CEREBRUM_OUTLINE} fill="none"
        stroke="var(--accent)" strokeWidth="1.6" filter="url(#bsvgwGlow)"/>
      <path d={CEREBELLUM_OUTLINE} fill="none"
        stroke="var(--accent)" strokeWidth="1.4" filter="url(#bsvgwGlow)"/>
      <path d={BRAINSTEM_OUTLINE} fill="none"
        stroke="var(--accent)" strokeWidth="1.2" strokeOpacity="0.7"/>

      {/* A few iconic interior arcs */}
      <g stroke="var(--accent)" fill="none" strokeWidth="1.0" strokeOpacity="0.55">
        <path d={SULCUS_LATERAL}/>
        <path d={SULCUS_CENTRAL}/>
      </g>

      {/* Synaptic arcs with traveling pulses */}
      <g style={{ mixBlendMode: "screen" }}>
        {arcs.map((d, i) => (
          <g key={i}>
            <path d={d} fill="none" stroke="var(--accent)"
              strokeWidth="0.8" strokeOpacity="0.4"/>
            <path d={d} fill="none" stroke="#ffffff"
              strokeWidth="2" strokeDasharray="10 200"
              strokeLinecap="round" filter="url(#bsvgwGlow)">
              <animate attributeName="stroke-dashoffset"
                from="210" to="0"
                dur={`${2.6 + i * 0.5}s`} begin={`${-i * 0.7}s`}
                repeatCount="indefinite"/>
            </path>
          </g>
        ))}
      </g>

      {/* Ambient firing spots */}
      <g style={{ mixBlendMode: "screen" }}>
        {[
          [110, 130], [180, 95], [260, 110], [310, 165], [150, 195],
          [225, 130], [275, 200], [275, 270], [100, 175],
        ].map(([x, y], i) => (
          <circle key={i} cx={x} cy={y} r="0" fill="#fff" filter="url(#bsvgwGlow)">
            <animate attributeName="r"
              values="0;3.5;0" dur={`${1.5 + (i % 3) * 0.3}s`}
              begin={`${-i * 0.27}s`} repeatCount="indefinite"/>
            <animate attributeName="opacity"
              values="0;1;0" dur={`${1.5 + (i % 3) * 0.3}s`}
              begin={`${-i * 0.27}s`} repeatCount="indefinite"/>
          </circle>
        ))}
      </g>
    </svg>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Switcher
   ───────────────────────────────────────────────────────────────── */

function BrainSVG({ variant = "anatomical" }) {
  if (variant === "constellation") return <BrainConstellation/>;
  if (variant === "wireframe") return <BrainWireframe/>;
  return <BrainAnatomical/>;
}

Object.assign(window, { BrainSVG, BrainAnatomical, BrainConstellation, BrainWireframe });
