/* global React, Kicker, LimeCheck, TopoLines, RecruitButton, useBreakpoint */

// Scalloped wax-seal SVG — matches the envelope's seal (deep navy, organic drip edges, dotted border, embossed number).
// Seal sits upright so the number reads straight; gets a subtle scale on hover instead of a tilt.
function WaxSeal({ number, hover, size = 96 }) {
  const cx = 50, cy = 50;
  // Procedural organic edge: 5 gentle lobes + a faster micro-wobble. Upright (no offset), so the number stays straight.
  const N = 64;
  const radii = Array.from({ length: N }, (_, i) => {
    const t = (i / N) * Math.PI * 2;
    return 44.8 + 2.6 * Math.sin(t * 5 + 0.35) + 0.9 * Math.sin(t * 11 + 1.7);
  });
  // Build smooth closed path through points.
  const pts = radii.map((r, i) => {
    const a = (i / N) * Math.PI * 2 - Math.PI / 2;
    return [cx + Math.cos(a) * r, cy + Math.sin(a) * r];
  });
  const line = pts.map((p, i) => (i === 0 ? 'M' : 'L') + p[0].toFixed(2) + ',' + p[1].toFixed(2)).join(' ') + ' Z';

  // Dotted rope border (24 dots around r=33)
  const dots = [];
  const DOT_N = 26;
  for (let i = 0; i < DOT_N; i++) {
    const a = (i / DOT_N) * Math.PI * 2;
    dots.push([cx + Math.cos(a) * 33, cy + Math.sin(a) * 33]);
  }

  return (
    <div style={{
      position: 'absolute', top: -size / 2, left: '50%',
      marginLeft: -size / 2,
      width: size, height: size,
      transform: hover ? 'scale(1.12)' : 'scale(1)',
      transition: 'transform 340ms cubic-bezier(0.2, 0.8, 0.2, 1)',
      filter: hover
        ? 'drop-shadow(0 18px 22px rgba(7,19,38,0.7)) drop-shadow(0 4px 6px rgba(0,0,0,0.5)) drop-shadow(0 0 18px rgba(41,92,170,0.5))'
        : 'drop-shadow(0 10px 14px rgba(7,19,38,0.6)) drop-shadow(0 2px 3px rgba(0,0,0,0.45))',
      pointerEvents: 'none',
    }}>
      <svg viewBox="0 0 100 100" width={size} height={size} style={{ display: 'block' }}>
        <defs>
          {/* Body: deep navy with strong top-left highlight falling to dark bottom-right */}
          <radialGradient id={`waxBody-${number}`} cx="30%" cy="24%" r="82%">
            <stop offset="0%"  stopColor="#4F82C4"/>
            <stop offset="18%" stopColor="#2C549A"/>
            <stop offset="48%" stopColor="#15326A"/>
            <stop offset="80%" stopColor="#091A40"/>
            <stop offset="100%" stopColor="#030A1E"/>
          </radialGradient>
          {/* Specular sheen */}
          <radialGradient id={`waxHL-${number}`} cx="28%" cy="22%" r="32%">
            <stop offset="0%"  stopColor="rgba(220,235,255,0.75)"/>
            <stop offset="40%" stopColor="rgba(180,210,255,0.25)"/>
            <stop offset="100%" stopColor="rgba(255,255,255,0)"/>
          </radialGradient>
          {/* Inner debossed well — darker inside */}
          <radialGradient id={`waxWell-${number}`} cx="42%" cy="40%" r="55%">
            <stop offset="0%"  stopColor="#0A1A3C"/>
            <stop offset="100%" stopColor="#040A1C"/>
          </radialGradient>
          {/* Subtle surface speckle for matte look */}
          <filter id={`waxNoise-${number}`}>
            <feTurbulence type="fractalNoise" baseFrequency="2.4" numOctaves="2" seed={Number(number)}/>
            <feColorMatrix values="0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 0.08 0"/>
            <feComposite in2="SourceGraphic" operator="in"/>
          </filter>
        </defs>

        {/* Main organic blob */}
        <path d={line} fill={`url(#waxBody-${number})`} stroke="rgba(0,0,0,0.5)" strokeWidth="0.5"/>

        {/* Noise overlay for matte texture */}
        <path d={line} filter={`url(#waxNoise-${number})`} opacity="0.6"/>

        {/* Outer debossed ring (inner edge shadow) */}
        <circle cx="50" cy="50" r="36" fill="none" stroke="rgba(0,0,0,0.35)" strokeWidth="1.4"/>
        <circle cx="50" cy="50" r="36" fill="none" stroke="rgba(120,160,220,0.2)" strokeWidth="0.6" transform="translate(-0.4,-0.4)"/>

        {/* Dotted rope border */}
        {dots.map((p, i) => (
          <circle key={i} cx={p[0]} cy={p[1]} r="0.75" fill="rgba(0,0,0,0.55)"/>
        ))}

        {/* Inner debossed well (circle holding the number) */}
        <circle cx="50" cy="50" r="28" fill={`url(#waxWell-${number})`} stroke="rgba(0,0,0,0.4)" strokeWidth="0.7"/>
        {/* Top highlight rim on the well */}
        <path d="M 24 50 A 26 26 0 0 1 76 50" fill="none" stroke="rgba(120,160,220,0.22)" strokeWidth="0.6" transform="translate(0,-1)"/>

        {/* Drop shadow under number */}
        <text x="50" y="61.5" textAnchor="middle"
          fontFamily='"Lato", sans-serif' fontWeight="900" fontSize="30"
          fill="rgba(0,0,0,0.55)"
          style={{ letterSpacing: '-0.02em' }}>
          {number}
        </text>
        {/* Bright white number */}
        <text x="50" y="60" textAnchor="middle"
          fontFamily='"Lato", sans-serif' fontWeight="900" fontSize="30"
          fill="#FFFFFF"
          style={{ letterSpacing: '-0.02em' }}>
          {number}
        </text>

        {/* Global specular sheen on top-left */}
        <path d={line} fill={`url(#waxHL-${number})`}/>
      </svg>
    </div>
  );
}

const TRAIL_STEPS = [
  { n: '01', icon: '🧭', t: 'Orientation',            b: 'What annuities really are, and where they fit in a retirement income plan — without the jargon.' },
  { n: '02', icon: '🏕', t: 'MYGAs 101',               b: 'Your easiest entry point to growth — with principal protection your clients already want.' },
  { n: '03', icon: '⛰', t: 'FIAs Made Simple',        b: 'No jargon, no overwhelm — just clarity on how fixed-indexed annuities actually work.' },
  { n: '04', icon: '🔭', t: 'Opportunity Spotting',    b: 'How to recognize qualified retirement savings and the clients already sitting on them.' },
  { n: '05', icon: '🗣', t: 'Cross-Sell Language',     b: 'Natural ways to shift the conversation from health to wealth without breaking trust.' },
  { n: '06', icon: '🛡', t: 'Objection Handling',      b: 'What to say when clients hesitate — compliant, client-first, rehearsed answers.' },
  { n: '07', icon: '📐', t: 'Quoting + Presenting',    b: 'Show value without confusion. Run your first live quote and walk it through like a pro.' },
  { n: '08', icon: '📜', t: 'Apps + Process',          b: 'How to write, submit, and issue policies — with suitability and back-office handoff built in.' },
  { n: '09', icon: '🔦', t: 'Case Walkthroughs',       b: 'Real examples from real agents. See the full arc from first question to funded case.' },
  { n: '10', icon: '🚩', t: 'Your First Appointments', b: 'Scripts, checklists, and a support team behind you when you sit down with your first client.' },
];

// Individual parchment step card. Rich hover: lift, slight rotate, lime rope animates, wax-seal number flips.
function StepCard({ step, index, variant }) {
  const [hover, setHover] = React.useState(false);
  const isBold = variant === 'bold';
  const tilt = index % 2 === 0 ? -0.4 : 0.4; // subtle parchment skew alternation

  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        position: 'relative',
        background: hover
              ? 'linear-gradient(180deg, #FAF6E8 0%, #F0E4C4 100%)'
              : 'linear-gradient(180deg, #F5EFDC 0%, #EADFC2 100%)',
        border: '1px solid rgba(61,42,21,0.22)',
        borderRadius: 18,
        padding: '70px 24px 26px',
        minHeight: 280,
        textAlign: 'center',
        cursor: 'pointer',
        transform: hover
          ? `translateY(-10px) rotate(0deg) scale(1.015)`
          : `translateY(0) rotate(${tilt}deg)`,
        boxShadow: hover
          ? '0 24px 48px rgba(15,35,65,0.28), 0 0 0 1px rgba(186,218,85,0.3), inset 0 0 80px rgba(61,42,21,0.06)'
          : '0 6px 18px rgba(15,35,65,0.10), inset 0 0 40px rgba(61,42,21,0.04)',
        transition: 'all 320ms cubic-bezier(0.2, 0.8, 0.2, 1)',
        overflow: 'visible',
      }}
    >
      {/* Wax-seal number badge — scalloped blob matching envelope seal */}
      <WaxSeal number={step.n} hover={hover} />

      {/* Torn paper corner accent, top-right */}
      <svg aria-hidden width="60" height="60" viewBox="0 0 60 60" style={{
        position: 'absolute', top: 0, right: 0, opacity: hover ? 0.5 : 0.3,
        transition: 'opacity 320ms ease',
      }}>
        <path d="M60 0 L60 60 L0 0 Z" fill="rgba(61,42,21,0.08)"/>
        <path d="M60 0 L20 0 L60 40 Z" fill="rgba(61,42,21,0.04)"/>
      </svg>

      {/* Lime rope on hover — animated trail */}
      <svg aria-hidden width="100%" height="8" viewBox="0 0 200 8" preserveAspectRatio="none" style={{
        position: 'absolute', left: 0, bottom: 0,
        opacity: hover ? 1 : 0,
        transition: 'opacity 320ms ease',
      }}>
        <path d="M0 4 Q 25 0, 50 4 T 100 4 T 150 4 T 200 4"
              fill="none" stroke="#BADA55" strokeWidth="2" strokeDasharray="6 4"
              strokeLinecap="round">
          <animate attributeName="stroke-dashoffset" from="0" to="-20" dur="1.2s" repeatCount="indefinite"/>
        </path>
      </svg>

      <div style={{ fontSize: 32, marginTop: 6, marginBottom: 12, filter: hover ? 'none' : 'saturate(0.85)', transition: 'filter 320ms ease' }}>
        {step.icon}
      </div>
      <h3 style={{
        color: '#0F2341', fontWeight: 900, margin: '0 0 10px',
        fontSize: 19, fontFamily: '"Lato", sans-serif', letterSpacing: '-0.005em',
      }}>{step.t}</h3>
      <p style={{ color: '#5A4329', fontSize: 14.5, lineHeight: 1.6, margin: 0 }}>{step.b}</p>

      {/* Subtle "checkpoint reached" flag, appears on hover */}
      <div style={{
        position: 'absolute', bottom: 14, left: '50%', transform: 'translateX(-50%)',
        fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', fontWeight: 800,
        color: '#1495B9',
        opacity: hover ? 1 : 0,
        transition: 'opacity 320ms ease',
        whiteSpace: 'nowrap',
      }}>
        ✦ Station {step.n}
      </div>
    </div>
  );
}

// Map showpiece — the map floats above parchment, with a label pointing to it.
function MapShowpiece({ imgBase }) {
  return (
    <div style={{
      position: 'relative',
      margin: '16px 0 72px',
      padding: '0 12px',
    }}>
      <img
        src={`${imgBase}/basecamp-treasure-map.png`}
        alt="BaseCamp treasure map — the 10-station training route"
        style={{
          width: '100%', height: 'auto', display: 'block',
          filter: 'drop-shadow(0 28px 50px rgba(15,35,65,0.28))',
          animation: 'bc-sway 6s ease-in-out infinite',
        }}
      />
      <style>{`
        @keyframes bc-sway {
          0%, 100% { transform: rotate(-0.4deg) translateY(0); }
          50%      { transform: rotate(0.4deg) translateY(-4px); }
        }
      `}</style>
    </div>
  );
}

// "Open Your Invitation to Apply Today" block — spans the empty slots in the trail grid.
// Headline above a large, floating envelope; the whole block clicks through to apply.html.
function EnvelopeCTA({ imgBase, span = 2, bp = 'desktop' }) {
  const [hover, setHover] = React.useState(false);
  const isNarrow = bp === 'mobile';
  return (
    <a
      href="apply.html"
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      aria-label="Open your Invitation to Apply Today"
      style={{
        gridColumn: `span ${span}`,
        display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center',
        position: 'relative',
        padding: '24px 20px 8px',
        minHeight: 280,
        background: 'transparent',
        cursor: 'pointer',
        textDecoration: 'none',
        textAlign: 'center',
        transform: hover ? 'translateY(-4px)' : 'translateY(0)',
        transition: 'transform 320ms cubic-bezier(0.2, 0.8, 0.2, 1)',
        font: 'inherit',
      }}
    >
      {/* Headline — single line on tablet/desktop, wraps on mobile to avoid overflow. */}
      <div style={{
        fontFamily: '"Lato", sans-serif', fontWeight: 900,
        fontSize: 'clamp(18px, 1.9vw, 26px)', lineHeight: 1.15,
        letterSpacing: '-0.005em', color: '#0F2341',
        whiteSpace: isNarrow ? 'normal' : 'nowrap',
        maxWidth: isNarrow ? '18ch' : 'none',
        marginBottom: 20,
      }}>
        Open your Invitation <span style={{ color: '#1495B9' }}>to Apply Today</span>
      </div>

      {/* Envelope — larger, continuous float animation. Hover deepens the shadow. */}
      <div style={{
        position: 'relative',
        width: '100%', maxWidth: 440,
        animation: 'bc-invite-float 4.5s ease-in-out infinite',
        filter: hover
          ? 'drop-shadow(0 30px 52px rgba(15,35,65,0.5))'
          : 'drop-shadow(0 16px 28px rgba(15,35,65,0.35))',
        transition: 'filter 320ms ease',
      }}>
        <img
          src={`${imgBase}/basecamp-treasure-envelope.png`}
          alt=""
          style={{ width: '100%', height: 'auto', display: 'block' }}
        />
        {/* Subtle lime glow behind seal on hover */}
        <div aria-hidden style={{
          position: 'absolute', inset: 0,
          background: 'radial-gradient(circle at 62% 50%, rgba(186,218,85,0.4) 0%, transparent 32%)',
          opacity: hover ? 1 : 0,
          transition: 'opacity 300ms ease',
          pointerEvents: 'none',
          mixBlendMode: 'screen',
        }}/>
      </div>

      <style>{`
        @keyframes bc-invite-float {
          0%, 100% { transform: rotate(-2deg) translateY(0); }
          50%      { transform: rotate(1.5deg) translateY(-10px); }
        }
      `}</style>
    </a>
  );
}

function TrailSection({ variant, imgBase }) {
  const isBold = variant === 'bold';
  const bp = useBreakpoint();
  const gridCols = bp === 'mobile' ? '1fr' : bp === 'tablet' ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)';
  // Invitation block: always fill the "empty slots" — spans 2 on desktop (takes the last 2 of 4), 2 on tablet (full row), 1 on mobile.
  const inviteSpan = bp === 'mobile' ? 1 : 2;
  return (
    <section id="trail" style={{
      padding: '96px 24px 120px',
      background: 'linear-gradient(180deg, #FAF6E8 0%, #F0E4C4 100%)',
      position: 'relative',
      overflow: 'hidden',
    }}>
      <TopoLines opacity={0.12} color="#3D2A15"/>
      <div style={{ maxWidth: 1200, margin: '0 auto', position: 'relative' }}>
        <Kicker color="#3D2A15">
          {isBold ? '✦ The Expedition Route · 10 stations' : 'The 10-Week Trail'}
        </Kicker>
        <h2 style={{
          fontFamily: '"Lato", sans-serif',
          fontSize: 'clamp(44px, 5vw, 76px)', fontWeight: 900,
          color: '#0F2341', margin: '0 0 16px', lineHeight: 1.02,
          letterSpacing: '-0.02em', maxWidth: '18ch',
          textShadow: '0 1px 0 rgba(255,255,255,0.4)',
        }}>
          {isBold
            ? <>10 stations. <span style={{ color: '#1495B9' }}>One summit.</span></>
            : <>10 weeks of content. <span style={{ color: '#1495B9' }}>One summit.</span></>
          }
        </h2>
        <p style={{ fontSize: 18, color: '#5A4329', maxWidth: '64ch', margin: '0 0 24px', lineHeight: 1.55 }}>
          {isBold
            ? "You don't get a binder. You get a route, a guide, and a cohort climbing beside you. Here's the full map — and the stations you'll pass through."
            : 'Each week builds on the last — from what annuities are, to sitting down with your first client ready to fund one.'
          }
        </p>

        <MapShowpiece imgBase={imgBase}/>

        <div style={{
          display: 'grid',
          gridTemplateColumns: gridCols,
          gap: 28,
          marginTop: 0,
          paddingTop: 20,
        }}>
          {TRAIL_STEPS.map((s, i) => <StepCard key={s.n} step={s} index={i} variant={variant}/>)}
          <EnvelopeCTA imgBase={imgBase} span={inviteSpan} bp={bp}/>
        </div>
      </div>
    </section>
  );
}

window.RecruitTrail = TrailSection;
